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/PassPlugin.h"
45#include "llvm/Passes/StandardInstrumentations.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);
177 bool AddEmitPasses(legacy::PassManager &CodeGenPasses,
BackendAction Action,
178 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
180 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
182 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
183 llvm::sys::fs::OF_None);
185 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
191 void RunOptimizationPipeline(
192 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
193 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
195 std::unique_ptr<raw_pwrite_stream> &OS,
196 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
203 bool shouldEmitRegularLTOSummary()
const {
204 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
205 TargetTriple.getVendor() != llvm::Triple::Apple;
211 bool shouldEmitUnifiedLTOModueFlag()
const {
212 return CodeGenOpts.UnifiedLTO &&
213 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
217 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
219 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
220 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
221 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
222 TheModule(M), VFS(std::move(VFS)),
223 TargetTriple(TheModule->getTargetTriple()) {}
225 ~EmitAssemblyHelper() {
226 if (CodeGenOpts.DisableFree)
227 BuryPointer(std::move(TM));
230 std::unique_ptr<TargetMachine> TM;
233 void emitAssembly(
BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
234 BackendConsumer *BC);
238static SanitizerCoverageOptions
240 SanitizerCoverageOptions Opts;
242 static_cast<SanitizerCoverageOptions::Type
>(CGOpts.SanitizeCoverageType);
243 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
244 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
245 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
246 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
247 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
248 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
249 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
250 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
251 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
252 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
253 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
254 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
255 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
256 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
257 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
258 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
259 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
263static SanitizerBinaryMetadataOptions
265 SanitizerBinaryMetadataOptions Opts;
266 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
267 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
268 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
277 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
279 switch (
T.getObjectFormat()) {
284 return !CGOpts.DisableIntegratedAS;
286 llvm::report_fatal_error(
"ASan not implemented for GOFF");
288 llvm::report_fatal_error(
"ASan not implemented for XCOFF.");
290 case Triple::DXContainer:
292 case Triple::UnknownObjectFormat:
298static std::optional<llvm::CodeModel::Model>
300 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.
CodeModel)
301 .Case(
"tiny", llvm::CodeModel::Tiny)
302 .Case(
"small", llvm::CodeModel::Small)
303 .Case(
"kernel", llvm::CodeModel::Kernel)
304 .Case(
"medium", llvm::CodeModel::Medium)
305 .Case(
"large", llvm::CodeModel::Large)
306 .Cases({
"default",
""}, ~1u)
308 assert(CodeModel != ~0u &&
"invalid code model!");
309 if (CodeModel == ~1u)
311 return static_cast<llvm::CodeModel::Model
>(CodeModel);
316 return CodeGenFileType::ObjectFile;
318 return CodeGenFileType::Null;
321 return CodeGenFileType::AssemblyFile;
331 StringRef MainFilename) {
333 return std::string{};
335 std::string FlatCmdLine;
336 raw_string_ostream OS(FlatCmdLine);
337 bool PrintedOneArg =
false;
338 if (!StringRef(Args[0]).
contains(
"-cc1")) {
339 llvm::sys::printArg(OS,
"-cc1",
true);
340 PrintedOneArg =
true;
342 for (
unsigned i = 0; i < Args.size(); i++) {
343 StringRef Arg = Args[i];
346 if (Arg ==
"-main-file-name" || Arg ==
"-o") {
350 if (Arg.starts_with(
"-object-file-name") || Arg == MainFilename)
353 if (Arg.starts_with(
"-fmessage-length"))
357 llvm::sys::printArg(OS, Arg,
true);
358 PrintedOneArg =
true;
365 llvm::TargetOptions &Options) {
370 switch (LangOpts.getThreadModel()) {
372 Options.ThreadModel = llvm::ThreadModel::POSIX;
375 Options.ThreadModel = llvm::ThreadModel::Single;
380 assert((CodeGenOpts.
FloatABI ==
"soft" || CodeGenOpts.
FloatABI ==
"softfp" ||
382 "Invalid Floating Point ABI!");
383 Options.FloatABIType =
384 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.
FloatABI)
385 .Case(
"soft", llvm::FloatABI::Soft)
386 .Case(
"softfp", llvm::FloatABI::Soft)
387 .Case(
"hard", llvm::FloatABI::Hard)
388 .Default(llvm::FloatABI::Default);
391 switch (LangOpts.getDefaultFPContractMode()) {
395 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
399 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
402 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
406 Options.BinutilsVersion =
407 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.
BinutilsVersion);
408 Options.UseInitArray = CodeGenOpts.UseInitArray;
409 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
415 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
417 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
419 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
421 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
423 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
424 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
425 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
427 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
429 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.
BBSections)
430 .Case(
"all", llvm::BasicBlockSection::All)
431 .StartsWith(
"list=", llvm::BasicBlockSection::List)
432 .Case(
"none", llvm::BasicBlockSection::None)
433 .Default(llvm::BasicBlockSection::None);
435 if (Options.BBSections == llvm::BasicBlockSection::List) {
436 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
440 Diags.
Report(diag::err_fe_unable_to_load_basic_block_sections_file)
441 << MBOrErr.getError().message();
444 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
447 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
448 Options.FunctionSections = CodeGenOpts.FunctionSections;
449 Options.DataSections = CodeGenOpts.DataSections;
450 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
451 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
452 Options.UniqueBasicBlockSectionNames =
453 CodeGenOpts.UniqueBasicBlockSectionNames;
454 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
455 Options.TLSSize = CodeGenOpts.TLSSize;
456 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
457 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
458 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
459 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
461 Options.EmitAddrsig = CodeGenOpts.Addrsig;
462 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
463 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
464 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
465 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
466 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
467 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
468 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
470 Options.Hotpatch = CodeGenOpts.HotPatch;
471 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
472 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
474 switch (CodeGenOpts.getVecLib()) {
475 case llvm::driver::VectorLibrary::NoLibrary:
476 Options.VecLib = llvm::VectorLibrary::NoLibrary;
478 case llvm::driver::VectorLibrary::Accelerate:
479 Options.VecLib = llvm::VectorLibrary::Accelerate;
481 case llvm::driver::VectorLibrary::Darwin_libsystem_m:
482 Options.VecLib = llvm::VectorLibrary::DarwinLibSystemM;
484 case llvm::driver::VectorLibrary::LIBMVEC:
485 Options.VecLib = llvm::VectorLibrary::LIBMVEC;
487 case llvm::driver::VectorLibrary::MASSV:
488 Options.VecLib = llvm::VectorLibrary::MASSV;
490 case llvm::driver::VectorLibrary::SVML:
491 Options.VecLib = llvm::VectorLibrary::SVML;
493 case llvm::driver::VectorLibrary::SLEEF:
494 Options.VecLib = llvm::VectorLibrary::SLEEFGNUABI;
496 case llvm::driver::VectorLibrary::ArmPL:
497 Options.VecLib = llvm::VectorLibrary::ArmPL;
499 case llvm::driver::VectorLibrary::AMDLIBM:
500 Options.VecLib = llvm::VectorLibrary::AMDLIBM;
504 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
506 Options.SwiftAsyncFramePointer =
507 SwiftAsyncFramePointerMode::DeploymentBased;
511 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
515 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
520 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
521 Options.MCOptions.EmitCompactUnwindNonCanonical =
522 CodeGenOpts.EmitCompactUnwindNonCanonical;
523 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
524 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
525 Options.MCOptions.MCUseDwarfDirectory =
526 CodeGenOpts.NoDwarfDirectoryAsm
527 ? llvm::MCTargetOptions::DisableDwarfDirectory
528 : llvm::MCTargetOptions::EnableDwarfDirectory;
529 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
530 Options.MCOptions.MCIncrementalLinkerCompatible =
531 CodeGenOpts.IncrementalLinkerCompatible;
532 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
533 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
534 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
535 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
536 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
537 Options.MCOptions.Crel = CodeGenOpts.Crel;
538 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
539 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
540 Options.MCOptions.CompressDebugSections =
541 CodeGenOpts.getCompressDebugSections();
542 if (CodeGenOpts.OutputAsmVariant != 3)
543 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
544 Options.MCOptions.ABIName = TargetOpts.
ABI;
545 for (
const auto &Entry : HSOpts.UserEntries)
546 if (!Entry.IsFramework &&
550 Options.MCOptions.IASSearchPaths.push_back(
551 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
552 Options.MCOptions.Argv0 = CodeGenOpts.
Argv0 ? CodeGenOpts.
Argv0 :
"";
556 Options.MCOptions.PPCUseFullRegisterNames =
557 CodeGenOpts.PPCUseFullRegisterNames;
558 Options.MisExpect = CodeGenOpts.MisExpect;
563static std::optional<GCOVOptions>
574 Options.NoRedZone = CodeGenOpts.DisableRedZone;
577 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
581static std::optional<InstrProfOptions>
586 InstrProfOptions Options;
587 Options.NoRedZone = CodeGenOpts.DisableRedZone;
591 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
596 vfs::FileSystem &VFS) {
598 BackendArgs.push_back(
"clang");
600 BackendArgs.push_back(
"-debug-pass");
601 BackendArgs.push_back(CodeGenOpts.
DebugPass.c_str());
604 BackendArgs.push_back(
"-limit-float-precision");
611 if (BackendArgs.size() == 1)
613 BackendArgs.push_back(
nullptr);
617 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
622void EmitAssemblyHelper::CreateTargetMachine(
bool MustCreateTM) {
625 const llvm::Triple &Triple = TheModule->getTargetTriple();
626 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple,
Error);
629 Diags.
Report(diag::err_fe_unable_to_create_target) <<
Error;
633 std::optional<llvm::CodeModel::Model> CM =
getCodeModel(CodeGenOpts);
634 std::string FeaturesStr =
637 std::optional<CodeGenOptLevel> OptLevelOrNone =
638 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
639 assert(OptLevelOrNone &&
"Invalid optimization level!");
640 CodeGenOptLevel OptLevel = *OptLevelOrNone;
642 llvm::TargetOptions Options;
645 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.
CPU, FeaturesStr,
646 Options, RM, CM, OptLevel));
651bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
653 raw_pwrite_stream &OS,
654 raw_pwrite_stream *DwoOS) {
656 std::unique_ptr<TargetLibraryInfoImpl> TLII(
657 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
658 CodeGenPasses.add(
new TargetLibraryInfoWrapperPass(*TLII));
660 const llvm::TargetOptions &Options = TM->Options;
661 CodeGenPasses.add(
new RuntimeLibraryInfoWrapper(
662 TargetTriple, Options.ExceptionModel, Options.FloatABIType,
663 Options.EABIVersion, Options.MCOptions.ABIName, Options.VecLib));
669 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
670 !CodeGenOpts.VerifyModule)) {
671 Diags.
Report(diag::err_fe_unable_to_interface_with_target);
679 switch (Opts.OptimizationLevel) {
681 llvm_unreachable(
"Invalid optimization level!");
684 return OptimizationLevel::O0;
687 return OptimizationLevel::O1;
690 switch (Opts.OptimizeSize) {
692 llvm_unreachable(
"Invalid optimization level for size!");
695 return OptimizationLevel::O2;
698 return OptimizationLevel::Os;
701 return OptimizationLevel::Oz;
705 return OptimizationLevel::O3;
712 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
713 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
714 TargetTriple.isARM() || TargetTriple.isThumb())
718 PB.registerOptimizerLastEPCallback(
719 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
720 if (Level == OptimizationLevel::O0 &&
722 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
727 PB.registerPeepholeEPCallback(
728 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
729 if (Level != OptimizationLevel::O0 &&
731 FPM.addPass(KCFIPass());
738 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
739 ThinOrFullLTOPhase) {
743 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
749 MPM.addPass(SanitizerBinaryMetadataPass(
751 PB.getVirtualFileSystemPtr(),
755 auto MSanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
757 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
760 MemorySanitizerOptions
options(TrackOrigins, Recover, CompileKernel,
761 CodeGenOpts.SanitizeMemoryParamRetval);
762 MPM.addPass(MemorySanitizerPass(
options));
763 if (Level != OptimizationLevel::O0) {
768 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
769 FunctionPassManager FPM;
770 FPM.addPass(EarlyCSEPass(
true ));
771 FPM.addPass(InstCombinePass());
772 FPM.addPass(JumpThreadingPass());
773 FPM.addPass(GVNPass());
774 FPM.addPass(InstCombinePass());
775 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
779 MSanPass(SanitizerKind::Memory,
false);
780 MSanPass(SanitizerKind::KernelMemory,
true);
782 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread)) {
783 MPM.addPass(ModuleThreadSanitizerPass());
784 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
788 MPM.addPass(TypeSanitizerPass());
790 if (LangOpts.
Sanitize.
has(SanitizerKind::NumericalStability))
791 MPM.addPass(NumericalStabilitySanitizerPass());
793 if (LangOpts.
Sanitize.
has(SanitizerKind::Realtime))
794 MPM.addPass(RealtimeSanitizerPass());
796 auto ASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
799 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
800 llvm::AsanDtorKind DestructorKind =
801 CodeGenOpts.getSanitizeAddressDtor();
802 AddressSanitizerOptions Opts;
803 Opts.CompileKernel = CompileKernel;
805 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
806 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
807 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
811 ASanPass(SanitizerKind::Address,
false);
812 ASanPass(SanitizerKind::KernelAddress,
true);
814 auto HWASanPass = [&](
SanitizerMask Mask,
bool CompileKernel) {
817 MPM.addPass(HWAddressSanitizerPass(
818 {CompileKernel, Recover,
819 CodeGenOpts.OptimizationLevel == 0}));
822 HWASanPass(SanitizerKind::HWAddress,
false);
823 HWASanPass(SanitizerKind::KernelHWAddress,
true);
825 if (LangOpts.
Sanitize.
has(SanitizerKind::DataFlow)) {
827 PB.getVirtualFileSystemPtr()));
831 PB.registerOptimizerEarlyEPCallback(
832 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
833 ThinOrFullLTOPhase Phase) {
834 ModulePassManager NewMPM;
835 SanitizersCallback(NewMPM, Level, Phase);
836 if (!NewMPM.isEmpty()) {
838 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
839 MPM.addPass(std::move(NewMPM));
844 PB.registerOptimizerLastEPCallback(SanitizersCallback);
850 uint64_t AllowRuntimeCheckSkipHotCutoff =
853 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
856 PB.registerOptimizerEarlyEPCallback(
857 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
858 ModulePassManager &MPM, OptimizationLevel Level,
859 ThinOrFullLTOPhase Phase) {
860 LowerAllowCheckPass::Options Opts;
862 if (ScaledCutoffs.has_value())
863 Opts.cutoffs = ScaledCutoffs.value();
864 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
866 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
871void EmitAssemblyHelper::RunOptimizationPipeline(
872 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
873 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
874 std::optional<PGOOptions> PGOOpt;
881 CodeGenOpts.DebugInfoForProfiling,
883 CodeGenOpts.AtomicProfileUpdate);
887 : PGOOptions::NoCSAction;
892 CodeGenOpts.DebugInfoForProfiling);
899 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
903 PGOOptions::NoAction, PGOOptions::NoCSAction,
905 else if (CodeGenOpts.PseudoProbeForProfiling)
907 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
909 CodeGenOpts.DebugInfoForProfiling,
true);
910 else if (CodeGenOpts.DebugInfoForProfiling)
912 PGOOpt = PGOOptions(
"",
"",
"",
"", PGOOptions::NoAction,
918 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
921 assert(PGOOpt->Action != PGOOptions::IRInstr &&
922 PGOOpt->Action != PGOOptions::SampleUse &&
923 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
926 PGOOpt->CSAction = PGOOptions::CSIRInstr;
929 "", PGOOptions::NoAction,
931 CodeGenOpts.DebugInfoForProfiling);
934 TM->setPGOOption(PGOOpt);
936 PipelineTuningOptions PTO;
937 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
938 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
939 PTO.LoopFusion = CodeGenOpts.FuseLoops;
942 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
943 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
944 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
945 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
948 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
949 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
950 PTO.DevirtualizeSpeculatively = CodeGenOpts.DevirtualizeSpeculatively;
952 LoopAnalysisManager LAM;
953 FunctionAnalysisManager FAM;
954 CGSCCAnalysisManager CGAM;
955 ModuleAnalysisManager MAM;
957 bool DebugPassStructure = CodeGenOpts.
DebugPass ==
"Structure";
958 PassInstrumentationCallbacks PIC;
959 PrintPassOptions PrintPassOpts;
960 PrintPassOpts.Indent = DebugPassStructure;
961 PrintPassOpts.SkipAnalyses = DebugPassStructure;
962 StandardInstrumentations SI(
963 TheModule->getContext(),
964 (CodeGenOpts.DebugPassManager || DebugPassStructure),
965 CodeGenOpts.VerifyEach, PrintPassOpts);
966 SI.registerCallbacks(PIC, &MAM);
970 switch (CodeGenOpts.getAssignmentTrackingMode()) {
971 case CodeGenOptions::AssignmentTrackingOpts::Forced:
972 PB.registerPipelineStartEPCallback(
973 [&](ModulePassManager &MPM, OptimizationLevel Level) {
974 MPM.addPass(AssignmentTrackingPass());
977 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
980 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
981 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
982 PB.registerPipelineStartEPCallback(
983 [&](ModulePassManager &MPM, OptimizationLevel Level) {
985 if (Level != OptimizationLevel::O0)
986 MPM.addPass(AssignmentTrackingPass());
990 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
995 DebugifyEachInstrumentation Debugify;
996 DebugInfoPerPass DebugInfoBeforePass;
997 if (CodeGenOpts.EnableDIPreservationVerify) {
998 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
999 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
1002 Debugify.setOrigDIVerifyBugsReportFilePath(
1004 Debugify.registerCallbacks(PIC, MAM);
1006#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
1013 if (!F.getSubprogram())
1015 for (BasicBlock &BB : F)
1016 for (Instruction &I : BB)
1017 if (!I.getDebugLoc())
1018 I.setDebugLoc(DebugLoc::getCompilerGenerated());
1024 auto PassPlugin = PassPlugin::Load(PluginFN);
1026 PassPlugin->registerPassBuilderCallbacks(PB);
1028 Diags.
Report(diag::err_fe_unable_to_load_plugin)
1029 << PluginFN <<
toString(PassPlugin.takeError());
1034#define HANDLE_EXTENSION(Ext) \
1035 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1036#include "llvm/Support/Extension.def"
1040 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1041 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1042 FAM.registerPass([&] {
return TargetLibraryAnalysis(*TLII); });
1045 PB.registerModuleAnalyses(MAM);
1046 PB.registerCGSCCAnalyses(CGAM);
1047 PB.registerFunctionAnalyses(FAM);
1048 PB.registerLoopAnalyses(LAM);
1049 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1051 ModulePassManager MPM;
1053 if (CodeGenOpts.VerifyModule)
1054 MPM.addPass(VerifierPass());
1056 if (!CodeGenOpts.DisableLLVMPasses) {
1061 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1062 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1064 if (LangOpts.ObjCAutoRefCount) {
1065 PB.registerPipelineStartEPCallback(
1066 [](ModulePassManager &MPM, OptimizationLevel Level) {
1067 if (Level != OptimizationLevel::O0)
1069 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1071 PB.registerScalarOptimizerLateEPCallback(
1072 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1073 if (Level != OptimizationLevel::O0)
1074 FPM.addPass(ObjCARCOptPass());
1084 if (IsThinLTOPostLink)
1085 PB.registerPipelineStartEPCallback(
1086 [](ModulePassManager &MPM, OptimizationLevel Level) {
1087 MPM.addPass(LowerTypeTestsPass(
1090 lowertypetests::DropTestKind::Assume));
1095 if (LangOpts.
Sanitize.
has(SanitizerKind::LocalBounds))
1096 PB.registerScalarOptimizerLateEPCallback([
this](FunctionPassManager &FPM,
1097 OptimizationLevel Level) {
1098 BoundsCheckingPass::Options Options;
1101 static_assert(SanitizerKind::SO_LocalBounds <=
1102 std::numeric_limits<
1103 decltype(Options.GuardKind)::value_type>
::max(),
1104 "Update type of llvm.allow.ubsan.check to represent "
1105 "SanitizerKind::SO_LocalBounds.");
1106 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1113 CodeGenOpts.SanitizeMinimalRuntime),
1117 static_cast<bool>(CodeGenOpts.SanitizeHandlerPreserveAllRegs),
1120 FPM.addPass(BoundsCheckingPass(Options));
1123 if (!IsThinLTOPostLink) {
1128 PB.registerPipelineStartEPCallback(
1129 [&](ModulePassManager &MPM, OptimizationLevel Level) {
1130 if (Level == OptimizationLevel::O0 &&
1131 LangOpts.
Sanitize.
has(SanitizerKind::AllocToken)) {
1137 MPM.addPass(InferFunctionAttrsPass());
1142 if (std::optional<GCOVOptions> Options =
1144 PB.registerPipelineStartEPCallback(
1145 [
this, Options](ModulePassManager &MPM, OptimizationLevel Level) {
1149 if (std::optional<InstrProfOptions> Options =
1151 PB.registerPipelineStartEPCallback(
1152 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1153 MPM.addPass(InstrProfilingLoweringPass(*Options,
false));
1159 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1160 OptimizationLevel Level,
1161 ThinOrFullLTOPhase) {
1162 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1163 MPM.addPass(ModuleMemProfilerPass());
1167 if (CodeGenOpts.FatLTO) {
1168 MPM.addPass(PB.buildFatLTODefaultPipeline(
1169 Level, PrepareForThinLTO,
1170 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1171 }
else if (PrepareForThinLTO) {
1172 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1173 }
else if (PrepareForLTO) {
1174 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1176 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1181 if (CodeGenOpts.LinkBitcodePostopt)
1182 MPM.addPass(LinkInModulesPass(BC));
1184 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1185 LangOpts.HIPStdParInterposeAlloc)
1186 MPM.addPass(HipStdParAllocationInterpositionPass());
1194 MPM.addPass(VerifierPass());
1197 CodeGenOpts.FatLTO) {
1198 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1199 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1200 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1201 CodeGenOpts.EnableSplitLTOUnit);
1208 MPM.addPass(ThinLTOBitcodeWriterPass(
1209 *OS, ThinLinkOS ? &ThinLinkOS->os() :
nullptr));
1211 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1217 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1218 if (EmitLTOSummary) {
1219 if (!TheModule->getModuleFlag(
"ThinLTO") && !CodeGenOpts.UnifiedLTO)
1220 TheModule->addModuleFlag(llvm::Module::Error,
"ThinLTO",
uint32_t(0));
1221 if (!TheModule->getModuleFlag(
"EnableSplitLTOUnit"))
1222 TheModule->addModuleFlag(llvm::Module::Error,
"EnableSplitLTOUnit",
1226 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1229 MPM.addPass(PrintModulePass(*OS,
"", CodeGenOpts.EmitLLVMUseLists,
1234 if (shouldEmitUnifiedLTOModueFlag() &&
1235 !TheModule->getModuleFlag(
"UnifiedLTO"))
1236 TheModule->addModuleFlag(llvm::Module::Error,
"UnifiedLTO",
uint32_t(1));
1243 if (PrintPipelinePasses) {
1244 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1245 auto PassName = PIC.getPassNameForClassName(ClassName);
1246 return PassName.empty() ? ClassName : PassName;
1254 PrettyStackTraceString CrashInfo(
"Optimizer");
1255 llvm::TimeTraceScope TimeScope(
"Optimizer");
1261 MPM.run(*TheModule, MAM);
1267void EmitAssemblyHelper::RunCodegenPipeline(
1268 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1269 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1273 legacy::PassManager CodeGenPasses;
1281 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1287 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1288 DwoOS ? &DwoOS->os() :
nullptr))
1299 if (PrintPipelinePasses) {
1304 PrettyStackTraceString CrashInfo(
"Code generation");
1305 llvm::TimeTraceScope TimeScope(
"CodeGenPasses");
1308 timer.init(
"codegen",
"Machine code generation", CI.
getTimerGroup());
1311 CodeGenPasses.run(*TheModule);
1318 std::unique_ptr<raw_pwrite_stream> OS,
1319 BackendConsumer *BC) {
1323 CreateTargetMachine(RequiresCodeGen);
1325 if (RequiresCodeGen && !TM)
1328 TheModule->setDataLayout(TM->createDataLayout());
1331 cl::PrintOptionValues();
1333 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1334 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1335 RunCodegenPipeline(Action, OS, DwoOS);
1345 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1346 std::string SampleProfile, std::string ProfileRemapping,
1351 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1352 ModuleToDefinedGVSummaries;
1353 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1360 FunctionImporter::ImportIDTable ImportIDs;
1361 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1362 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1365 auto AddStream = [&](
size_t Task,
const Twine &ModuleName) {
1366 return std::make_unique<CachedFileStream>(std::move(OS),
1367 CGOpts.ObjectFilenameForDebug);
1370 if (CGOpts.SaveTempsFilePrefix !=
"") {
1371 if (
Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix +
".",
1373 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1374 errs() <<
"Error setting up ThinLTO save-temps: " << EIB.message()
1379 Conf.CPU = TOpts.CPU;
1381 Conf.MAttrs = TOpts.Features;
1382 Conf.RelocModel = CGOpts.RelocationModel;
1383 std::optional<CodeGenOptLevel> OptLevelOrNone =
1384 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1385 assert(OptLevelOrNone &&
"Invalid optimization level!");
1386 Conf.CGOptLevel = *OptLevelOrNone;
1387 Conf.OptLevel = CGOpts.OptimizationLevel;
1389 Conf.SampleProfile = std::move(SampleProfile);
1390 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1391 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1392 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1395 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1396 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1397 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1400 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1403 if (CGOpts.hasProfileCSIRInstr()) {
1404 Conf.RunCSIRInstr =
true;
1406 }
else if (CGOpts.hasProfileCSIRUse()) {
1407 Conf.RunCSIRInstr =
false;
1408 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1411 Conf.ProfileRemapping = std::move(ProfileRemapping);
1412 Conf.DebugPassManager = CGOpts.DebugPassManager;
1413 Conf.VerifyEach = CGOpts.VerifyEach;
1414 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1415 Conf.RemarksFilename = CGOpts.OptRecordFile;
1416 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1417 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1418 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1419 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1422 Conf.PreCodeGenModuleHook = [](
size_t Task,
const llvm::Module &Mod) {
1427 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1428 M->print(*OS,
nullptr, CGOpts.EmitLLVMUseLists);
1433 Conf.PreCodeGenModuleHook = [&](
size_t Task,
const llvm::Module &Mod) {
1434 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1445 finalizeLLVMOptimizationRemarks(M->getContext());
1447 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1448 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1449 nullptr, Conf.CodeGenOnly,
1450 nullptr, CGOpts.CmdArgs)) {
1451 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1452 errs() <<
"Error running ThinLTO backend: " << EIB.message() <<
'\n';
1458 StringRef TDesc, llvm::Module *M,
1461 std::unique_ptr<raw_pwrite_stream> OS,
1463 llvm::TimeTraceScope TimeScope(
"Backend");
1466 std::unique_ptr<llvm::Module> EmptyModule;
1469 auto BypassSandbox = sys::sandbox::scopedDisable();
1473 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1474 if (
Error E = llvm::getModuleSummaryIndexForFile(
1477 .moveInto(CombinedIndex)) {
1478 logAllUnhandledErrors(std::move(E), errs(),
1479 "Error loading index file '" +
1487 if (CombinedIndex) {
1488 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1500 EmptyModule = std::make_unique<llvm::Module>(
"empty", M->getContext());
1501 EmptyModule->setTargetTriple(M->getTargetTriple());
1502 M = EmptyModule.get();
1506 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1507 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1512 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1513 if (DLDesc != TDesc) {
1516 "expected target description '%1'");
1517 Diags.
Report(DiagID) << DLDesc << TDesc;
1525 llvm::MemoryBufferRef Buf) {
1528 llvm::embedBitcodeInModule(
1540 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1541 VFS.getBufferForFile(OffloadObject);
1542 if (ObjectOrErr.getError()) {
1544 "could not open '%0' for embedding");
1545 Diags.
Report(DiagID) << OffloadObject;
1549 llvm::embedBufferInModule(*M, **ObjectOrErr,
".llvm.offloading",
1550 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)
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 std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
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.
std::vector< std::string > PassPlugins
List of dynamic shared object files to be loaded as pass plugins.
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()
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.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
@ 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.