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/Bitcode/BitcodeReader.h"
26#include "llvm/Bitcode/BitcodeWriter.h"
27#include "llvm/Bitcode/BitcodeWriterPass.h"
28#include "llvm/CodeGen/TargetSubtargetInfo.h"
29#include "llvm/Config/llvm-config.h"
30#include "llvm/Frontend/Driver/CodeGenOptions.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/DebugInfo.h"
33#include "llvm/IR/LLVMRemarkStreamer.h"
34#include "llvm/IR/LegacyPassManager.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/ModuleSummaryIndex.h"
37#include "llvm/IR/PassManager.h"
38#include "llvm/IR/Verifier.h"
39#include "llvm/IRPrinter/IRPrintingPasses.h"
40#include "llvm/LTO/LTOBackend.h"
41#include "llvm/MC/TargetRegistry.h"
42#include "llvm/Object/OffloadBinary.h"
43#include "llvm/Passes/PassBuilder.h"
44#include "llvm/Passes/StandardInstrumentations.h"
45#include "llvm/Plugins/PassPlugin.h"
46#include "llvm/ProfileData/InstrProfCorrelator.h"
47#include "llvm/Support/BuryPointer.h"
48#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/IOSandbox.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/PrettyStackTrace.h"
53#include "llvm/Support/Program.h"
54#include "llvm/Support/TimeProfiler.h"
55#include "llvm/Support/Timer.h"
56#include "llvm/Support/ToolOutputFile.h"
57#include "llvm/Support/VirtualFileSystem.h"
58#include "llvm/Support/raw_ostream.h"
59#include "llvm/Target/TargetMachine.h"
60#include "llvm/Target/TargetOptions.h"
61#include "llvm/TargetParser/SubtargetFeature.h"
62#include "llvm/TargetParser/Triple.h"
63#include "llvm/Transforms/HipStdPar/HipStdPar.h"
64#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
65#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
66#include "llvm/Transforms/IPO/LowerTypeTests.h"
67#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
68#include "llvm/Transforms/InstCombine/InstCombine.h"
69#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
70#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
71#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
72#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
73#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
74#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
75#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
76#include "llvm/Transforms/Instrumentation/KCFI.h"
77#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
78#include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
79#include "llvm/Transforms/Instrumentation/MemProfUse.h"
80#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
81#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
82#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
83#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
84#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
85#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
86#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
87#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
88#include "llvm/Transforms/ObjCARC.h"
89#include "llvm/Transforms/Scalar/EarlyCSE.h"
90#include "llvm/Transforms/Scalar/GVN.h"
91#include "llvm/Transforms/Scalar/JumpThreading.h"
92#include "llvm/Transforms/Utils/Debugify.h"
93#include "llvm/Transforms/Utils/ModuleUtils.h"
100#define HANDLE_EXTENSION(Ext) \
101 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
102#include "llvm/Support/Extension.def"
107 "sanitizer-early-opt-ep", cl::Optional,
108 cl::desc(
"Insert sanitizers on OptimizerEarlyEP."));
113 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
115 "Function attribute to apply to cold functions as determined by PGO"),
116 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default,
"default",
117 "Default (no attribute)"),
118 clEnumValN(PGOOptions::ColdFuncOpt::OptSize,
"optsize",
119 "Mark cold functions with optsize."),
120 clEnumValN(PGOOptions::ColdFuncOpt::MinSize,
"minsize",
121 "Mark cold functions with minsize."),
122 clEnumValN(PGOOptions::ColdFuncOpt::OptNone,
"optnone",
123 "Mark cold functions with optnone.")));
125LLVM_ABI
extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
135 ? llvm::driver::getDefaultProfileGenName()
137 if (CodeGenOpts.ContinuousProfileSync)
144class EmitAssemblyHelper {
145 CompilerInstance &CI;
146 DiagnosticsEngine &Diags;
147 const CodeGenOptions &CodeGenOpts;
148 const clang::TargetOptions &TargetOpts;
149 const LangOptions &LangOpts;
150 llvm::Module *TheModule;
151 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
153 std::unique_ptr<raw_pwrite_stream> OS;
157 TargetIRAnalysis getTargetIRAnalysis()
const {
159 return TM->getTargetIRAnalysis();
161 return TargetIRAnalysis();
172 void CreateTargetMachine(
bool MustCreateTM);
174 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
176 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
177 llvm::sys::fs::OF_None);
179 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
185 void RunOptimizationPipeline(
186 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
187 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
189 std::unique_ptr<raw_pwrite_stream> &OS,
190 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
197 bool shouldEmitRegularLTOSummary()
const {
198 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
199 TargetTriple.getVendor() != llvm::Triple::Apple;
205 bool shouldEmitUnifiedLTOModueFlag()
const {
206 return CodeGenOpts.UnifiedLTO &&
207 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
211 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
213 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
214 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
215 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
216 TheModule(M), VFS(std::move(VFS)),
217 TargetTriple(TheModule->getTargetTriple()) {}
219 ~EmitAssemblyHelper() {
220 if (CodeGenOpts.DisableFree)
221 BuryPointer(std::move(TM));
224 std::unique_ptr<TargetMachine> TM;
227 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
228 BackendConsumer *BC);
232static SanitizerCoverageOptions
234 SanitizerCoverageOptions Opts;
236 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
237 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
238 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
239 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
240 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
241 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
242 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
243 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
244 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
245 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
246 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
247 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
248 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
249 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
250 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
251 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
252 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
253 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
257static SanitizerBinaryMetadataOptions
259 SanitizerBinaryMetadataOptions Opts;
260 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
261 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
262 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
271 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
273 switch (
T.getObjectFormat()) {
278 return !CGOpts.DisableIntegratedAS;
280 llvm::report_fatal_error(
"ASan not implemented for GOFF");
282 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
284 case Triple::DXContainer:
286 case Triple::UnknownObjectFormat:
292static std::optional<llvm::CodeModel::Model>
294 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
295 .Case(
"tiny", llvm::CodeModel::Tiny)
296 .Case(
"small", llvm::CodeModel::Small)
297 .Case(
"kernel", llvm::CodeModel::Kernel)
298 .Case(
"medium", llvm::CodeModel::Medium)
299 .Case(
"large", llvm::CodeModel::Large)
300 .Cases({
"default",
""}, ~1u)
302 assert(CodeModel != ~0u &&
"invalid code model!");
303 if (CodeModel == ~1u)
305 return static_cast<llvm::CodeModel::Model
>(CodeModel);
310 return CodeGenFileType::ObjectFile;
312 return CodeGenFileType::Null;
315 return CodeGenFileType::AssemblyFile;
325 StringRef MainFilename) {
327 return std::string{};
329 std::string FlatCmdLine;
330 raw_string_ostream OS(FlatCmdLine);
331 bool PrintedOneArg =
false;
332 if (!StringRef(Args[0]).
contains(
"-cc1")) {
333 llvm::sys::printArg(OS,
"-cc1",
true);
334 PrintedOneArg =
true;
336 for (
unsigned i = 0; i < Args.size(); i++) {
337 StringRef Arg = Args[i];
340 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
344 if (Arg.starts_with(
"-object-file-name") || Arg == MainFilename)
347 if (Arg.starts_with(
"-fmessage-length"))
351 llvm::sys::printArg(OS, Arg,
true);
352 PrintedOneArg =
true;
359 llvm::TargetOptions &Options) {
364 switch (LangOpts.getThreadModel()) {
366 Options.ThreadModel = llvm::ThreadModel::POSIX;
369 Options.ThreadModel = llvm::ThreadModel::Single;
374 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
376 "Invalid Floating Point ABI!");
377 Options.FloatABIType =
378 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
379 .Case(
"soft", llvm::FloatABI::Soft)
380 .Case(
"softfp", llvm::FloatABI::Soft)
381 .Case(
"hard", llvm::FloatABI::Hard)
382 .Default(llvm::FloatABI::Default);
385 switch (LangOpts.getDefaultFPContractMode()) {
389 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
393 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
396 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
400 Options.BinutilsVersion =
401 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
402 Options.UseInitArray = CodeGenOpts.UseInitArray;
403 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
409 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
411 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
413 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
415 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
417 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
418 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
419 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
421 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
423 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
424 .Case(
"all", llvm::BasicBlockSection::All)
425 .StartsWith(
"list=", llvm::BasicBlockSection::List)
426 .Case(
"none", llvm::BasicBlockSection::None)
427 .Default(llvm::BasicBlockSection::None);
429 if (Options.BBSections == llvm::BasicBlockSection::List) {
430 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
434 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
435 << MBOrErr.getError().message();
438 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
441 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
442 Options.EnableStaticDataPartitioning =
443 CodeGenOpts.PartitionStaticDataSections;
444 Options.FunctionSections = CodeGenOpts.FunctionSections;
445 Options.DataSections = CodeGenOpts.DataSections;
446 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
447 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
448 Options.UniqueBasicBlockSectionNames =
449 CodeGenOpts.UniqueBasicBlockSectionNames;
450 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
451 Options.TLSSize = CodeGenOpts.TLSSize;
452 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
453 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
454 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
455 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
457 Options.EmitAddrsig = CodeGenOpts.Addrsig;
458 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
459 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
460 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
461 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
462 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
463 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
464 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
466 Options.Hotpatch = CodeGenOpts.HotPatch;
467 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
468 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
470 convertDriverVectorLibraryToVectorLibrary(CodeGenOpts.getVecLib());
472 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
474 Options.SwiftAsyncFramePointer =
475 SwiftAsyncFramePointerMode::DeploymentBased;
479 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
483 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
488 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
489 Options.MCOptions.EmitCompactUnwindNonCanonical =
490 CodeGenOpts.EmitCompactUnwindNonCanonical;
491 Options.MCOptions.EmitSFrameUnwind = CodeGenOpts.EmitSFrameUnwind;
492 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
493 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
494 Options.MCOptions.MCUseDwarfDirectory =
495 CodeGenOpts.NoDwarfDirectoryAsm
496 ? llvm::MCTargetOptions::DisableDwarfDirectory
497 : llvm::MCTargetOptions::EnableDwarfDirectory;
498 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
499 Options.MCOptions.MCIncrementalLinkerCompatible =
500 CodeGenOpts.IncrementalLinkerCompatible;
501 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
502 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
503 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
504 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
505 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
506 Options.MCOptions.Crel = CodeGenOpts.Crel;
507 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
508 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
509 Options.MCOptions.CompressDebugSections =
510 CodeGenOpts.getCompressDebugSections();
511 if (CodeGenOpts.OutputAsmVariant != 3)
512 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
513 Options.MCOptions.ABIName = TargetOpts.
ABI;
514 for (
const auto &Entry : HSOpts.UserEntries)
515 if (!Entry.IsFramework &&
519 Options.MCOptions.IASSearchPaths.push_back(
520 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
521 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
525 Options.MCOptions.PPCUseFullRegisterNames =
526 CodeGenOpts.PPCUseFullRegisterNames;
527 Options.MisExpect = CodeGenOpts.MisExpect;
532static std::optional<GCOVOptions>
543 Options.NoRedZone = CodeGenOpts.DisableRedZone;
546 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
550static std::optional<InstrProfOptions>
555 InstrProfOptions Options;
556 Options.NoRedZone = CodeGenOpts.DisableRedZone;
560 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
565 vfs::FileSystem &VFS) {
567 BackendArgs.push_back(
"clang");
569 BackendArgs.push_back(
"-debug-pass");
570 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
573 BackendArgs.push_back(
"-limit-float-precision");
580 if (BackendArgs.size() == 1)
582 BackendArgs.push_back(
nullptr);
586 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
591void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
594 const llvm::Triple &Triple = TheModule->getTargetTriple();
595 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
598 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
602 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
603 std::string FeaturesStr =
606 std::optional<CodeGenOptLevel> OptLevelOrNone =
607 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
608 assert(OptLevelOrNone &&
"Invalid optimization level!");
609 CodeGenOptLevel OptLevel = *OptLevelOrNone;
611 llvm::TargetOptions Options;
614 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
615 Options, RM, CM, OptLevel));
621 switch (Opts.OptimizationLevel) {
623 llvm_unreachable(
"Invalid optimization level!");
626 return OptimizationLevel::O0;
629 return OptimizationLevel::O1;
632 switch (Opts.OptimizeSize) {
634 llvm_unreachable(
"Invalid optimization level for size!");
637 return OptimizationLevel::O2;
640 return OptimizationLevel::Os;
643 return OptimizationLevel::Oz;
647 return OptimizationLevel::O3;
654 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
655 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
656 TargetTriple.isARM() || TargetTriple.isThumb())
660 PB.registerOptimizerLastEPCallback(
661 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
662 if (Level == OptimizationLevel::O0 &&
664 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
669 PB.registerPeepholeEPCallback(
670 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
671 if (Level != OptimizationLevel::O0 &&
673 FPM.addPass(KCFIPass());
680 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
681 ThinOrFullLTOPhase) {
685 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
691 MPM.addPass(SanitizerBinaryMetadataPass(
693 PB.getVirtualFileSystemPtr(),
697 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
699 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
702 MemorySanitizerOptions
options(TrackOrigins, Recover, CompileKernel,
703 CodeGenOpts.SanitizeMemoryParamRetval);
704 MPM.addPass(MemorySanitizerPass(
options));
705 if (Level != OptimizationLevel::O0) {
710 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
711 FunctionPassManager FPM;
712 FPM.addPass(EarlyCSEPass(
true ));
713 FPM.addPass(InstCombinePass());
714 FPM.addPass(JumpThreadingPass());
715 FPM.addPass(GVNPass());
716 FPM.addPass(InstCombinePass());
717 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
721 MSanPass(SanitizerKind::Memory,
false);
722 MSanPass(SanitizerKind::KernelMemory,
true);
724 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
725 MPM.addPass(ModuleThreadSanitizerPass());
726 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
730 MPM.addPass(TypeSanitizerPass());
732 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
733 MPM.addPass(NumericalStabilitySanitizerPass());
735 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
736 MPM.addPass(RealtimeSanitizerPass());
738 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
741 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
742 llvm::AsanDtorKind DestructorKind =
743 CodeGenOpts.getSanitizeAddressDtor();
744 AddressSanitizerOptions Opts;
745 Opts.CompileKernel = CompileKernel;
747 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
748 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
749 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
753 ASanPass(SanitizerKind::Address,
false);
754 ASanPass(SanitizerKind::KernelAddress,
true);
756 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
759 MPM.addPass(HWAddressSanitizerPass(
760 {CompileKernel, Recover,
761 CodeGenOpts.OptimizationLevel == 0}));
764 HWASanPass(SanitizerKind::HWAddress,
false);
765 HWASanPass(SanitizerKind::KernelHWAddress,
true);
767 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
769 PB.getVirtualFileSystemPtr()));
773 PB.registerOptimizerEarlyEPCallback(
774 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
775 ThinOrFullLTOPhase Phase) {
776 ModulePassManager NewMPM;
777 SanitizersCallback(NewMPM, Level, Phase);
778 if (!NewMPM.isEmpty()) {
780 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
781 MPM.addPass(std::move(NewMPM));
786 PB.registerOptimizerLastEPCallback(SanitizersCallback);
795 uint64_t AllowRuntimeCheckSkipHotCutoff =
800 SanitizerKind::Address | SanitizerKind::KernelAddress |
801 SanitizerKind::Thread | SanitizerKind::Memory |
802 SanitizerKind::KernelMemory | SanitizerKind::HWAddress |
803 SanitizerKind::KernelHWAddress);
806 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
808 LowerAllowSanitize) {
810 PB.registerOptimizerEarlyEPCallback(
811 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
812 ModulePassManager &MPM, OptimizationLevel Level,
813 ThinOrFullLTOPhase Phase) {
814 LowerAllowCheckPass::Options Opts;
816 if (ScaledCutoffs.has_value())
817 Opts.cutoffs = ScaledCutoffs.value();
818 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
820 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
825void EmitAssemblyHelper::RunOptimizationPipeline(
826 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
827 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
828 std::optional<PGOOptions> PGOOpt;
835 CodeGenOpts.DebugInfoForProfiling,
837 CodeGenOpts.AtomicProfileUpdate);
841 : PGOOptions::NoCSAction;
846 CodeGenOpts.DebugInfoForProfiling);
853 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
857 PGOOptions::NoAction, PGOOptions::NoCSAction,
859 else if (CodeGenOpts.PseudoProbeForProfiling)
861 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
863 CodeGenOpts.DebugInfoForProfiling,
true);
864 else if (CodeGenOpts.DebugInfoForProfiling)
866 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
872 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
875 assert(PGOOpt->Action != PGOOptions::IRInstr &&
876 PGOOpt->Action != PGOOptions::SampleUse &&
877 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
880 PGOOpt->CSAction = PGOOptions::CSIRInstr;
883 "", PGOOptions::NoAction,
885 CodeGenOpts.DebugInfoForProfiling);
888 TM->setPGOOption(PGOOpt);
890 PipelineTuningOptions PTO;
891 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
892 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
893 PTO.LoopFusion = CodeGenOpts.FuseLoops;
896 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
897 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
898 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
899 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
902 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
903 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
904 PTO.DevirtualizeSpeculatively = CodeGenOpts.DevirtualizeSpeculatively;
906 LoopAnalysisManager LAM;
907 FunctionAnalysisManager FAM;
908 CGSCCAnalysisManager CGAM;
909 ModuleAnalysisManager MAM;
911 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
912 PassInstrumentationCallbacks PIC;
913 PrintPassOptions PrintPassOpts;
914 PrintPassOpts.Indent = DebugPassStructure;
915 PrintPassOpts.SkipAnalyses = DebugPassStructure;
916 StandardInstrumentations SI(
917 TheModule->getContext(),
918 (CodeGenOpts.DebugPassManager || DebugPassStructure),
919 CodeGenOpts.VerifyEach, PrintPassOpts);
920 SI.registerCallbacks(PIC, &MAM);
924 switch (CodeGenOpts.getAssignmentTrackingMode()) {
925 case CodeGenOptions::AssignmentTrackingOpts::Forced:
926 PB.registerPipelineStartEPCallback(
927 [&](ModulePassManager &MPM, OptimizationLevel Level) {
928 MPM.addPass(AssignmentTrackingPass());
931 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
934 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
935 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
936 PB.registerPipelineStartEPCallback(
937 [&](ModulePassManager &MPM, OptimizationLevel Level) {
939 if (Level != OptimizationLevel::O0)
940 MPM.addPass(AssignmentTrackingPass());
944 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
949 DebugifyEachInstrumentation Debugify;
950 DebugInfoPerPass DebugInfoBeforePass;
951 if (CodeGenOpts.EnableDIPreservationVerify) {
952 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
953 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
956 Debugify.setOrigDIVerifyBugsReportFilePath(
958 Debugify.registerCallbacks(PIC, MAM);
960#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
967 if (!F.getSubprogram())
969 for (BasicBlock &BB : F)
970 for (Instruction &I : BB)
971 if (!I.getDebugLoc())
972 I.setDebugLoc(DebugLoc::getCompilerGenerated());
977 for (
const std::unique_ptr<PassPlugin> &Plugin : CI.
getPassPlugins())
978 Plugin->registerPassBuilderCallbacks(PB);
981#define HANDLE_EXTENSION(Ext) \
982 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
983#include "llvm/Support/Extension.def"
987 std::unique_ptr<TargetLibraryInfoImpl> TLII(
988 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
989 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
992 PB.registerModuleAnalyses(MAM);
993 PB.registerCGSCCAnalyses(CGAM);
994 PB.registerFunctionAnalyses(FAM);
995 PB.registerLoopAnalyses(LAM);
996 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
998 ModulePassManager MPM;
1000 if (CodeGenOpts.VerifyModule)
1001 MPM.addPass(VerifierPass());
1003 if (!CodeGenOpts.DisableLLVMPasses) {
1008 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1009 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1011 if (LangOpts.ObjCAutoRefCount) {
1012 PB.registerPipelineStartEPCallback(
1013 [](ModulePassManager &MPM, OptimizationLevel Level) {
1014 if (Level != OptimizationLevel::O0)
1016 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1018 PB.registerScalarOptimizerLateEPCallback(
1019 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1020 if (Level != OptimizationLevel::O0)
1021 FPM.addPass(ObjCARCOptPass());
1031 if (IsThinLTOPostLink)
1032 PB.registerPipelineStartEPCallback(
1033 [](ModulePassManager &MPM, OptimizationLevel Level) {
1034 MPM.addPass(LowerTypeTestsPass(
1037 lowertypetests::DropTestKind::Assume));
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 }
else if (PrepareForThinLTO) {
1120 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1121 }
else if (PrepareForLTO) {
1122 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1124 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1129 if (CodeGenOpts.LinkBitcodePostopt)
1130 MPM.addPass(LinkInModulesPass(BC));
1132 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1133 LangOpts.HIPStdParInterposeAlloc)
1134 MPM.addPass(HipStdParAllocationInterpositionPass());
1142 MPM.addPass(VerifierPass());
1145 CodeGenOpts.FatLTO) {
1146 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1147 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1148 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1149 CodeGenOpts.EnableSplitLTOUnit);
1156 MPM.addPass(ThinLTOBitcodeWriterPass(
1157 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1159 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1165 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1166 if (EmitLTOSummary) {
1167 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1168 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1169 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1170 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1174 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1177 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1182 if (shouldEmitUnifiedLTOModueFlag() &&
1183 !TheModule->getModuleFlag(
"UnifiedLTO"))
1184 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1191 if (PrintPipelinePasses) {
1192 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1193 auto PassName = PIC.getPassNameForClassName(ClassName);
1194 return PassName.empty() ? ClassName : PassName;
1202 PrettyStackTraceString CrashInfo(
"Optimizer");
1203 llvm::TimeTraceScope TimeScope(
"Optimizer");
1209 MPM.run(*TheModule, MAM);
1215void EmitAssemblyHelper::RunCodegenPipeline(
1216 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1217 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1227 for (
const std::unique_ptr<llvm::PassPlugin> &Plugin : CI.
getPassPlugins()) {
1228 if (Plugin->invokePreCodeGenCallback(*TheModule, *TM, CGFT, *OS))
1235 legacy::PassManager CodeGenPasses;
1238 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1240 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1241 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1242 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
1244 const llvm::TargetOptions &Options = TM->Options;
1245 CodeGenPasses.add(
new RuntimeLibraryInfoWrapper(
1246 TargetTriple, Options.ExceptionModel, Options.FloatABIType,
1247 Options.EABIVersion, Options.MCOptions.ABIName, Options.VecLib));
1255 if (TM->addPassesToEmitFile(CodeGenPasses, *OS,
1256 DwoOS ? &DwoOS->os() :
nullptr, CGFT,
1257 !CodeGenOpts.VerifyModule)) {
1258 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
1265 if (PrintPipelinePasses) {
1270 PrettyStackTraceString CrashInfo(
"Code generation");
1271 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1274 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1277 CodeGenPasses.run(*TheModule);
1284 std::unique_ptr<raw_pwrite_stream> OS,
1285 BackendConsumer *BC) {
1289 CreateTargetMachine(RequiresCodeGen);
1291 if (RequiresCodeGen && !TM)
1294 TheModule->setDataLayout(TM->createDataLayout());
1297 cl::PrintOptionValues();
1299 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1300 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1301 RunCodegenPipeline(Action, OS, DwoOS);
1311 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1312 std::string SampleProfile, std::string ProfileRemapping,
1317 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1318 ModuleToDefinedGVSummaries;
1319 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1326 FunctionImporter::ImportIDTable ImportIDs;
1327 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1328 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1331 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1332 return std::make_unique<CachedFileStream>(std::move(OS),
1333 CGOpts.ObjectFilenameForDebug);
1336 if (CGOpts.SaveTempsFilePrefix !=
"") {
1337 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1339 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1340 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1345 Conf.CPU = TOpts.CPU;
1347 Conf.MAttrs = TOpts.Features;
1348 Conf.RelocModel = CGOpts.RelocationModel;
1349 std::optional<CodeGenOptLevel> OptLevelOrNone =
1350 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1351 assert(OptLevelOrNone &&
"Invalid optimization level!");
1352 Conf.CGOptLevel = *OptLevelOrNone;
1353 Conf.OptLevel = CGOpts.OptimizationLevel;
1355 Conf.SampleProfile = std::move(SampleProfile);
1356 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1357 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1358 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1361 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1362 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1363 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1366 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1369 if (CGOpts.hasProfileCSIRInstr()) {
1370 Conf.RunCSIRInstr =
true;
1372 }
else if (CGOpts.hasProfileCSIRUse()) {
1373 Conf.RunCSIRInstr =
false;
1374 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1377 Conf.ProfileRemapping = std::move(ProfileRemapping);
1378 Conf.DebugPassManager = CGOpts.DebugPassManager;
1379 Conf.VerifyEach = CGOpts.VerifyEach;
1380 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1381 Conf.RemarksFilename = CGOpts.OptRecordFile;
1382 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1383 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1384 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1385 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1388 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1393 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1394 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1399 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1400 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1411 finalizeLLVMOptimizationRemarks(M->getContext());
1413 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1414 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1415 nullptr, Conf.CodeGenOnly,
1416 nullptr, CGOpts.CmdArgs)) {
1417 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1418 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1424 StringRef TDesc, llvm::Module *M,
1427 std::unique_ptr<raw_pwrite_stream> OS,
1429 llvm::TimeTraceScope TimeScope(
"Backend");
1432 std::unique_ptr<llvm::Module> EmptyModule;
1435 auto BypassSandbox = sys::sandbox::scopedDisable();
1439 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1440 if (
Error E = llvm::getModuleSummaryIndexForFile(
1443 .moveInto(CombinedIndex)) {
1444 logAllUnhandledErrors(std::move(E), errs(),
1445 "Error loading index file '" +
1453 if (CombinedIndex) {
1454 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1466 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1467 EmptyModule->setTargetTriple(M->getTargetTriple());
1468 M = EmptyModule.get();
1472 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1473 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1478 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1479 if (DLDesc != TDesc) {
1480 Diags.
Report(diag::err_data_layout_mismatch) << DLDesc << TDesc;
1488 llvm::MemoryBufferRef Buf) {
1491 llvm::embedBitcodeInModule(
1503 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1504 VFS.getBufferForFile(OffloadObject);
1505 if (ObjectOrErr.getError()) {
1506 Diags.
Report(diag::err_failed_to_open_for_embedding) << OffloadObject;
1510 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1511 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 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::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)
static std::string flattenClangCommandLine(ArrayRef< std::string > Args, StringRef MainFilename)
Defines the Diagnostic-related interfaces.
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 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::string StackUsageOutput
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
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.
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()
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.
@ 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'.
The JSON file list parser is used to communicate input to InstallAPI.
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."))
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.