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/TargetRegistry.h"
44#include "llvm/Object/OffloadBinary.h"
45#include "llvm/Passes/PassBuilder.h"
46#include "llvm/Passes/StandardInstrumentations.h"
47#include "llvm/Plugins/PassPlugin.h"
48#include "llvm/ProfileData/InstrProfCorrelator.h"
49#include "llvm/Support/BuryPointer.h"
50#include "llvm/Support/CodeGen.h"
51#include "llvm/Support/CommandLine.h"
52#include "llvm/Support/Compiler.h"
53#include "llvm/Support/IOSandbox.h"
54#include "llvm/Support/MemoryBuffer.h"
55#include "llvm/Support/PrettyStackTrace.h"
56#include "llvm/Support/Program.h"
57#include "llvm/Support/TimeProfiler.h"
58#include "llvm/Support/Timer.h"
59#include "llvm/Support/ToolOutputFile.h"
60#include "llvm/Support/VirtualFileSystem.h"
61#include "llvm/Support/raw_ostream.h"
62#include "llvm/Target/TargetMachine.h"
63#include "llvm/Target/TargetOptions.h"
64#include "llvm/TargetParser/SubtargetFeature.h"
65#include "llvm/TargetParser/Triple.h"
66#include "llvm/Transforms/HipStdPar/HipStdPar.h"
67#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
68#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
69#include "llvm/Transforms/IPO/LowerTypeTests.h"
70#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
71#include "llvm/Transforms/InstCombine/InstCombine.h"
72#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
73#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
74#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
75#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
76#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
77#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
78#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
79#include "llvm/Transforms/Instrumentation/KCFI.h"
80#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
81#include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
82#include "llvm/Transforms/Instrumentation/MemProfUse.h"
83#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
84#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
85#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
86#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
87#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
88#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
89#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
90#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
91#include "llvm/Transforms/ObjCARC.h"
92#include "llvm/Transforms/Scalar/EarlyCSE.h"
93#include "llvm/Transforms/Scalar/GVN.h"
94#include "llvm/Transforms/Scalar/JumpThreading.h"
95#include "llvm/Transforms/Utils/AssignGUID.h"
96#include "llvm/Transforms/Utils/Debugify.h"
97#include "llvm/Transforms/Utils/DynamicDebugging.h"
98#include "llvm/Transforms/Utils/ModuleUtils.h"
102using namespace clang;
105#define HANDLE_EXTENSION(Ext) \
106 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
107#include "llvm/Support/Extension.def"
112 "sanitizer-early-opt-ep", cl::Optional,
113 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
118 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
120 "Function attribute to apply to cold functions as determined by PGO"),
121 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
122 "Default (no attribute)"),
123 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
124 "Mark cold functions with optsize."),
125 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
126 "Mark cold functions with minsize."),
127 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
128 "Mark cold functions with optnone.")));
130LLVM_ABI
extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
140 ? llvm::driver::getDefaultProfileGenName()
142 if (CodeGenOpts.ContinuousProfileSync)
149class EmitAssemblyHelper {
150 CompilerInstance &CI;
151 DiagnosticsEngine &Diags;
152 const CodeGenOptions &CodeGenOpts;
153 const clang::TargetOptions &TargetOpts;
154 const LangOptions &LangOpts;
155 llvm::Module *TheModule;
156 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
158 std::unique_ptr<raw_pwrite_stream> OS;
162 TargetIRAnalysis getTargetIRAnalysis()
const {
164 return TM->getTargetIRAnalysis();
166 return TargetIRAnalysis();
177 void CreateTargetMachine(
bool MustCreateTM);
179 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
181 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
182 llvm::sys::fs::OF_None);
184 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
190 void RunOptimizationPipeline(
191 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
192 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
194 std::unique_ptr<raw_pwrite_stream> &OS,
195 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
197 std::unique_ptr<raw_pwrite_stream> &OS,
198 std::unique_ptr<llvm::ToolOutputFile> &DwoOS,
199 CodeGenFileType CGFT);
201 std::unique_ptr<raw_pwrite_stream> &OS,
202 std::unique_ptr<llvm::ToolOutputFile> &DwoOS,
203 CodeGenFileType CGFT);
204 void TimeCodegenPasses(llvm::function_ref<
void()> RunPasses);
211 bool shouldEmitRegularLTOSummary()
const {
212 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
213 TargetTriple.getVendor() != llvm::Triple::Apple;
219 bool shouldEmitUnifiedLTOModueFlag()
const {
220 return CodeGenOpts.UnifiedLTO &&
221 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
225 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
227 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
228 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
229 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
230 TheModule(M), VFS(std::move(VFS)),
231 TargetTriple(TheModule->getTargetTriple()) {}
233 ~EmitAssemblyHelper() {
234 if (CodeGenOpts.DisableFree)
235 BuryPointer(std::move(TM));
238 std::unique_ptr<TargetMachine> TM;
241 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
242 BackendConsumer *BC);
246static SanitizerCoverageOptions
248 SanitizerCoverageOptions Opts;
250 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
251 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
252 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
253 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
254 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
255 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
256 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
257 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
258 Opts.TracePCEntryExit = CGOpts.SanitizeCoverageTracePCEntryExit;
259 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
260 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
261 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
262 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
263 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
264 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
265 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
266 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
267 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
268 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
272static SanitizerBinaryMetadataOptions
274 SanitizerBinaryMetadataOptions Opts;
275 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
276 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
277 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
286 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
288 switch (
T.getObjectFormat()) {
293 return !CGOpts.DisableIntegratedAS;
295 llvm::report_fatal_error(
"ASan not implemented for GOFF");
297 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
299 case Triple::DXContainer:
301 case Triple::UnknownObjectFormat:
307static std::optional<llvm::CodeModel::Model>
309 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
310 .Case(
"tiny", llvm::CodeModel::Tiny)
311 .Case(
"small", llvm::CodeModel::Small)
312 .Case(
"kernel", llvm::CodeModel::Kernel)
313 .Case(
"medium", llvm::CodeModel::Medium)
314 .Case(
"large", llvm::CodeModel::Large)
315 .Cases({
"default",
""}, ~1u)
317 assert(CodeModel != ~0u &&
"invalid code model!");
318 if (CodeModel == ~1u)
320 return static_cast<llvm::CodeModel::Model
>(CodeModel);
325 return CodeGenFileType::ObjectFile;
327 return CodeGenFileType::Null;
330 return CodeGenFileType::AssemblyFile;
340 StringRef MainFilename,
343 return std::string{};
345 std::string FlatCmdLine;
346 raw_string_ostream OS(FlatCmdLine);
347 bool PrintedOneArg =
false;
348 if (!StringRef(Args[0]).
contains(
"-cc1")) {
349 llvm::sys::printArg(OS,
"-cc1",
true);
350 PrintedOneArg =
true;
352 for (
unsigned i = 0; i < Args.size(); i++) {
353 StringRef Arg = Args[i];
356 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
360 if (Arg.starts_with(
"-object-file-name"))
368 if (Arg == MainFilename || llvm::is_contained(InputFiles, Arg))
371 if (Arg.starts_with(
"-fmessage-length"))
375 llvm::sys::printArg(OS, Arg,
true);
376 PrintedOneArg =
true;
383 llvm::TargetOptions &Options) {
388 switch (LangOpts.getThreadModel()) {
390 Options.ThreadModel = llvm::ThreadModel::POSIX;
393 Options.ThreadModel = llvm::ThreadModel::Single;
398 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
400 "Invalid Floating Point ABI!");
401 Options.FloatABIType =
402 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
403 .Case(
"soft", llvm::FloatABI::Soft)
404 .Case(
"softfp", llvm::FloatABI::Soft)
405 .Case(
"hard", llvm::FloatABI::Hard)
406 .Default(llvm::FloatABI::Default);
409 switch (LangOpts.getDefaultFPContractMode()) {
413 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
417 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
420 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
424 Options.BinutilsVersion =
425 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
426 Options.UseInitArray = CodeGenOpts.UseInitArray;
427 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
433 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
435 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
437 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
439 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
441 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
443 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
445 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
446 .Case(
"all", llvm::BasicBlockSection::All)
447 .StartsWith(
"list=", llvm::BasicBlockSection::List)
448 .Case(
"none", llvm::BasicBlockSection::None)
449 .Default(llvm::BasicBlockSection::None);
451 if (Options.BBSections == llvm::BasicBlockSection::List) {
452 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
456 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
457 << MBOrErr.getError().message();
460 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
463 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
464 Options.EnableStaticDataPartitioning =
465 CodeGenOpts.PartitionStaticDataSections;
466 Options.FunctionSections = CodeGenOpts.FunctionSections;
467 Options.DataSections = CodeGenOpts.DataSections;
468 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
469 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
470 Options.UniqueBasicBlockSectionNames =
471 CodeGenOpts.UniqueBasicBlockSectionNames;
472 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
473 Options.TLSSize = CodeGenOpts.TLSSize;
474 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
475 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
476 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
477 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
479 Options.EmitAddrsig = CodeGenOpts.Addrsig;
480 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
481 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
482 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
483 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
484 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
485 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
486 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
488 Options.Hotpatch = CodeGenOpts.HotPatch;
489 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
490 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
492 convertDriverVectorLibraryToVectorLibrary(CodeGenOpts.getVecLib());
494 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
496 Options.SwiftAsyncFramePointer =
497 SwiftAsyncFramePointerMode::DeploymentBased;
501 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
505 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
510 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
511 Options.MCOptions.EmitCompactUnwindNonCanonical =
512 CodeGenOpts.EmitCompactUnwindNonCanonical;
513 Options.MCOptions.EmitSFrameUnwind = CodeGenOpts.EmitSFrameUnwind;
514 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
515 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
516 Options.MCOptions.MCUseDwarfDirectory =
517 CodeGenOpts.NoDwarfDirectoryAsm
518 ? llvm::MCTargetOptions::DisableDwarfDirectory
519 : llvm::MCTargetOptions::EnableDwarfDirectory;
520 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
521 Options.MCOptions.MCIncrementalLinkerCompatible =
522 CodeGenOpts.IncrementalLinkerCompatible;
523 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
524 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
525 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
526 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
527 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
528 Options.MCOptions.Crel = CodeGenOpts.Crel;
529 Options.MCOptions.RelocSectionSym = CodeGenOpts.getRelocSectionSym();
530 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
531 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
532 Options.MCOptions.CompressDebugSections =
533 CodeGenOpts.getCompressDebugSections();
534 if (CodeGenOpts.OutputAsmVariant != 3)
535 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
536 Options.MCOptions.ABIName = TargetOpts.
ABI;
537 for (
const auto &Entry : HSOpts.UserEntries)
538 if (!Entry.IsFramework &&
542 Options.MCOptions.IASSearchPaths.push_back(
543 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
544 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
551 InputFiles.push_back(Input.getFile());
555 Options.MCOptions.PPCUseFullRegisterNames =
556 CodeGenOpts.PPCUseFullRegisterNames;
557 Options.MisExpect = CodeGenOpts.MisExpect;
562static std::optional<GCOVOptions>
573 Options.NoRedZone = CodeGenOpts.DisableRedZone;
576 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
580static std::optional<InstrProfOptions>
585 InstrProfOptions Options;
586 Options.NoRedZone = CodeGenOpts.DisableRedZone;
590 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
595 vfs::FileSystem &VFS) {
597 BackendArgs.push_back(
"clang");
599 BackendArgs.push_back(
"-debug-pass");
600 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
603 BackendArgs.push_back(
"-limit-float-precision");
610 if (BackendArgs.size() == 1)
612 BackendArgs.push_back(
nullptr);
616 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
621void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
624 const llvm::Triple &Triple = TheModule->getTargetTriple();
625 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
628 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
632 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
633 std::string FeaturesStr =
636 std::optional<CodeGenOptLevel> OptLevelOrNone =
637 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
638 assert(OptLevelOrNone &&
"Invalid optimization level!");
639 CodeGenOptLevel OptLevel = *OptLevelOrNone;
641 llvm::TargetOptions Options;
644 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
645 Options, RM, CM, OptLevel));
651 switch (Opts.OptimizationLevel) {
653 llvm_unreachable(
"Invalid optimization level!");
656 return OptimizationLevel::O0;
659 return OptimizationLevel::O1;
662 return OptimizationLevel::O2;
665 return OptimizationLevel::O3;
672 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
673 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
674 TargetTriple.isARM() || TargetTriple.isThumb() ||
675 TargetTriple.getArch() == llvm::Triple::hexagon)
679 PB.registerOptimizerLastEPCallback(
680 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
681 if (Level == OptimizationLevel::O0 &&
683 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
688 PB.registerPeepholeEPCallback(
689 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
690 if (Level != OptimizationLevel::O0 &&
692 FPM.addPass(KCFIPass());
699 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
700 ThinOrFullLTOPhase) {
704 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
710 MPM.addPass(SanitizerBinaryMetadataPass(
712 PB.getVirtualFileSystemPtr(),
716 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
718 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
721 MemorySanitizerOptions
options(TrackOrigins, Recover, CompileKernel,
722 CodeGenOpts.SanitizeMemoryParamRetval);
723 MPM.addPass(MemorySanitizerPass(
options));
724 if (Level != OptimizationLevel::O0) {
729 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
730 FunctionPassManager FPM;
731 FPM.addPass(EarlyCSEPass(
true ));
732 FPM.addPass(InstCombinePass());
733 FPM.addPass(JumpThreadingPass());
734 FPM.addPass(GVNPass());
735 FPM.addPass(InstCombinePass());
736 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
740 MSanPass(SanitizerKind::Memory,
false);
741 MSanPass(SanitizerKind::KernelMemory,
true);
743 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
744 MPM.addPass(ModuleThreadSanitizerPass());
745 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
749 MPM.addPass(TypeSanitizerPass());
751 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
752 MPM.addPass(NumericalStabilitySanitizerPass());
754 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
755 MPM.addPass(RealtimeSanitizerPass());
757 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
760 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
761 llvm::AsanDtorKind DestructorKind =
762 CodeGenOpts.getSanitizeAddressDtor();
763 AddressSanitizerOptions Opts;
764 Opts.CompileKernel = CompileKernel;
766 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
767 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
768 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
772 ASanPass(SanitizerKind::Address,
false);
773 ASanPass(SanitizerKind::KernelAddress,
true);
775 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
778 MPM.addPass(HWAddressSanitizerPass(
779 {CompileKernel, Recover,
780 CodeGenOpts.OptimizationLevel == 0}));
783 HWASanPass(SanitizerKind::HWAddress,
false);
784 HWASanPass(SanitizerKind::KernelHWAddress,
true);
786 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
788 PB.getVirtualFileSystemPtr()));
792 PB.registerOptimizerEarlyEPCallback(
793 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
794 ThinOrFullLTOPhase Phase) {
795 ModulePassManager NewMPM;
796 SanitizersCallback(NewMPM, Level, Phase);
797 if (!NewMPM.isEmpty()) {
799 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
800 MPM.addPass(std::move(NewMPM));
805 PB.registerOptimizerLastEPCallback(SanitizersCallback);
814 uint64_t AllowRuntimeCheckSkipHotCutoff =
819 SanitizerKind::Address | SanitizerKind::KernelAddress |
820 SanitizerKind::Thread | SanitizerKind::Memory |
821 SanitizerKind::KernelMemory | SanitizerKind::HWAddress |
822 SanitizerKind::KernelHWAddress);
825 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
827 LowerAllowSanitize) {
829 PB.registerOptimizerEarlyEPCallback(
830 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
831 ModulePassManager &MPM, OptimizationLevel Level,
832 ThinOrFullLTOPhase Phase) {
833 LowerAllowCheckPass::Options Opts;
835 if (ScaledCutoffs.has_value())
836 Opts.cutoffs = ScaledCutoffs.value();
837 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
839 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
844void EmitAssemblyHelper::RunOptimizationPipeline(
845 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
846 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
847 std::optional<PGOOptions> PGOOpt;
854 CodeGenOpts.DebugInfoForProfiling,
856 CodeGenOpts.AtomicProfileUpdate);
860 : PGOOptions::NoCSAction;
865 CodeGenOpts.DebugInfoForProfiling);
872 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
876 PGOOptions::NoAction, PGOOptions::NoCSAction,
878 else if (CodeGenOpts.PseudoProbeForProfiling)
880 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
882 CodeGenOpts.DebugInfoForProfiling,
true);
883 else if (CodeGenOpts.DebugInfoForProfiling)
885 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
891 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
894 assert(PGOOpt->Action != PGOOptions::IRInstr &&
895 PGOOpt->Action != PGOOptions::SampleUse &&
896 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
899 PGOOpt->CSAction = PGOOptions::CSIRInstr;
902 "", PGOOptions::NoAction,
904 CodeGenOpts.DebugInfoForProfiling);
907 TM->setPGOOption(PGOOpt);
909 PipelineTuningOptions PTO;
910 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
911 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
912 PTO.LoopFusion = CodeGenOpts.FuseLoops;
915 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
916 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
917 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
918 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
921 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
922 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
923 PTO.DevirtualizeSpeculatively = CodeGenOpts.DevirtualizeSpeculatively;
925 LoopAnalysisManager LAM;
926 FunctionAnalysisManager FAM;
927 CGSCCAnalysisManager CGAM;
928 ModuleAnalysisManager MAM;
930 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
931 PassInstrumentationCallbacks PIC;
932 PrintPassOptions PrintPassOpts;
933 PrintPassOpts.Indent = DebugPassStructure;
934 PrintPassOpts.SkipAnalyses = DebugPassStructure;
935 StandardInstrumentations SI(
936 TheModule->getContext(),
937 (CodeGenOpts.DebugPassManager || DebugPassStructure),
938 CodeGenOpts.VerifyEach, PrintPassOpts);
939 SI.registerCallbacks(PIC, &MAM);
943 switch (CodeGenOpts.getAssignmentTrackingMode()) {
944 case CodeGenOptions::AssignmentTrackingOpts::Forced:
945 PB.registerPipelineStartEPCallback(
946 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
947 MPM.addPass(AssignmentTrackingPass());
950 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
953 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
954 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
955 PB.registerPipelineStartEPCallback(
956 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
958 if (
Level != OptimizationLevel::O0)
959 MPM.addPass(AssignmentTrackingPass());
963 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
968 DebugifyEachInstrumentation Debugify;
969 DebugInfoPerPass DebugInfoBeforePass;
970 if (CodeGenOpts.EnableDIPreservationVerify) {
971 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
972 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
975 Debugify.setOrigDIVerifyBugsReportFilePath(
977 Debugify.registerCallbacks(PIC, MAM);
979#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
986 if (!F.getSubprogram())
988 for (BasicBlock &BB : F)
989 for (Instruction &I : BB)
990 if (!I.getDebugLoc())
991 I.setDebugLoc(DebugLoc::getCompilerGenerated());
996 for (
const std::unique_ptr<PassPlugin> &Plugin : CI.
getPassPlugins())
997 Plugin->registerPassBuilderCallbacks(PB);
1000#define HANDLE_EXTENSION(Ext) \
1001 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1002#include "llvm/Support/Extension.def"
1006 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1007 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1008 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
1011 PB.registerModuleAnalyses(MAM);
1012 PB.registerCGSCCAnalyses(CGAM);
1013 PB.registerFunctionAnalyses(FAM);
1014 PB.registerLoopAnalyses(LAM);
1015 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1017 ModulePassManager MPM;
1019 if (CodeGenOpts.VerifyModule)
1020 MPM.addPass(VerifierPass());
1022 if (!CodeGenOpts.DisableLLVMPasses) {
1027 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1028 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1030 if (LangOpts.ObjCAutoRefCount) {
1031 PB.registerPipelineStartEPCallback(
1032 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1033 if (
Level != OptimizationLevel::O0)
1035 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1037 PB.registerScalarOptimizerLateEPCallback(
1038 [](FunctionPassManager &FPM, OptimizationLevel
Level) {
1039 if (
Level != OptimizationLevel::O0)
1040 FPM.addPass(ObjCARCOptPass());
1050 if (IsThinLTOPostLink)
1051 PB.registerPipelineStartEPCallback(
1052 [](ModulePassManager &MPM, OptimizationLevel
Level) {
1053 MPM.addPass(DropTypeTestsPass());
1058 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1059 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1060 OptimizationLevel
Level) {
1061 BoundsCheckingPass::Options Options;
1064 static_assert(SanitizerKind::SO_LocalBounds <=
1065 std::numeric_limits<
1066 decltype(Options.GuardKind)::value_type>
::max(),
1067 "Update type of llvm.allow.ubsan.check to represent "
1068 "SanitizerKind::SO_LocalBounds.");
1069 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1076 CodeGenOpts.SanitizeMinimalRuntime),
1080 static_cast<bool>(CodeGenOpts.SanitizeHandlerPreserveAllRegs),
1083 FPM.addPass(BoundsCheckingPass(Options));
1086 if (!IsThinLTOPostLink) {
1092 PB.registerPipelineStartEPCallback(
1093 [&](ModulePassManager &MPM, OptimizationLevel
Level) {
1094 if (
Level == OptimizationLevel::O0 &&
1095 LangOpts.
Sanitize.
has(SanitizerKind::AllocToken)) {
1101 MPM.addPass(InferFunctionAttrsPass());
1106 if (std::optional<GCOVOptions> Options =
1108 PB.registerPipelineStartEPCallback(
1109 [
this, Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1113 if (std::optional<InstrProfOptions> Options =
1115 PB.registerPipelineStartEPCallback(
1116 [Options](ModulePassManager &MPM, OptimizationLevel
Level) {
1117 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1123 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1124 OptimizationLevel
Level,
1125 ThinOrFullLTOPhase) {
1126 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1127 MPM.addPass(ModuleMemProfilerPass());
1131 if (CodeGenOpts.FatLTO) {
1132 MPM.addPass(PB.buildFatLTODefaultPipeline(
1133 Level, PrepareForThinLTO,
1134 PrepareForThinLTO || shouldEmitRegularLTOSummary(),
1135 CodeGenOpts.VerifyModule));
1136 }
else if (PrepareForThinLTO) {
1137 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(
Level));
1138 }
else if (PrepareForLTO) {
1139 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(
Level));
1141 MPM.addPass(PB.buildPerModuleDefaultPipeline(
Level));
1146 if (CodeGenOpts.LinkBitcodePostopt) {
1147 MPM.addPass(LinkInModulesPass(BC));
1148 MPM.addPass(AssignGUIDPass());
1151 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1152 LangOpts.HIPStdParInterposeAlloc)
1153 MPM.addPass(HipStdParAllocationInterpositionPass());
1161 MPM.addPass(VerifierPass());
1164 CodeGenOpts.FatLTO) {
1165 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1166 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1167 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1168 CodeGenOpts.EnableSplitLTOUnit);
1175 MPM.addPass(ThinLTOBitcodeWriterPass(
1176 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1178 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1184 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1185 if (EmitLTOSummary) {
1186 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1187 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1188 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1189 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1193 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1196 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1201 if (shouldEmitUnifiedLTOModueFlag() &&
1202 !TheModule->getModuleFlag(
"UnifiedLTO"))
1203 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1210 if (PrintPipelinePasses) {
1211 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1212 auto PassName = PIC.getPassNameForClassName(ClassName);
1213 return PassName.empty() ? ClassName : PassName;
1221 PrettyStackTraceString CrashInfo(
"Optimizer");
1222 llvm::TimeTraceScope TimeScope(
"Optimizer");
1228 MPM.run(*TheModule, MAM);
1234void EmitAssemblyHelper::RunCodegenPipeline(
1235 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1236 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1246 for (
const std::unique_ptr<llvm::PassPlugin> &Plugin : CI.
getPassPlugins()) {
1247 if (Plugin->invokePreCodeGenCallback(*TheModule, *TM, CGFT, *OS))
1257 if (CodeGenOpts.getEnableNewPMCodeGen() ==
1258 CodeGenOptions::NewPMEnablementLevel::ForceEnable ||
1259 (CodeGenOpts.getEnableNewPMCodeGen() ==
1260 CodeGenOptions::NewPMEnablementLevel::Auto &&
1261 TM->shouldDefaultToNewPM())) {
1262 RunCodegenPipelineNewPM(Action, OS, DwoOS, CGFT);
1264 RunCodegenPipelineLegacy(Action, OS, DwoOS, CGFT);
1268void EmitAssemblyHelper::RunCodegenPipelineLegacy(
1269 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1270 std::unique_ptr<llvm::ToolOutputFile> &DwoOS, CodeGenFileType CGFT) {
1274 legacy::PassManager CodeGenPasses;
1277 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1279 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1280 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1281 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
1283 const llvm::TargetOptions &Options = TM->Options;
1284 CodeGenPasses.add(
new RuntimeLibraryInfoWrapper(
1285 TargetTriple, Options.ExceptionModel, Options.FloatABIType,
1286 Options.EABIVersion, Options.MCOptions.ABIName, Options.VecLib));
1288 if (TM->addPassesToEmitFile(CodeGenPasses, *OS,
1289 DwoOS ? &DwoOS->os() :
nullptr, CGFT,
1290 !CodeGenOpts.VerifyModule)) {
1291 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
1298 if (PrintPipelinePasses) {
1302 TimeCodegenPasses([&] { CodeGenPasses.run(*TheModule); });
1305void EmitAssemblyHelper::RunCodegenPipelineNewPM(
1306 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1307 std::unique_ptr<llvm::ToolOutputFile> &DwoOS, CodeGenFileType CGFT) {
1308 ModulePassManager MPM;
1309 MachineFunctionAnalysisManager MFAM;
1310 LoopAnalysisManager LAM;
1311 FunctionAnalysisManager FAM;
1312 CGSCCAnalysisManager CGAM;
1313 ModuleAnalysisManager MAM;
1314 CGPassBuilderOption Opt = getCGPassBuilderOption();
1315 Opt.DisableVerify = !CodeGenOpts.VerifyModule;
1316 MachineModuleInfo MMI(TM.get());
1317 PassInstrumentationCallbacks PIC;
1318 PipelineTuningOptions PTOptions;
1319 TargetMachine *TMPointer = TM.get();
1320 PassBuilder PB(TMPointer, PTOptions, std::nullopt, &PIC,
1322 PB.registerModuleAnalyses(MAM);
1323 PB.registerCGSCCAnalyses(CGAM);
1324 PB.registerFunctionAnalyses(FAM);
1325 PB.registerLoopAnalyses(LAM);
1326 PB.registerMachineFunctionAnalyses(MFAM);
1327 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM, &MFAM);
1329 MAM.registerPass([&] {
return MachineModuleAnalysis(MMI); });
1331 Error BuildPipelineError =
1332 TM->buildCodeGenPipeline(MPM, MAM, *OS, DwoOS ? &DwoOS->os() :
nullptr,
1333 CGFT, Opt, MMI.getContext(), &PIC);
1334 if (BuildPipelineError) {
1335 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
1339 TimeCodegenPasses([&] { MPM.run(*TheModule, MAM); });
1342void EmitAssemblyHelper::TimeCodegenPasses(
1343 llvm::function_ref<
void()> RunPasses) {
1344 PrettyStackTraceString CrashInfo(
"Code generation");
1345 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1348 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1357 std::unique_ptr<raw_pwrite_stream> OS,
1358 BackendConsumer *BC) {
1362 CreateTargetMachine(RequiresCodeGen);
1364 if (RequiresCodeGen && !TM)
1367 TheModule->setDataLayout(TM->createDataLayout());
1370 cl::PrintOptionValues();
1372 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1373 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1374 RunCodegenPipeline(Action, OS, DwoOS);
1384 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1385 std::string SampleProfile, std::string ProfileRemapping,
1390 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1391 ModuleToDefinedGVSummaries;
1392 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1399 FunctionImporter::ImportIDTable ImportIDs;
1400 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1401 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1404 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1405 return std::make_unique<CachedFileStream>(std::move(OS),
1406 CGOpts.ObjectFilenameForDebug);
1409 if (CGOpts.SaveTempsFilePrefix !=
"") {
1410 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1412 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1413 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1418 Conf.CPU = TOpts.CPU;
1420 Conf.MAttrs = TOpts.Features;
1421 Conf.RelocModel = CGOpts.RelocationModel;
1422 std::optional<CodeGenOptLevel> OptLevelOrNone =
1423 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1424 assert(OptLevelOrNone &&
"Invalid optimization level!");
1425 Conf.CGOptLevel = *OptLevelOrNone;
1426 Conf.OptLevel = CGOpts.OptimizationLevel;
1428 Conf.SampleProfile = std::move(SampleProfile);
1429 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1430 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1431 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1434 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1435 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1436 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1439 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1442 if (CGOpts.hasProfileCSIRInstr()) {
1443 Conf.RunCSIRInstr =
true;
1445 }
else if (CGOpts.hasProfileCSIRUse()) {
1446 Conf.RunCSIRInstr =
false;
1447 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1450 Conf.ProfileRemapping = std::move(ProfileRemapping);
1451 Conf.DebugPassManager = CGOpts.DebugPassManager;
1452 Conf.VerifyEach = CGOpts.VerifyEach;
1453 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1454 Conf.RemarksFilename = CGOpts.OptRecordFile;
1455 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1456 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1457 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1458 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1460 Conf.LoadedPassPlugins.push_back(Plugin.get());
1463 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1468 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1469 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1474 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1475 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1488 finalizeLLVMOptimizationRemarks(M->getContext());
1489 if (
Error E = thinBackend(
1490 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1491 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1492 nullptr, Conf.CodeGenOnly, {},
1493 nullptr, CGOpts.CmdArgs)) {
1494 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1495 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1504 auto SaveModule = [&](StringRef Name, llvm::Module &M) {
1510 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
1514 errs() <<
"failed to open " << Path <<
": " << EC.message() <<
'\n';
1518 M.print(OS,
nullptr);
1522 std::string PromotionSuffix;
1529 for (
auto *CU : M->debug_compile_units()) {
1530 if (CU->getDirectory().size() > 0)
1531 Hash.update(CU->getDirectory());
1533 Hash.update(CU->getFilename());
1538 PromotionSuffix =
".dyndbg." + utohexstr(
Result.low());
1541 SaveModule(
"dyndbg.0.input", *M);
1543 auto UnoptM = prepareForDynamicDebugging(M, PromotionSuffix);
1544 SaveModule(
"dyndbg.1.inner", *UnoptM);
1546 if (!CGOpts.DiscardDynamicDebuggingDebugModule) {
1548 UnoptOpts.OptimizationLevel = 0;
1549 UnoptOpts.OptimizeSize = 0;
1550 EmitAssemblyHelper AsmHelper(CI, UnoptOpts, UnoptM.get(), VFS);
1554 std::unique_ptr<llvm::raw_pwrite_stream> UnoptOS =
1555 std::make_unique<llvm::raw_svector_ostream>(UnoptBuf);
1562 assert(!UnoptBuf.empty() &&
"Expected emitAssembly to fill UnoptBuf");
1565 StringRef SR(UnoptBuf.data(), UnoptBuf.size());
1566 std::unique_ptr<MemoryBuffer> Buf =
1567 MemoryBuffer::getMemBuffer(SR,
"",
false);
1569 GlobalVariable *EmbeddedGV =
1570 llvm::embedBufferInModule(*M, *Buf,
".debug_llvm_dyndbg", Align(8),
1573 auto &
C = M->getContext();
1574 auto getU32Metadata = [&
C](
unsigned Val) {
1575 return ConstantAsMetadata::get(ConstantInt::get(
C, APInt(32, Val)));
1577 EmbeddedGV->addMetadata(
1578 LLVMContext::MD_elf_section_properties,
1579 *MDTuple::get(
C, { getU32Metadata(ELF::SHT_LLVM_DYNDBG_ELF),
1580 getU32Metadata(0)}));
1582 SaveModule(
"dyndbg.2.outer", *M);
1586 StringRef TDesc, llvm::Module *M,
1589 std::unique_ptr<raw_pwrite_stream> OS,
1591 llvm::TimeTraceScope TimeScope(
"Backend");
1594 std::unique_ptr<llvm::Module> EmptyModule;
1597 auto BypassSandbox = sys::sandbox::scopedDisable();
1601 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1602 if (
Error E = llvm::getModuleSummaryIndexForFile(
1605 .moveInto(CombinedIndex)) {
1606 logAllUnhandledErrors(std::move(E), errs(),
1607 "Error loading index file '" +
1615 if (CombinedIndex) {
1616 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1628 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1629 EmptyModule->setTargetTriple(M->getTargetTriple());
1630 M = EmptyModule.get();
1634 bool EnableDynamicDebugging = CGOpts.DynamicDebugging;
1635 if (EnableDynamicDebugging) {
1639 const llvm::Target *TheTarget =
1640 TargetRegistry::lookupTarget(M->getTargetTriple(),
Error);
1641 if (!TheTarget && !CGOpts.DiscardDynamicDebuggingDebugModule) {
1642 Diags.
Report(diag::warn_dyndbg_unable_to_create_target) <<
Error;
1643 EnableDynamicDebugging =
false;
1650 if (CGOpts.getProfileInstr() != driver::ProfileInstrKind::ProfileNone) {
1651 Diags.
Report(diag::err_dyndbg_no_instrumentation);
1652 EnableDynamicDebugging =
false;
1655 if (EnableDynamicDebugging)
1658 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1659 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1664 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1665 if (DLDesc != TDesc) {
1666 Diags.
Report(diag::err_data_layout_mismatch) << DLDesc << TDesc;
1674 llvm::MemoryBufferRef Buf) {
1677 llvm::embedBitcodeInModule(
1689 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1690 VFS.getBufferForFile(OffloadObject);
1691 if (ObjectOrErr.getError()) {
1692 Diags.
Report(diag::err_failed_to_open_for_embedding) << OffloadObject;
1696 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1697 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 FloatABI
The ABI to use for passing floating point arguments.
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
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.