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;
392 switch (LangOpts.getDefaultFPContractMode()) {
396 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
400 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
403 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
407 Options.MCOptions.BinutilsVersion =
408 llvm::MCTargetOptions::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
409 Options.UseInitArray = CodeGenOpts.UseInitArray;
410 Options.MCOptions.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
416 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
418 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
420 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
422 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
424 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
426 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
428 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
429 .Case(
"all", llvm::BasicBlockSection::All)
430 .StartsWith(
"list=", llvm::BasicBlockSection::List)
431 .Case(
"none", llvm::BasicBlockSection::None)
432 .Default(llvm::BasicBlockSection::None);
434 if (Options.BBSections == llvm::BasicBlockSection::List) {
435 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
439 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
440 << MBOrErr.getError().message();
443 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
446 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
447 Options.EnableStaticDataPartitioning =
448 CodeGenOpts.PartitionStaticDataSections;
449 Options.FunctionSections = CodeGenOpts.FunctionSections;
450 Options.DataSections = CodeGenOpts.DataSections;
451 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
452 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
453 Options.UniqueBasicBlockSectionNames =
454 CodeGenOpts.UniqueBasicBlockSectionNames;
455 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
456 Options.TLSSize = CodeGenOpts.TLSSize;
457 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
458 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
459 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
460 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
462 Options.EmitAddrsig = CodeGenOpts.Addrsig;
463 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
464 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
465 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
466 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
467 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
468 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
469 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
472 Options.Hotpatch = CodeGenOpts.HotPatch;
473 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
474 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
476 convertDriverVectorLibraryToVectorLibrary(CodeGenOpts.getVecLib());
478 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
480 Options.SwiftAsyncFramePointer =
481 SwiftAsyncFramePointerMode::DeploymentBased;
485 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
489 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
494 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
495 Options.MCOptions.EmitCompactUnwindNonCanonical =
496 CodeGenOpts.EmitCompactUnwindNonCanonical;
497 Options.MCOptions.EmitSFrameUnwind = CodeGenOpts.EmitSFrameUnwind;
498 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
499 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
500 Options.MCOptions.MCUseDwarfDirectory =
501 CodeGenOpts.NoDwarfDirectoryAsm
502 ? llvm::MCTargetOptions::DisableDwarfDirectory
503 : llvm::MCTargetOptions::EnableDwarfDirectory;
504 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
505 Options.MCOptions.MCIncrementalLinkerCompatible =
506 CodeGenOpts.IncrementalLinkerCompatible;
507 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
508 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
509 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
510 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
511 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
512 Options.MCOptions.Crel = CodeGenOpts.Crel;
513 Options.MCOptions.RelocSectionSym = CodeGenOpts.getRelocSectionSym();
514 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
515 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
516 Options.MCOptions.CompressDebugSections =
517 CodeGenOpts.getCompressDebugSections();
518 if (CodeGenOpts.OutputAsmVariant != 3)
519 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
520 Options.MCOptions.ABIName = TargetOpts.
ABI;
521 for (
const auto &Entry : HSOpts.UserEntries)
522 if (!Entry.IsFramework &&
526 Options.MCOptions.IASSearchPaths.push_back(
527 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
528 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
535 InputFiles.push_back(Input.getFile());
539 Options.MCOptions.PPCUseFullRegisterNames =
540 CodeGenOpts.PPCUseFullRegisterNames;
541 Options.MisExpect = CodeGenOpts.MisExpect;
546static std::optional<GCOVOptions>
557 Options.NoRedZone = CodeGenOpts.DisableRedZone;
560 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
564static std::optional<InstrProfOptions>
569 InstrProfOptions Options;
570 Options.NoRedZone = CodeGenOpts.DisableRedZone;
574 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
579 vfs::FileSystem &VFS) {
581 BackendArgs.push_back(
"clang");
583 BackendArgs.push_back(
"-debug-pass");
584 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
587 BackendArgs.push_back(
"-limit-float-precision");
594 if (BackendArgs.size() == 1)
596 BackendArgs.push_back(
nullptr);
600 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
605void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
608 const llvm::Triple &Triple = TheModule->getTargetTriple();
609 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
612 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
616 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
617 std::string FeaturesStr =
620 std::optional<CodeGenOptLevel> OptLevelOrNone =
621 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
622 assert(OptLevelOrNone &&
"Invalid optimization level!");
623 CodeGenOptLevel OptLevel = *OptLevelOrNone;
625 llvm::TargetOptions Options;
628 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
629 Options, RM, CM, OptLevel));
635 switch (Opts.OptimizationLevel) {
637 llvm_unreachable(
"Invalid optimization level!");
640 return OptimizationLevel::O0;
643 return OptimizationLevel::O1;
646 return OptimizationLevel::O2;
649 return OptimizationLevel::O3;
656 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
657 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
658 TargetTriple.isARM() || TargetTriple.isThumb() ||
659 TargetTriple.getArch() == llvm::Triple::hexagon)
663 PB.registerOptimizerLastEPCallback(
664 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
665 if (Level == OptimizationLevel::O0 &&
667 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
672 PB.registerPeepholeEPCallback(
673 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
674 if (Level != OptimizationLevel::O0 &&
676 FPM.addPass(KCFIPass());
683 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
684 ThinOrFullLTOPhase) {
688 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
694 MPM.addPass(SanitizerBinaryMetadataPass(
696 PB.getVirtualFileSystemPtr(),
700 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
702 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
705 MemorySanitizerOptions
options(TrackOrigins, Recover, CompileKernel,
706 CodeGenOpts.SanitizeMemoryParamRetval);
707 MPM.addPass(MemorySanitizerPass(
options));
708 if (Level != OptimizationLevel::O0) {
713 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
714 FunctionPassManager FPM;
715 FPM.addPass(EarlyCSEPass(
true ));
716 FPM.addPass(InstCombinePass());
717 FPM.addPass(JumpThreadingPass());
718 FPM.addPass(GVNPass());
719 FPM.addPass(InstCombinePass());
720 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
724 MSanPass(SanitizerKind::Memory,
false);
725 MSanPass(SanitizerKind::KernelMemory,
true);
727 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
728 MPM.addPass(ModuleThreadSanitizerPass());
729 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
733 MPM.addPass(TypeSanitizerPass());
735 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
736 MPM.addPass(NumericalStabilitySanitizerPass());
738 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
739 MPM.addPass(RealtimeSanitizerPass());
741 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
744 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
745 llvm::AsanDtorKind DestructorKind =
746 CodeGenOpts.getSanitizeAddressDtor();
747 AddressSanitizerOptions Opts;
748 Opts.CompileKernel = CompileKernel;
750 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
751 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
752 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
756 ASanPass(SanitizerKind::Address,
false);
757 ASanPass(SanitizerKind::KernelAddress,
true);
759 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
762 MPM.addPass(HWAddressSanitizerPass(
763 {CompileKernel, Recover,
764 CodeGenOpts.OptimizationLevel == 0}));
767 HWASanPass(SanitizerKind::HWAddress,
false);
768 HWASanPass(SanitizerKind::KernelHWAddress,
true);
770 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
772 PB.getVirtualFileSystemPtr()));
776 PB.registerOptimizerEarlyEPCallback(
777 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
778 ThinOrFullLTOPhase Phase) {
779 ModulePassManager NewMPM;
780 SanitizersCallback(NewMPM, Level, Phase);
781 if (!NewMPM.isEmpty()) {
783 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
784 MPM.addPass(std::move(NewMPM));
789 PB.registerOptimizerLastEPCallback(SanitizersCallback);
798 uint64_t AllowRuntimeCheckSkipHotCutoff =
803 SanitizerKind::Address | SanitizerKind::KernelAddress |
804 SanitizerKind::Thread | SanitizerKind::Memory |
805 SanitizerKind::KernelMemory | SanitizerKind::HWAddress |
806 SanitizerKind::KernelHWAddress);
809 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
811 LowerAllowSanitize) {
813 PB.registerOptimizerEarlyEPCallback(
814 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
815 ModulePassManager &MPM, OptimizationLevel Level,
816 ThinOrFullLTOPhase Phase) {
817 LowerAllowCheckPass::Options Opts;
819 if (ScaledCutoffs.has_value())
820 Opts.cutoffs = ScaledCutoffs.value();
821 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
823 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
828void EmitAssemblyHelper::RunOptimizationPipeline(
829 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
830 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
831 std::optional<PGOOptions> PGOOpt;
838 CodeGenOpts.DebugInfoForProfiling,
840 CodeGenOpts.AtomicProfileUpdate);
844 : PGOOptions::NoCSAction;
849 CodeGenOpts.DebugInfoForProfiling);
856 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
860 PGOOptions::NoAction, PGOOptions::NoCSAction,
862 else if (CodeGenOpts.PseudoProbeForProfiling)
864 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
866 CodeGenOpts.DebugInfoForProfiling,
true);
867 else if (CodeGenOpts.DebugInfoForProfiling)
869 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
875 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
878 assert(PGOOpt->Action != PGOOptions::IRInstr &&
879 PGOOpt->Action != PGOOptions::SampleUse &&
880 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
883 PGOOpt->CSAction = PGOOptions::CSIRInstr;
886 "", PGOOptions::NoAction,
888 CodeGenOpts.DebugInfoForProfiling);
891 TM->setPGOOption(PGOOpt);
893 PipelineTuningOptions PTO;
894 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
895 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
896 PTO.LoopFusion = CodeGenOpts.FuseLoops;
899 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
900 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
901 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
902 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
905 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
906 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
907 PTO.DevirtualizeSpeculatively = CodeGenOpts.DevirtualizeSpeculatively;
909 LoopAnalysisManager LAM;
910 FunctionAnalysisManager FAM;
911 CGSCCAnalysisManager CGAM;
912 ModuleAnalysisManager MAM;
914 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
915 PassInstrumentationCallbacks PIC;
916 PrintPassOptions PrintPassOpts;
917 PrintPassOpts.Indent = DebugPassStructure;
918 PrintPassOpts.SkipAnalyses = DebugPassStructure;
919 StandardInstrumentations SI(
920 TheModule->getContext(),
921 (CodeGenOpts.DebugPassManager || DebugPassStructure),
922 CodeGenOpts.VerifyEach, PrintPassOpts);
923 SI.registerCallbacks(PIC, &MAM);
927 switch (CodeGenOpts.getAssignmentTrackingMode()) {
928 case CodeGenOptions::AssignmentTrackingOpts::Forced:
929 PB.registerPipelineStartEPCallback(
930 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
931 MPM.addPass(AssignmentTrackingPass());
934 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
937 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
938 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
939 PB.registerPipelineStartEPCallback(
940 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
942 if (
Level != OptimizationLevel::O0)
943 MPM.addPass(AssignmentTrackingPass());
947 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
952 DebugifyEachInstrumentation Debugify;
953 DebugInfoPerPass DebugInfoBeforePass;
954 if (CodeGenOpts.EnableDIPreservationVerify) {
955 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
956 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
959 Debugify.setOrigDIVerifyBugsReportFilePath(
961 Debugify.registerCallbacks(PIC, MAM);
963#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
970 if (!F.getSubprogram())
972 for (BasicBlock &BB : F)
973 for (Instruction &I : BB)
974 if (!I.getDebugLoc())
975 I.setDebugLoc(DebugLoc::getCompilerGenerated());
980 for (
const std::unique_ptr<PassPlugin> &Plugin : CI.
getPassPlugins())
981 Plugin->registerPassBuilderCallbacks(PB);
984#define HANDLE_EXTENSION(Ext) \
985 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
986#include "llvm/Support/Extension.def"
990 std::unique_ptr<TargetLibraryInfoImpl> TLII(
991 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
992 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
995 PB.registerModuleAnalyses(MAM);
996 PB.registerCGSCCAnalyses(CGAM);
997 PB.registerFunctionAnalyses(FAM);
998 PB.registerLoopAnalyses(LAM);
999 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1001 ModulePassManager MPM;
1003 if (CodeGenOpts.VerifyModule)
1004 MPM.addPass(VerifierPass());
1006 if (!CodeGenOpts.DisableLLVMPasses) {
1011 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1012 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1014 if (LangOpts.ObjCAutoRefCount) {
1015 PB.registerPipelineStartEPCallback(
1016 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1017 if (
Level != OptimizationLevel::O0)
1019 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1021 PB.registerScalarOptimizerLateEPCallback(
1022 [](FunctionPassManager &FPM, OptimizationLevel
Level) {
1023 if (
Level != OptimizationLevel::O0)
1024 FPM.addPass(ObjCARCOptPass());
1034 if (IsThinLTOPostLink)
1035 PB.registerPipelineStartEPCallback(
1036 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1037 MPM.addPass(DropTypeTestsPass());
1042 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1043 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1044 OptimizationLevel
Level) {
1045 BoundsCheckingPass::Options Options;
1048 static_assert(SanitizerKind::SO_LocalBounds <=
1049 std::numeric_limits<
1050 decltype(Options.GuardKind)::value_type>
::max(),
1051 "Update type of llvm.allow.ubsan.check to represent "
1052 "SanitizerKind::SO_LocalBounds.");
1053 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1060 CodeGenOpts.SanitizeMinimalRuntime),
1064 static_cast<bool>(CodeGenOpts.SanitizeHandlerPreserveAllRegs),
1067 FPM.addPass(BoundsCheckingPass(Options));
1070 if (!IsThinLTOPostLink) {
1076 PB.registerPipelineStartEPCallback(
1077 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
1078 if (
Level == OptimizationLevel::O0 &&
1079 LangOpts.
Sanitize.
has(SanitizerKind::AllocToken)) {
1085 MPM.addPass(InferFunctionAttrsPass());
1090 if (std::optional<GCOVOptions> Options =
1092 PB.registerPipelineStartEPCallback(
1093 [
this, Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1097 if (std::optional<InstrProfOptions> Options =
1099 PB.registerPipelineStartEPCallback(
1100 [Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1101 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1107 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1108 OptimizationLevel
Level,
1109 ThinOrFullLTOPhase) {
1110 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1111 MPM.addPass(ModuleMemProfilerPass());
1115 if (CodeGenOpts.FatLTO) {
1116 MPM.addPass(PB.buildFatLTODefaultPipeline(
1117 Level, PrepareForThinLTO,
1118 PrepareForThinLTO || shouldEmitRegularLTOSummary(),
1119 CodeGenOpts.VerifyModule));
1120 }
else if (PrepareForThinLTO) {
1121 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(
Level));
1122 }
else if (PrepareForLTO) {
1123 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(
Level));
1125 MPM.addPass(PB.buildPerModuleDefaultPipeline(
Level));
1130 if (CodeGenOpts.LinkBitcodePostopt) {
1131 MPM.addPass(LinkInModulesPass(BC));
1132 MPM.addPass(AssignGUIDPass());
1135 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1136 LangOpts.HIPStdParInterposeAlloc)
1137 MPM.addPass(HipStdParAllocationInterpositionPass());
1145 MPM.addPass(VerifierPass());
1148 CodeGenOpts.FatLTO) {
1149 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1150 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1151 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1152 CodeGenOpts.EnableSplitLTOUnit);
1159 MPM.addPass(ThinLTOBitcodeWriterPass(
1160 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1162 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1169 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1170 if (EmitLTOSummary) {
1171 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1172 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1173 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1174 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1178 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1181 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1187 if (shouldEmitUnifiedLTOModueFlag() &&
1188 !TheModule->getModuleFlag(
"UnifiedLTO"))
1189 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1196 if (PrintPipelinePasses) {
1197 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1198 auto PassName = PIC.getPassNameForClassName(ClassName);
1199 return PassName.empty() ? ClassName : PassName;
1207 PrettyStackTraceString CrashInfo(
"Optimizer");
1208 llvm::TimeTraceScope TimeScope(
"Optimizer");
1214 MPM.run(*TheModule, MAM);
1220void EmitAssemblyHelper::RunCodegenPipeline(
1221 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1222 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1232 for (
const std::unique_ptr<llvm::PassPlugin> &Plugin : CI.
getPassPlugins()) {
1233 if (Plugin->invokePreCodeGenCallback(*TheModule, *TM, CGFT, *OS))
1243 TimeCodegenPasses([&]() {
1244 Error CodeGenError = runCodeGenPipeline(
1245 *TM, *TheModule, *OS, DwoOS, CGFT, PrintPipelinePasses.has_value(),
1248 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
1252void EmitAssemblyHelper::TimeCodegenPasses(
1253 llvm::function_ref<
void()> RunPasses) {
1254 PrettyStackTraceString CrashInfo(
"Code generation");
1255 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1258 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1267 std::unique_ptr<raw_pwrite_stream> OS,
1268 BackendConsumer *BC) {
1272 CreateTargetMachine(RequiresCodeGen);
1274 if (RequiresCodeGen && !TM)
1277 TheModule->setDataLayout(TM->createDataLayout());
1280 cl::PrintOptionValues();
1282 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1283 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1284 RunCodegenPipeline(Action, OS, DwoOS);
1294 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1295 std::string SampleProfile, std::string ProfileRemapping,
1300 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1301 ModuleToDefinedGVSummaries;
1302 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1309 FunctionImporter::ImportIDTable ImportIDs;
1310 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1311 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1314 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1315 return std::make_unique<CachedFileStream>(std::move(OS),
1316 CGOpts.ObjectFilenameForDebug);
1319 if (CGOpts.SaveTempsFilePrefix !=
"") {
1320 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1322 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1323 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1328 Conf.CPU = TOpts.CPU;
1330 Conf.MAttrs = TOpts.Features;
1331 Conf.RelocModel = CGOpts.RelocationModel;
1332 std::optional<CodeGenOptLevel> OptLevelOrNone =
1333 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1334 assert(OptLevelOrNone &&
"Invalid optimization level!");
1335 Conf.CGOptLevel = *OptLevelOrNone;
1336 Conf.OptLevel = CGOpts.OptimizationLevel;
1338 Conf.SampleProfile = std::move(SampleProfile);
1339 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1340 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1341 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1344 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1345 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1346 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1349 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1352 if (CGOpts.hasProfileCSIRInstr()) {
1353 Conf.RunCSIRInstr =
true;
1355 }
else if (CGOpts.hasProfileCSIRUse()) {
1356 Conf.RunCSIRInstr =
false;
1357 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1360 Conf.ProfileRemapping = std::move(ProfileRemapping);
1361 Conf.DebugPassManager = CGOpts.DebugPassManager;
1362 Conf.VerifyEach = CGOpts.VerifyEach;
1363 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1364 Conf.RemarksFilename = CGOpts.OptRecordFile;
1365 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1366 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1367 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1368 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1370 Conf.LoadedPassPlugins.push_back(Plugin.get());
1373 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1378 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1379 M->renumberMetadataForAssembly();
1380 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1385 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1386 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1399 finalizeLLVMOptimizationRemarks(M->getContext());
1400 if (
Error E = thinBackend(
1401 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1402 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1403 nullptr, Conf.CodeGenOnly, {},
1404 nullptr, CGOpts.CmdArgs)) {
1405 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1406 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1415 auto SaveModule = [&](StringRef Name, llvm::Module &M) {
1421 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
1425 errs() <<
"failed to open " << Path <<
": " << EC.message() <<
'\n';
1429 M.print(OS,
nullptr);
1433 std::string PromotionSuffix;
1440 for (
auto *CU : M->debug_compile_units()) {
1441 if (CU->getDirectory().size() > 0)
1442 Hash.update(CU->getDirectory());
1444 Hash.update(CU->getFilename());
1449 PromotionSuffix =
".dyndbg." + utohexstr(
Result.low());
1452 SaveModule(
"dyndbg.0.input", *M);
1454 auto UnoptM = prepareForDynamicDebugging(M, PromotionSuffix);
1455 SaveModule(
"dyndbg.1.inner", *UnoptM);
1457 if (!CGOpts.DiscardDynamicDebuggingDebugModule) {
1459 UnoptOpts.OptimizationLevel = 0;
1460 UnoptOpts.OptimizeSize = 0;
1461 EmitAssemblyHelper AsmHelper(CI, UnoptOpts, UnoptM.get(), VFS);
1465 std::unique_ptr<llvm::raw_pwrite_stream> UnoptOS =
1466 std::make_unique<llvm::raw_svector_ostream>(UnoptBuf);
1473 assert(!UnoptBuf.empty() &&
"Expected emitAssembly to fill UnoptBuf");
1476 StringRef SR(UnoptBuf.data(), UnoptBuf.size());
1477 std::unique_ptr<MemoryBuffer> Buf =
1478 MemoryBuffer::getMemBuffer(SR,
"",
false);
1480 GlobalVariable *EmbeddedGV =
1481 llvm::embedBufferInModule(*M, *Buf,
".debug_llvm_dyndbg", Align(8),
1484 auto &
C = M->getContext();
1485 auto getU32Metadata = [&
C](
unsigned Val) {
1486 return ConstantAsMetadata::get(ConstantInt::get(
C, APInt(32, Val)));
1488 EmbeddedGV->addMetadata(
1489 LLVMContext::MD_elf_section_properties,
1490 *MDTuple::get(
C, { getU32Metadata(ELF::SHT_LLVM_DYNDBG_ELF),
1491 getU32Metadata(0)}));
1493 SaveModule(
"dyndbg.2.outer", *M);
1497 StringRef TDesc, llvm::Module *M,
1500 std::unique_ptr<raw_pwrite_stream> OS,
1502 llvm::TimeTraceScope TimeScope(
"Backend");
1505 std::unique_ptr<llvm::Module> EmptyModule;
1508 auto BypassSandbox = sys::sandbox::scopedDisable();
1512 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1513 if (
Error E = llvm::getModuleSummaryIndexForFile(
1516 .moveInto(CombinedIndex)) {
1517 logAllUnhandledErrors(std::move(E), errs(),
1518 "Error loading index file '" +
1526 if (CombinedIndex) {
1527 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1539 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1540 EmptyModule->setTargetTriple(M->getTargetTriple());
1541 M = EmptyModule.get();
1545 bool EnableDynamicDebugging = CGOpts.DynamicDebugging;
1546 if (EnableDynamicDebugging) {
1550 const llvm::Target *TheTarget =
1551 TargetRegistry::lookupTarget(M->getTargetTriple(),
Error);
1552 if (!TheTarget && !CGOpts.DiscardDynamicDebuggingDebugModule) {
1553 Diags.
Report(diag::warn_dyndbg_unable_to_create_target) <<
Error;
1554 EnableDynamicDebugging =
false;
1561 if (CGOpts.getProfileInstr() != driver::ProfileInstrKind::ProfileNone) {
1562 Diags.
Report(diag::err_dyndbg_no_instrumentation);
1563 EnableDynamicDebugging =
false;
1566 if (EnableDynamicDebugging)
1569 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1570 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1575 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1576 if (DLDesc != TDesc) {
1577 Diags.
Report(diag::err_data_layout_mismatch) << DLDesc << TDesc;
1585 llvm::MemoryBufferRef Buf) {
1588 llvm::embedBitcodeInModule(
1600 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1601 VFS.getBufferForFile(OffloadObject);
1602 if (ObjectOrErr.getError()) {
1603 Diags.
Report(diag::err_failed_to_open_for_embedding) << OffloadObject;
1607 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1608 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 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.