19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Analysis/GlobalsModRef.h"
22#include "llvm/Analysis/RuntimeLibcallInfo.h"
23#include "llvm/Analysis/TargetLibraryInfo.h"
24#include "llvm/Analysis/TargetTransformInfo.h"
25#include "llvm/BinaryFormat/ELF.h"
26#include "llvm/Bitcode/BitcodeReader.h"
27#include "llvm/Bitcode/BitcodeWriter.h"
28#include "llvm/Bitcode/BitcodeWriterPass.h"
29#include "llvm/CodeGen/MachineModuleInfo.h"
30#include "llvm/CodeGen/TargetSubtargetInfo.h"
31#include "llvm/Config/llvm-config.h"
32#include "llvm/Frontend/Driver/CodeGenOptions.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DebugInfo.h"
35#include "llvm/IR/LLVMRemarkStreamer.h"
36#include "llvm/IR/LegacyPassManager.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/ModuleSummaryIndex.h"
39#include "llvm/IR/PassManager.h"
40#include "llvm/IR/Verifier.h"
41#include "llvm/IRPrinter/IRPrintingPasses.h"
42#include "llvm/LTO/LTOBackend.h"
43#include "llvm/MC/MCTargetOptions.h"
44#include "llvm/MC/TargetRegistry.h"
45#include "llvm/Object/OffloadBinary.h"
46#include "llvm/Passes/PassBuilder.h"
47#include "llvm/Passes/RunCodeGen.h"
48#include "llvm/Passes/StandardInstrumentations.h"
49#include "llvm/Plugins/PassPlugin.h"
50#include "llvm/ProfileData/InstrProfCorrelator.h"
51#include "llvm/Support/BuryPointer.h"
52#include "llvm/Support/CodeGen.h"
53#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/Support/IOSandbox.h"
56#include "llvm/Support/MemoryBuffer.h"
57#include "llvm/Support/PrettyStackTrace.h"
58#include "llvm/Support/Program.h"
59#include "llvm/Support/TimeProfiler.h"
60#include "llvm/Support/Timer.h"
61#include "llvm/Support/ToolOutputFile.h"
62#include "llvm/Support/VirtualFileSystem.h"
63#include "llvm/Support/raw_ostream.h"
64#include "llvm/Target/TargetMachine.h"
65#include "llvm/Target/TargetOptions.h"
66#include "llvm/TargetParser/SubtargetFeature.h"
67#include "llvm/TargetParser/Triple.h"
68#include "llvm/Transforms/HipStdPar/HipStdPar.h"
69#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
70#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
71#include "llvm/Transforms/IPO/LowerTypeTests.h"
72#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
73#include "llvm/Transforms/InstCombine/InstCombine.h"
74#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
75#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
76#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
77#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
78#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
79#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
80#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
81#include "llvm/Transforms/Instrumentation/KCFI.h"
82#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
83#include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
84#include "llvm/Transforms/Instrumentation/MemProfUse.h"
85#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
86#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
87#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
88#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
89#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
90#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
91#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
92#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
93#include "llvm/Transforms/ObjCARC.h"
94#include "llvm/Transforms/Scalar/EarlyCSE.h"
95#include "llvm/Transforms/Scalar/GVN.h"
96#include "llvm/Transforms/Scalar/JumpThreading.h"
97#include "llvm/Transforms/Utils/AssignGUID.h"
98#include "llvm/Transforms/Utils/Debugify.h"
99#include "llvm/Transforms/Utils/DynamicDebugging.h"
100#include "llvm/Transforms/Utils/ModuleUtils.h"
104using namespace clang;
107#define HANDLE_EXTENSION(Ext) \
108 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
109#include "llvm/Support/Extension.def"
114 "sanitizer-early-opt-ep", cl::Optional,
115 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
120 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
122 "Function attribute to apply to cold functions as determined by PGO"),
123 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
124 "Default (no attribute)"),
125 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
126 "Mark cold functions with optsize."),
127 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
128 "Mark cold functions with minsize."),
129 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
130 "Mark cold functions with optnone.")));
132LLVM_ABI
extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
142 ? llvm::driver::getDefaultProfileGenName()
144 if (CodeGenOpts.ContinuousProfileSync)
151class EmitAssemblyHelper {
152 CompilerInstance &CI;
153 DiagnosticsEngine &Diags;
154 const CodeGenOptions &CodeGenOpts;
155 const clang::TargetOptions &TargetOpts;
156 const LangOptions &LangOpts;
157 llvm::Module *TheModule;
158 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
160 std::unique_ptr<raw_pwrite_stream> OS;
164 TargetIRAnalysis getTargetIRAnalysis()
const {
166 return TM->getTargetIRAnalysis();
168 return TargetIRAnalysis();
179 void CreateTargetMachine(
bool MustCreateTM);
181 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
183 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
184 llvm::sys::fs::OF_None);
186 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
192 void RunOptimizationPipeline(
193 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
194 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
196 std::unique_ptr<raw_pwrite_stream> &OS,
197 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
198 void TimeCodegenPasses(llvm::function_ref<
void()> RunPasses);
205 bool shouldEmitRegularLTOSummary()
const {
206 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
207 TargetTriple.getVendor() != llvm::Triple::Apple;
213 bool shouldEmitUnifiedLTOModueFlag()
const {
214 return CodeGenOpts.UnifiedLTO &&
215 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
219 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
221 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
222 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
223 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
224 TheModule(M), VFS(std::move(VFS)),
225 TargetTriple(TheModule->getTargetTriple()) {}
227 ~EmitAssemblyHelper() {
228 if (CodeGenOpts.DisableFree)
229 BuryPointer(std::move(TM));
232 std::unique_ptr<TargetMachine> TM;
235 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
236 BackendConsumer *BC);
240static SanitizerCoverageOptions
242 SanitizerCoverageOptions Opts;
244 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
245 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
246 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
247 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
248 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
249 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
250 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
251 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
252 Opts.TracePCEntryExit = CGOpts.SanitizeCoverageTracePCEntryExit;
253 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
254 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
255 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
256 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
257 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
258 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
259 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
260 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
261 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
262 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
266static SanitizerBinaryMetadataOptions
268 SanitizerBinaryMetadataOptions Opts;
269 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
270 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
271 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
280 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
282 switch (
T.getObjectFormat()) {
287 return !CGOpts.DisableIntegratedAS;
289 llvm::report_fatal_error(
"ASan not implemented for GOFF");
291 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
293 case Triple::DXContainer:
295 case Triple::UnknownObjectFormat:
301static std::optional<llvm::CodeModel::Model>
303 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
304 .Case(
"tiny", llvm::CodeModel::Tiny)
305 .Case(
"small", llvm::CodeModel::Small)
306 .Case(
"kernel", llvm::CodeModel::Kernel)
307 .Case(
"medium", llvm::CodeModel::Medium)
308 .Case(
"large", llvm::CodeModel::Large)
309 .Cases({
"default",
""}, ~1u)
311 assert(CodeModel != ~0u &&
"invalid code model!");
312 if (CodeModel == ~1u)
314 return static_cast<llvm::CodeModel::Model
>(CodeModel);
319 return CodeGenFileType::ObjectFile;
321 return CodeGenFileType::Null;
324 return CodeGenFileType::AssemblyFile;
334 StringRef MainFilename,
337 return std::string{};
339 std::string FlatCmdLine;
340 raw_string_ostream OS(FlatCmdLine);
341 bool PrintedOneArg =
false;
342 if (!StringRef(Args[0]).
contains(
"-cc1")) {
343 llvm::sys::printArg(OS,
"-cc1",
true);
344 PrintedOneArg =
true;
346 for (
unsigned i = 0; i < Args.size(); i++) {
347 StringRef Arg = Args[i];
350 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
354 if (Arg.starts_with(
"-object-file-name"))
362 if (Arg == MainFilename || llvm::is_contained(InputFiles, Arg))
365 if (Arg.starts_with(
"-fmessage-length"))
369 llvm::sys::printArg(OS, Arg,
true);
370 PrintedOneArg =
true;
377 llvm::TargetOptions &Options) {
382 switch (LangOpts.getThreadModel()) {
384 Options.ThreadModel = llvm::ThreadModel::POSIX;
387 Options.ThreadModel = llvm::ThreadModel::Single;
391 Options.MCOptions.BinutilsVersion =
392 llvm::MCTargetOptions::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
393 Options.UseInitArray = CodeGenOpts.UseInitArray;
394 Options.MCOptions.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
400 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
402 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
404 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
406 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
408 Options.ExceptionModel = llvm::ExceptionHandling::Emscripten;
410 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
412 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
414 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
415 .Case(
"all", llvm::BasicBlockSection::All)
416 .StartsWith(
"list=", llvm::BasicBlockSection::List)
417 .Case(
"none", llvm::BasicBlockSection::None)
418 .Default(llvm::BasicBlockSection::None);
420 if (Options.BBSections == llvm::BasicBlockSection::List) {
421 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
425 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
426 << MBOrErr.getError().message();
429 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
432 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
433 Options.EnableStaticDataPartitioning =
434 CodeGenOpts.PartitionStaticDataSections;
435 Options.FunctionSections = CodeGenOpts.FunctionSections;
436 Options.DataSections = CodeGenOpts.DataSections;
437 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
438 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
439 Options.UniqueBasicBlockSectionNames =
440 CodeGenOpts.UniqueBasicBlockSectionNames;
441 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
442 Options.TLSSize = CodeGenOpts.TLSSize;
443 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
444 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
445 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
446 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
448 Options.EmitAddrsig = CodeGenOpts.Addrsig;
449 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
450 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
451 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
452 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
453 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
454 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
455 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
458 Options.Hotpatch = CodeGenOpts.HotPatch;
459 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
460 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
462 convertDriverVectorLibraryToVectorLibrary(CodeGenOpts.getVecLib());
464 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
466 Options.SwiftAsyncFramePointer =
467 SwiftAsyncFramePointerMode::DeploymentBased;
471 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
475 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
480 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
481 Options.MCOptions.EmitCompactUnwindNonCanonical =
482 CodeGenOpts.EmitCompactUnwindNonCanonical;
483 Options.MCOptions.EmitSFrameUnwind = CodeGenOpts.EmitSFrameUnwind;
484 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
485 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
486 Options.MCOptions.MCUseDwarfDirectory =
487 CodeGenOpts.NoDwarfDirectoryAsm
488 ? llvm::MCTargetOptions::DisableDwarfDirectory
489 : llvm::MCTargetOptions::EnableDwarfDirectory;
490 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
491 Options.MCOptions.MCIncrementalLinkerCompatible =
492 CodeGenOpts.IncrementalLinkerCompatible;
493 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
494 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
495 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
496 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
497 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
498 Options.MCOptions.Crel = CodeGenOpts.Crel;
499 Options.MCOptions.RelocSectionSym = CodeGenOpts.getRelocSectionSym();
500 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
501 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
502 Options.MCOptions.CompressDebugSections =
503 CodeGenOpts.getCompressDebugSections();
504 if (CodeGenOpts.OutputAsmVariant != 3)
505 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
506 Options.MCOptions.ABIName = TargetOpts.
ABI;
507 for (
const auto &Entry : HSOpts.UserEntries)
508 if (!Entry.IsFramework &&
512 Options.MCOptions.IASSearchPaths.push_back(
513 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
514 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
521 InputFiles.push_back(Input.getFile());
525 Options.MCOptions.PPCUseFullRegisterNames =
526 CodeGenOpts.PPCUseFullRegisterNames;
527 Options.MisExpect = CodeGenOpts.MisExpect;
532static std::optional<GCOVOptions>
543 Options.NoRedZone = CodeGenOpts.DisableRedZone;
546 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
550static std::optional<InstrProfOptions>
555 InstrProfOptions Options;
556 Options.NoRedZone = CodeGenOpts.DisableRedZone;
560 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
565 vfs::FileSystem &VFS) {
567 BackendArgs.push_back(
"clang");
569 BackendArgs.push_back(
"-debug-pass");
570 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
573 BackendArgs.push_back(
"-limit-float-precision");
580 if (BackendArgs.size() == 1)
582 BackendArgs.push_back(
nullptr);
586 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
591void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
594 const llvm::Triple &Triple = TheModule->getTargetTriple();
595 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
598 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
602 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
603 std::string FeaturesStr =
606 std::optional<CodeGenOptLevel> OptLevelOrNone =
607 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
608 assert(OptLevelOrNone &&
"Invalid optimization level!");
609 CodeGenOptLevel OptLevel = *OptLevelOrNone;
611 llvm::TargetOptions Options;
614 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
615 Options, RM, CM, OptLevel));
621 switch (Opts.OptimizationLevel) {
623 llvm_unreachable(
"Invalid optimization level!");
626 return OptimizationLevel::O0;
629 return OptimizationLevel::O1;
632 return OptimizationLevel::O2;
635 return OptimizationLevel::O3;
642 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
643 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
644 TargetTriple.isARM() || TargetTriple.isThumb() ||
645 TargetTriple.getArch() == llvm::Triple::hexagon)
649 PB.registerOptimizerLastEPCallback(
650 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
651 if (Level == OptimizationLevel::O0 &&
653 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
658 PB.registerPeepholeEPCallback(
659 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
660 if (Level != OptimizationLevel::O0 &&
662 FPM.addPass(KCFIPass());
669 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
670 ThinOrFullLTOPhase) {
674 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
680 MPM.addPass(SanitizerBinaryMetadataPass(
682 PB.getVirtualFileSystemPtr(),
686 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
688 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
691 MemorySanitizerOptions
options(TrackOrigins, Recover, CompileKernel,
692 CodeGenOpts.SanitizeMemoryParamRetval);
693 MPM.addPass(MemorySanitizerPass(
options));
694 if (Level != OptimizationLevel::O0) {
699 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
700 FunctionPassManager FPM;
701 FPM.addPass(EarlyCSEPass(
true ));
702 FPM.addPass(InstCombinePass());
703 FPM.addPass(JumpThreadingPass());
704 FPM.addPass(GVNPass());
705 FPM.addPass(InstCombinePass());
706 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
710 MSanPass(SanitizerKind::Memory,
false);
711 MSanPass(SanitizerKind::KernelMemory,
true);
713 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
714 MPM.addPass(ModuleThreadSanitizerPass());
715 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
719 MPM.addPass(TypeSanitizerPass());
721 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
722 MPM.addPass(NumericalStabilitySanitizerPass());
724 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
725 MPM.addPass(RealtimeSanitizerPass());
727 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
730 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
731 llvm::AsanDtorKind DestructorKind =
732 CodeGenOpts.getSanitizeAddressDtor();
733 AddressSanitizerOptions Opts;
734 Opts.CompileKernel = CompileKernel;
736 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
737 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
738 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
742 ASanPass(SanitizerKind::Address,
false);
743 ASanPass(SanitizerKind::KernelAddress,
true);
745 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
748 MPM.addPass(HWAddressSanitizerPass(
749 {CompileKernel, Recover,
750 CodeGenOpts.OptimizationLevel == 0}));
753 HWASanPass(SanitizerKind::HWAddress,
false);
754 HWASanPass(SanitizerKind::KernelHWAddress,
true);
756 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
758 PB.getVirtualFileSystemPtr()));
762 PB.registerOptimizerEarlyEPCallback(
763 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
764 ThinOrFullLTOPhase Phase) {
765 ModulePassManager NewMPM;
766 SanitizersCallback(NewMPM, Level, Phase);
767 if (!NewMPM.isEmpty()) {
769 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
770 MPM.addPass(std::move(NewMPM));
775 PB.registerOptimizerLastEPCallback(SanitizersCallback);
784 uint64_t AllowRuntimeCheckSkipHotCutoff =
789 SanitizerKind::Address | SanitizerKind::KernelAddress |
790 SanitizerKind::Thread | SanitizerKind::Memory |
791 SanitizerKind::KernelMemory | SanitizerKind::HWAddress |
792 SanitizerKind::KernelHWAddress);
795 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
797 LowerAllowSanitize) {
799 PB.registerOptimizerEarlyEPCallback(
800 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
801 ModulePassManager &MPM, OptimizationLevel Level,
802 ThinOrFullLTOPhase Phase) {
803 LowerAllowCheckPass::Options Opts;
805 if (ScaledCutoffs.has_value())
806 Opts.cutoffs = ScaledCutoffs.value();
807 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
809 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
814void EmitAssemblyHelper::RunOptimizationPipeline(
815 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
816 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
817 std::optional<PGOOptions> PGOOpt;
824 CodeGenOpts.DebugInfoForProfiling,
826 CodeGenOpts.AtomicProfileUpdate);
830 : PGOOptions::NoCSAction;
835 CodeGenOpts.DebugInfoForProfiling);
842 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
846 PGOOptions::NoAction, PGOOptions::NoCSAction,
848 else if (CodeGenOpts.PseudoProbeForProfiling)
850 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
852 CodeGenOpts.DebugInfoForProfiling,
true);
853 else if (CodeGenOpts.DebugInfoForProfiling)
855 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
861 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
864 assert(PGOOpt->Action != PGOOptions::IRInstr &&
865 PGOOpt->Action != PGOOptions::SampleUse &&
866 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
869 PGOOpt->CSAction = PGOOptions::CSIRInstr;
872 "", PGOOptions::NoAction,
874 CodeGenOpts.DebugInfoForProfiling);
877 TM->setPGOOption(PGOOpt);
879 PipelineTuningOptions PTO;
880 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
881 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
882 PTO.LoopFusion = CodeGenOpts.FuseLoops;
885 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
886 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
887 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
888 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
891 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
892 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
893 PTO.DevirtualizeSpeculatively = CodeGenOpts.DevirtualizeSpeculatively;
895 LoopAnalysisManager LAM;
896 FunctionAnalysisManager FAM;
897 CGSCCAnalysisManager CGAM;
898 ModuleAnalysisManager MAM;
900 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
901 PassInstrumentationCallbacks PIC;
902 PrintPassOptions PrintPassOpts;
903 PrintPassOpts.Indent = DebugPassStructure;
904 PrintPassOpts.SkipAnalyses = DebugPassStructure;
905 StandardInstrumentations SI(
906 TheModule->getContext(),
907 (CodeGenOpts.DebugPassManager || DebugPassStructure),
908 CodeGenOpts.VerifyEach, PrintPassOpts);
909 SI.registerCallbacks(PIC, &MAM);
913 switch (CodeGenOpts.getAssignmentTrackingMode()) {
914 case CodeGenOptions::AssignmentTrackingOpts::Forced:
915 PB.registerPipelineStartEPCallback(
916 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
917 MPM.addPass(AssignmentTrackingPass());
920 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
923 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
924 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
925 PB.registerPipelineStartEPCallback(
926 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
928 if (
Level != OptimizationLevel::O0)
929 MPM.addPass(AssignmentTrackingPass());
933 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
938 DebugifyEachInstrumentation Debugify;
939 DebugInfoPerPass DebugInfoBeforePass;
940 if (CodeGenOpts.EnableDIPreservationVerify) {
941 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
942 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
945 Debugify.setOrigDIVerifyBugsReportFilePath(
947 Debugify.registerCallbacks(PIC, MAM);
949#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
956 if (!F.getSubprogram())
958 for (BasicBlock &BB : F)
959 for (Instruction &I : BB)
960 if (!I.getDebugLoc())
961 I.setDebugLoc(DebugLoc::getCompilerGenerated());
966 for (
const std::unique_ptr<PassPlugin> &Plugin : CI.
getPassPlugins())
967 Plugin->registerPassBuilderCallbacks(PB);
970#define HANDLE_EXTENSION(Ext) \
971 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
972#include "llvm/Support/Extension.def"
976 std::unique_ptr<TargetLibraryInfoImpl> TLII(
977 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
978 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
981 PB.registerModuleAnalyses(MAM);
982 PB.registerCGSCCAnalyses(CGAM);
983 PB.registerFunctionAnalyses(FAM);
984 PB.registerLoopAnalyses(LAM);
985 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
987 ModulePassManager MPM;
989 if (CodeGenOpts.VerifyModule)
990 MPM.addPass(VerifierPass());
992 if (!CodeGenOpts.DisableLLVMPasses) {
997 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
998 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1000 if (LangOpts.ObjCAutoRefCount) {
1001 PB.registerPipelineStartEPCallback(
1002 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1003 if (
Level != OptimizationLevel::O0)
1005 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1007 PB.registerScalarOptimizerLateEPCallback(
1008 [](FunctionPassManager &FPM, OptimizationLevel
Level) {
1009 if (
Level != OptimizationLevel::O0)
1010 FPM.addPass(ObjCARCOptPass());
1020 if (IsThinLTOPostLink)
1021 PB.registerPipelineStartEPCallback(
1022 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1023 MPM.addPass(DropTypeTestsPass());
1028 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1029 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1030 OptimizationLevel
Level) {
1031 BoundsCheckingPass::Options Options;
1034 static_assert(SanitizerKind::SO_LocalBounds <=
1035 std::numeric_limits<
1036 decltype(Options.GuardKind)::value_type>
::max(),
1037 "Update type of llvm.allow.ubsan.check to represent "
1038 "SanitizerKind::SO_LocalBounds.");
1039 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1046 CodeGenOpts.SanitizeMinimalRuntime),
1050 static_cast<bool>(CodeGenOpts.SanitizeHandlerPreserveAllRegs),
1053 FPM.addPass(BoundsCheckingPass(Options));
1056 if (!IsThinLTOPostLink) {
1062 PB.registerPipelineStartEPCallback(
1063 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
1064 if (
Level == OptimizationLevel::O0 &&
1065 LangOpts.
Sanitize.
has(SanitizerKind::AllocToken)) {
1071 MPM.addPass(InferFunctionAttrsPass());
1076 if (std::optional<GCOVOptions> Options =
1078 PB.registerPipelineStartEPCallback(
1079 [
this, Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1083 if (std::optional<InstrProfOptions> Options =
1085 PB.registerPipelineStartEPCallback(
1086 [Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1087 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1093 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1094 OptimizationLevel
Level,
1095 ThinOrFullLTOPhase) {
1096 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1097 MPM.addPass(ModuleMemProfilerPass());
1101 if (CodeGenOpts.FatLTO) {
1102 MPM.addPass(PB.buildFatLTODefaultPipeline(
1103 Level, PrepareForThinLTO,
1104 PrepareForThinLTO || shouldEmitRegularLTOSummary(),
1105 CodeGenOpts.VerifyModule));
1106 }
else if (PrepareForThinLTO) {
1107 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(
Level));
1108 }
else if (PrepareForLTO) {
1109 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(
Level));
1111 MPM.addPass(PB.buildPerModuleDefaultPipeline(
Level));
1116 if (CodeGenOpts.LinkBitcodePostopt) {
1117 MPM.addPass(LinkInModulesPass(BC));
1118 MPM.addPass(AssignGUIDPass());
1121 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1122 LangOpts.HIPStdParInterposeAlloc)
1123 MPM.addPass(HipStdParAllocationInterpositionPass());
1131 MPM.addPass(VerifierPass());
1134 CodeGenOpts.FatLTO) {
1135 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1136 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1137 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1138 CodeGenOpts.EnableSplitLTOUnit);
1145 MPM.addPass(ThinLTOBitcodeWriterPass(
1146 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1148 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1155 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1156 if (EmitLTOSummary) {
1157 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1158 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1159 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1160 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1164 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1167 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1173 if (shouldEmitUnifiedLTOModueFlag() &&
1174 !TheModule->getModuleFlag(
"UnifiedLTO"))
1175 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1182 if (PrintPipelinePasses) {
1183 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1184 auto PassName = PIC.getPassNameForClassName(ClassName);
1185 return PassName.empty() ? ClassName : PassName;
1193 PrettyStackTraceString CrashInfo(
"Optimizer");
1194 llvm::TimeTraceScope TimeScope(
"Optimizer");
1200 MPM.run(*TheModule, MAM);
1206void EmitAssemblyHelper::RunCodegenPipeline(
1207 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1208 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1218 for (
const std::unique_ptr<llvm::PassPlugin> &Plugin : CI.
getPassPlugins()) {
1219 if (Plugin->invokePreCodeGenCallback(*TheModule, *TM, CGFT, *OS))
1229 TimeCodegenPasses([&]() {
1230 Error CodeGenError = runCodeGenPipeline(
1231 *TM, *TheModule, *OS, DwoOS, CGFT, PrintPipelinePasses.has_value(),
1232 !CodeGenOpts.VerifyModule,
false,
1235 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
1239void EmitAssemblyHelper::TimeCodegenPasses(
1240 llvm::function_ref<
void()> RunPasses) {
1241 PrettyStackTraceString CrashInfo(
"Code generation");
1242 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1245 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1254 std::unique_ptr<raw_pwrite_stream> OS,
1255 BackendConsumer *BC) {
1259 CreateTargetMachine(RequiresCodeGen);
1261 if (RequiresCodeGen && !TM)
1264 TheModule->setDataLayout(TM->createDataLayout());
1267 cl::PrintOptionValues();
1269 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1270 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1271 RunCodegenPipeline(Action, OS, DwoOS);
1281 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1282 std::string SampleProfile, std::string ProfileRemapping,
1287 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1288 ModuleToDefinedGVSummaries;
1289 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1296 FunctionImporter::ImportIDTable ImportIDs;
1297 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1298 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1301 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1302 return std::make_unique<CachedFileStream>(std::move(OS),
1303 CGOpts.ObjectFilenameForDebug);
1306 if (CGOpts.SaveTempsFilePrefix !=
"") {
1307 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1309 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1310 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1315 Conf.CPU = TOpts.CPU;
1317 Conf.MAttrs = TOpts.Features;
1318 Conf.RelocModel = CGOpts.RelocationModel;
1319 std::optional<CodeGenOptLevel> OptLevelOrNone =
1320 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1321 assert(OptLevelOrNone &&
"Invalid optimization level!");
1322 Conf.CGOptLevel = *OptLevelOrNone;
1323 Conf.OptLevel = CGOpts.OptimizationLevel;
1325 Conf.SampleProfile = std::move(SampleProfile);
1326 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1327 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1328 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1331 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1332 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1333 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1336 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1339 if (CGOpts.hasProfileCSIRInstr()) {
1340 Conf.RunCSIRInstr =
true;
1342 }
else if (CGOpts.hasProfileCSIRUse()) {
1343 Conf.RunCSIRInstr =
false;
1344 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1347 Conf.ProfileRemapping = std::move(ProfileRemapping);
1348 Conf.DebugPassManager = CGOpts.DebugPassManager;
1349 Conf.VerifyEach = CGOpts.VerifyEach;
1350 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1351 Conf.RemarksFilename = CGOpts.OptRecordFile;
1352 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1353 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1354 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1355 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1357 Conf.LoadedPassPlugins.push_back(Plugin.get());
1360 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1365 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1366 M->renumberMetadataForAssembly();
1367 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1372 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1373 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1386 finalizeLLVMOptimizationRemarks(M->getContext());
1387 if (
Error E = thinBackend(
1388 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1389 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1390 nullptr, Conf.CodeGenOnly, {},
1391 nullptr, CGOpts.CmdArgs)) {
1392 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1393 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1402 auto SaveModule = [&](StringRef Name, llvm::Module &M) {
1408 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
1412 errs() <<
"failed to open " << Path <<
": " << EC.message() <<
'\n';
1416 M.print(OS,
nullptr);
1420 std::string PromotionSuffix;
1427 for (
auto *CU : M->debug_compile_units()) {
1428 if (CU->getDirectory().size() > 0)
1429 Hash.update(CU->getDirectory());
1431 Hash.update(CU->getFilename());
1436 PromotionSuffix =
".dyndbg." + utohexstr(
Result.low());
1439 SaveModule(
"dyndbg.0.input", *M);
1441 auto UnoptM = prepareForDynamicDebugging(M, PromotionSuffix);
1442 SaveModule(
"dyndbg.1.inner", *UnoptM);
1444 if (!CGOpts.DiscardDynamicDebuggingDebugModule) {
1446 UnoptOpts.OptimizationLevel = 0;
1447 UnoptOpts.OptimizeSize = 0;
1448 EmitAssemblyHelper AsmHelper(CI, UnoptOpts, UnoptM.get(), VFS);
1452 std::unique_ptr<llvm::raw_pwrite_stream> UnoptOS =
1453 std::make_unique<llvm::raw_svector_ostream>(UnoptBuf);
1460 assert(!UnoptBuf.empty() &&
"Expected emitAssembly to fill UnoptBuf");
1463 StringRef SR(UnoptBuf.data(), UnoptBuf.size());
1464 std::unique_ptr<MemoryBuffer> Buf =
1465 MemoryBuffer::getMemBuffer(SR,
"",
false);
1467 GlobalVariable *EmbeddedGV =
1468 llvm::embedBufferInModule(*M, *Buf,
".debug_llvm_dyndbg", Align(8),
1471 auto &
C = M->getContext();
1472 auto getU32Metadata = [&
C](
unsigned Val) {
1473 return ConstantAsMetadata::get(ConstantInt::get(
C, APInt(32, Val)));
1475 EmbeddedGV->addMetadata(
1476 LLVMContext::MD_elf_section_properties,
1477 *MDTuple::get(
C, { getU32Metadata(ELF::SHT_LLVM_DYNDBG_ELF),
1478 getU32Metadata(0)}));
1480 SaveModule(
"dyndbg.2.outer", *M);
1484 StringRef TDesc, llvm::Module *M,
1487 std::unique_ptr<raw_pwrite_stream> OS,
1489 llvm::TimeTraceScope TimeScope(
"Backend");
1492 std::unique_ptr<llvm::Module> EmptyModule;
1495 auto BypassSandbox = sys::sandbox::scopedDisable();
1499 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1500 if (
Error E = llvm::getModuleSummaryIndexForFile(
1503 .moveInto(CombinedIndex)) {
1504 logAllUnhandledErrors(std::move(E), errs(),
1505 "Error loading index file '" +
1513 if (CombinedIndex) {
1514 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1526 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1527 EmptyModule->setTargetTriple(M->getTargetTriple());
1528 M = EmptyModule.get();
1532 bool EnableDynamicDebugging = CGOpts.DynamicDebugging;
1533 if (EnableDynamicDebugging) {
1537 const llvm::Target *TheTarget =
1538 TargetRegistry::lookupTarget(M->getTargetTriple(),
Error);
1539 if (!TheTarget && !CGOpts.DiscardDynamicDebuggingDebugModule) {
1540 Diags.
Report(diag::warn_dyndbg_unable_to_create_target) <<
Error;
1541 EnableDynamicDebugging =
false;
1548 if (CGOpts.getProfileInstr() != driver::ProfileInstrKind::ProfileNone) {
1549 Diags.
Report(diag::err_dyndbg_no_instrumentation);
1550 EnableDynamicDebugging =
false;
1553 if (EnableDynamicDebugging)
1556 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1557 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1562 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1563 if (DLDesc != TDesc) {
1564 Diags.
Report(diag::err_data_layout_mismatch) << DLDesc << TDesc;
1572 llvm::MemoryBufferRef Buf) {
1575 llvm::embedBitcodeInModule(
1587 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1588 VFS.getBufferForFile(OffloadObject);
1589 if (ObjectOrErr.getError()) {
1590 Diags.
Report(diag::err_failed_to_open_for_embedding) << OffloadObject;
1594 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1595 Align(object::OffloadBinary::getAlignment()));
static bool actionRequiresCodeGen(BackendAction Action)
static void addSanitizers(const Triple &TargetTriple, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, PassBuilder &PB)
static std::optional< llvm::CodeModel::Model > getCodeModel(const CodeGenOptions &CodeGenOpts)
static void runThinLTOBackend(CompilerInstance &CI, ModuleSummaryIndex *CombinedIndex, llvm::Module *M, std::unique_ptr< raw_pwrite_stream > OS, std::string SampleProfile, std::string ProfileRemapping, BackendAction Action)
static void createAndEmbedModuleForDynamicDebugging(CompilerInstance &CI, CodeGenOptions &CGOpts, llvm::Module *M, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, BackendConsumer *BC)
static SanitizerBinaryMetadataOptions getSanitizerBinaryMetadataOptions(const CodeGenOptions &CGOpts)
static std::optional< GCOVOptions > getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool initTargetOptions(const CompilerInstance &CI, DiagnosticsEngine &Diags, llvm::TargetOptions &Options)
static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts, vfs::FileSystem &VFS)
static std::string getProfileGenName(const CodeGenOptions &CodeGenOpts)
static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts, PassBuilder &PB)
static SanitizerCoverageOptions getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts)
static OptimizationLevel mapToLevel(const CodeGenOptions &Opts)
static std::string flattenClangCommandLine(ArrayRef< std::string > Args, StringRef MainFilename, ArrayRef< StringRef > InputFiles)
static std::optional< InstrProfOptions > getInstrProfOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts)
static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts)
void addLowerAllowCheckPass(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, PassBuilder &PB)
static CodeGenFileType getCodeGenFileType(BackendAction Action)
Defines the Diagnostic-related interfaces.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::LangOptions interface.
This file provides a pass to link in Modules from a provided BackendConsumer.
static bool contains(const std::set< tok::TokenKind > &Terminators, const Token &Tok)
Defines the clang::TargetOptions class.
__DEVICE__ int max(int __a, int __b)
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
SanitizerSet SanitizeMergeHandlers
Set of sanitizer checks that can merge handlers (smaller code size at the expense of debuggability).
std::string StackUsageFile
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
std::string InstrProfileOutput
Name of the profile file to use as output for -fprofile-instr-generate, -fprofile-generate,...
std::string BinutilsVersion
bool hasEmscriptenExceptions() const
bool hasDWARFExceptions() const
bool hasProfileIRUse() const
Check if IR level profile use is on.
char CoverageVersion[4]
The version string to put into coverage files.
std::string ThinLinkBitcodeFile
Name of a file that can optionally be written with minimized bitcode to be used as input for the Thin...
bool hasProfileCSIRInstr() const
Check if CS IR level profile instrumentation is on.
std::string DebugPass
Enable additional debugging information.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
uint64_t LargeDataThreshold
The code model-specific large data threshold to use (-mlarge-data-threshold).
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
std::vector< std::function< void(llvm::PassBuilder &)> > PassBuilderCallbacks
List of pass builder callbacks.
std::string LimitFloatPrecision
The float precision limit to use, if non-empty.
std::string CodeModel
The code model to use (-mcmodel).
std::string CoverageDataFile
The filename with path we use for coverage data files.
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
std::vector< std::string > SanitizeCoverageAllowlistFiles
Path to allowlist file specifying which objects (files, functions) should exclusively be instrumented...
std::vector< std::string > SanitizeCoverageIgnorelistFiles
Path to ignorelist file specifying which objects (files, functions) listed for instrumentation by san...
bool hasSanitizeCoverage() const
std::string MainFileName
The user provided name for the "main file", if non-empty.
bool hasProfileIRInstr() const
Check if IR level profile instrumentation is on.
bool hasProfileCSIRUse() const
Check if CSIR profile use is on.
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
std::vector< std::string > SanitizeMetadataIgnorelistFiles
Path to ignorelist file specifying which objects (files, functions) listed for instrumentation by san...
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
std::string ProfileExcludeFiles
Regexes separated by a semi-colon to filter the files to not instrument.
std::string AsSecureLogFile
The name of a file to use with .secure_log_unique directives.
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
bool hasSanitizeBinaryMetadata() const
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
const char * Argv0
Executable and command-line used to create a given CompilerInvocation.
bool hasWasmExceptions() const
bool hasSjLjExceptions() const
std::string remapDebugPathPrefix(StringRef Path) const
Remap specified path prefix using provided DebugPrefixMap map.
SanitizerMaskCutoffs SanitizeSkipHotCutoffs
Set of thresholds in a range [0.0, 1.0]: the top hottest code responsible for the given fraction of P...
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
std::vector< uint8_t > CmdArgs
List of backend command-line options for -fembed-bitcode.
std::optional< double > AllowRuntimeCheckSkipHotCutoff
std::vector< std::string > CommandLineArgs
bool hasSEHExceptions() const
std::string MemoryProfileUsePath
Name of the profile file to use as input for -fmemory-profile-use.
std::vector< std::string > OffloadObjects
List of filenames passed in using the -fembed-offload-object option.
std::string ProfileFilterFiles
Regexes separated by a semi-colon to filter the files to instrument.
std::string ObjectFilenameForDebug
Output filename used in the COFF debug information.
std::string SplitDwarfOutput
Output filename for the split debug info, not used in the skeleton CU.
std::string DIBugsReportFilePath
The file to use for dumping bug report by Debugify for original debug info.
std::string SaveDynDbgTempsFilePrefix
Prefix to use for -save-dynamic-debugging-temps output.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
llvm::TimerGroup & getTimerGroup() const
llvm::Timer & getFrontendTimer() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
TargetOptions & getTargetOpts()
FrontendOptions & getFrontendOpts()
HeaderSearchOptions & getHeaderSearchOpts()
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
llvm::ArrayRef< std::unique_ptr< llvm::PassPlugin > > getPassPlugins() const
CodeGenOptions & getCodeGenOpts()
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
@ Single
Single Threaded Environment.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
SanitizerSet Sanitize
Set of enabled sanitizers.
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
std::optional< std::vector< unsigned > > getAllScaled(unsigned ScalingFactor) const
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string ABI
If given, the name of the target ABI to use.
std::string CPU
If given, the name of the target CPU to generate code for.
llvm::EABI EABIVersion
The EABI version to use.
@ Angled
Paths for '#include <>' added by '-I'.
@ System
Like Angled, but marks system directories.
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
Top level wrappers for InstallAPI frontend operations.
@ Default
Set to the current date and time.
const FunctionProtoType * T
llvm::cl::opt< bool > ClSanitizeGuardChecks
void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
@ Backend_EmitAssembly
Emit native assembly files.
@ Backend_EmitLL
Emit human-readable LLVM assembly.
@ Backend_EmitBC
Emit LLVM bitcode files.
@ Backend_EmitObj
Emit native object files.
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
Diagnostic wrappers for TextAPI types for error reporting.
LLVM_ABI cl::opt< InstrProfCorrelator::ProfCorrelatorKind > ProfileCorrelate
static cl::opt< PGOOptions::ColdFuncOpt > ClPGOColdFuncAttr("pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden, cl::desc("Function attribute to apply to cold functions as determined by PGO"), cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default, "default", "Default (no attribute)"), clEnumValN(PGOOptions::ColdFuncOpt::OptSize, "optsize", "Mark cold functions with optsize."), clEnumValN(PGOOptions::ColdFuncOpt::MinSize, "minsize", "Mark cold functions with minsize."), clEnumValN(PGOOptions::ColdFuncOpt::OptNone, "optnone", "Mark cold functions with optnone.")))
static cl::opt< bool > ClSanitizeOnOptimizerEarlyEP("sanitizer-early-opt-ep", cl::Optional, cl::desc("Insert sanitizers on OptimizerEarlyEP."))
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.