clang 22.0.0git
BackendUtil.cpp
Go to the documentation of this file.
1//===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "BackendConsumer.h"
11#include "LinkInModulesPass.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Analysis/GlobalsModRef.h"
22#include "llvm/Analysis/TargetLibraryInfo.h"
23#include "llvm/Analysis/TargetTransformInfo.h"
24#include "llvm/Bitcode/BitcodeReader.h"
25#include "llvm/Bitcode/BitcodeWriter.h"
26#include "llvm/Bitcode/BitcodeWriterPass.h"
27#include "llvm/CodeGen/TargetSubtargetInfo.h"
28#include "llvm/Config/llvm-config.h"
29#include "llvm/Frontend/Driver/CodeGenOptions.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DebugInfo.h"
32#include "llvm/IR/LegacyPassManager.h"
33#include "llvm/IR/Module.h"
34#include "llvm/IR/ModuleSummaryIndex.h"
35#include "llvm/IR/PassManager.h"
36#include "llvm/IR/Verifier.h"
37#include "llvm/IRPrinter/IRPrintingPasses.h"
38#include "llvm/LTO/LTOBackend.h"
39#include "llvm/MC/TargetRegistry.h"
40#include "llvm/Object/OffloadBinary.h"
41#include "llvm/Passes/PassBuilder.h"
42#include "llvm/Passes/PassPlugin.h"
43#include "llvm/Passes/StandardInstrumentations.h"
44#include "llvm/ProfileData/InstrProfCorrelator.h"
45#include "llvm/Support/BuryPointer.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Compiler.h"
48#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/PrettyStackTrace.h"
50#include "llvm/Support/Program.h"
51#include "llvm/Support/TimeProfiler.h"
52#include "llvm/Support/Timer.h"
53#include "llvm/Support/ToolOutputFile.h"
54#include "llvm/Support/VirtualFileSystem.h"
55#include "llvm/Support/raw_ostream.h"
56#include "llvm/Target/TargetMachine.h"
57#include "llvm/Target/TargetOptions.h"
58#include "llvm/TargetParser/SubtargetFeature.h"
59#include "llvm/TargetParser/Triple.h"
60#include "llvm/Transforms/HipStdPar/HipStdPar.h"
61#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
62#include "llvm/Transforms/IPO/LowerTypeTests.h"
63#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
64#include "llvm/Transforms/InstCombine/InstCombine.h"
65#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
66#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
67#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
68#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
69#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
70#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
71#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
72#include "llvm/Transforms/Instrumentation/KCFI.h"
73#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
74#include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
75#include "llvm/Transforms/Instrumentation/MemProfUse.h"
76#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
77#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
78#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
79#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
80#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
81#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
82#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
83#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
84#include "llvm/Transforms/ObjCARC.h"
85#include "llvm/Transforms/Scalar/EarlyCSE.h"
86#include "llvm/Transforms/Scalar/GVN.h"
87#include "llvm/Transforms/Scalar/JumpThreading.h"
88#include "llvm/Transforms/Utils/Debugify.h"
89#include "llvm/Transforms/Utils/ModuleUtils.h"
90#include <limits>
91#include <memory>
92#include <optional>
93using namespace clang;
94using namespace llvm;
95
96#define HANDLE_EXTENSION(Ext) \
97 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
98#include "llvm/Support/Extension.def"
99
100namespace llvm {
101// Experiment to move sanitizers earlier.
102static cl::opt<bool> ClSanitizeOnOptimizerEarlyEP(
103 "sanitizer-early-opt-ep", cl::Optional,
104 cl::desc("Insert sanitizers on OptimizerEarlyEP."));
105
106// Experiment to mark cold functions as optsize/minsize/optnone.
107// TODO: remove once this is exposed as a proper driver flag.
108static cl::opt<PGOOptions::ColdFuncOpt> ClPGOColdFuncAttr(
109 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
110 cl::desc(
111 "Function attribute to apply to cold functions as determined by PGO"),
112 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default, "default",
113 "Default (no attribute)"),
114 clEnumValN(PGOOptions::ColdFuncOpt::OptSize, "optsize",
115 "Mark cold functions with optsize."),
116 clEnumValN(PGOOptions::ColdFuncOpt::MinSize, "minsize",
117 "Mark cold functions with minsize."),
118 clEnumValN(PGOOptions::ColdFuncOpt::OptNone, "optnone",
119 "Mark cold functions with optnone.")));
120
121LLVM_ABI extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
123} // namespace llvm
124namespace clang {
125extern llvm::cl::opt<bool> ClSanitizeGuardChecks;
126}
127
128// Path and name of file used for profile generation
129static std::string getProfileGenName(const CodeGenOptions &CodeGenOpts) {
130 std::string FileName = CodeGenOpts.InstrProfileOutput.empty()
131 ? llvm::driver::getDefaultProfileGenName()
132 : CodeGenOpts.InstrProfileOutput;
133 if (CodeGenOpts.ContinuousProfileSync)
134 FileName = "%c" + FileName;
135 return FileName;
136}
137
138namespace {
139
140class EmitAssemblyHelper {
142 DiagnosticsEngine &Diags;
143 const CodeGenOptions &CodeGenOpts;
144 const clang::TargetOptions &TargetOpts;
145 const LangOptions &LangOpts;
146 llvm::Module *TheModule;
148
149 std::unique_ptr<raw_pwrite_stream> OS;
150
151 Triple TargetTriple;
152
153 TargetIRAnalysis getTargetIRAnalysis() const {
154 if (TM)
155 return TM->getTargetIRAnalysis();
156
157 return TargetIRAnalysis();
158 }
159
160 /// Generates the TargetMachine.
161 /// Leaves TM unchanged if it is unable to create the target machine.
162 /// Some of our clang tests specify triples which are not built
163 /// into clang. This is okay because these tests check the generated
164 /// IR, and they require DataLayout which depends on the triple.
165 /// In this case, we allow this method to fail and not report an error.
166 /// When MustCreateTM is used, we print an error if we are unable to load
167 /// the requested target.
168 void CreateTargetMachine(bool MustCreateTM);
169
170 /// Add passes necessary to emit assembly or LLVM IR.
171 ///
172 /// \return True on success.
173 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
174 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
175
176 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
177 std::error_code EC;
178 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
179 llvm::sys::fs::OF_None);
180 if (EC) {
181 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
182 F.reset();
183 }
184 return F;
185 }
186
187 void RunOptimizationPipeline(
188 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
189 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
190 void RunCodegenPipeline(BackendAction Action,
191 std::unique_ptr<raw_pwrite_stream> &OS,
192 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
193
194 /// Check whether we should emit a module summary for regular LTO.
195 /// The module summary should be emitted by default for regular LTO
196 /// except for ld64 targets.
197 ///
198 /// \return True if the module summary should be emitted.
199 bool shouldEmitRegularLTOSummary() const {
200 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
201 TargetTriple.getVendor() != llvm::Triple::Apple;
202 }
203
204 /// Check whether we should emit a flag for UnifiedLTO.
205 /// The UnifiedLTO module flag should be set when UnifiedLTO is enabled for
206 /// ThinLTO or Full LTO with module summaries.
207 bool shouldEmitUnifiedLTOModueFlag() const {
208 return CodeGenOpts.UnifiedLTO &&
209 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
210 }
211
212public:
213 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
214 llvm::Module *M,
216 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
217 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
218 TheModule(M), VFS(std::move(VFS)),
219 TargetTriple(TheModule->getTargetTriple()) {}
220
221 ~EmitAssemblyHelper() {
222 if (CodeGenOpts.DisableFree)
223 BuryPointer(std::move(TM));
224 }
225
226 std::unique_ptr<TargetMachine> TM;
227
228 // Emit output using the new pass manager for the optimization pipeline.
229 void emitAssembly(BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
230 BackendConsumer *BC);
231};
232} // namespace
233
234static SanitizerCoverageOptions
236 SanitizerCoverageOptions Opts;
237 Opts.CoverageType =
238 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
239 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
240 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
241 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
242 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
243 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
244 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
245 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
246 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
247 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
248 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
249 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
250 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
251 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
252 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
253 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
254 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
255 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
256 return Opts;
257}
258
259static SanitizerBinaryMetadataOptions
261 SanitizerBinaryMetadataOptions Opts;
262 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
263 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
264 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
265 return Opts;
266}
267
268// Check if ASan should use GC-friendly instrumentation for globals.
269// First of all, there is no point if -fdata-sections is off (expect for MachO,
270// where this is not a factor). Also, on ELF this feature requires an assembler
271// extension that only works with -integrated-as at the moment.
272static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
273 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
274 return false;
275 switch (T.getObjectFormat()) {
276 case Triple::MachO:
277 case Triple::COFF:
278 return true;
279 case Triple::ELF:
280 return !CGOpts.DisableIntegratedAS;
281 case Triple::GOFF:
282 llvm::report_fatal_error("ASan not implemented for GOFF");
283 case Triple::XCOFF:
284 llvm::report_fatal_error("ASan not implemented for XCOFF.");
285 case Triple::Wasm:
286 case Triple::DXContainer:
287 case Triple::SPIRV:
288 case Triple::UnknownObjectFormat:
289 break;
290 }
291 return false;
292}
293
294static std::optional<llvm::CodeModel::Model>
295getCodeModel(const CodeGenOptions &CodeGenOpts) {
296 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
297 .Case("tiny", llvm::CodeModel::Tiny)
298 .Case("small", llvm::CodeModel::Small)
299 .Case("kernel", llvm::CodeModel::Kernel)
300 .Case("medium", llvm::CodeModel::Medium)
301 .Case("large", llvm::CodeModel::Large)
302 .Cases("default", "", ~1u)
303 .Default(~0u);
304 assert(CodeModel != ~0u && "invalid code model!");
305 if (CodeModel == ~1u)
306 return std::nullopt;
307 return static_cast<llvm::CodeModel::Model>(CodeModel);
308}
309
310static CodeGenFileType getCodeGenFileType(BackendAction Action) {
311 if (Action == Backend_EmitObj)
312 return CodeGenFileType::ObjectFile;
313 else if (Action == Backend_EmitMCNull)
314 return CodeGenFileType::Null;
315 else {
316 assert(Action == Backend_EmitAssembly && "Invalid action!");
317 return CodeGenFileType::AssemblyFile;
318 }
319}
320
322 return Action != Backend_EmitNothing && Action != Backend_EmitBC &&
323 Action != Backend_EmitLL;
324}
325
327 StringRef MainFilename) {
328 if (Args.empty())
329 return std::string{};
330
331 std::string FlatCmdLine;
332 raw_string_ostream OS(FlatCmdLine);
333 bool PrintedOneArg = false;
334 if (!StringRef(Args[0]).contains("-cc1")) {
335 llvm::sys::printArg(OS, "-cc1", /*Quote=*/true);
336 PrintedOneArg = true;
337 }
338 for (unsigned i = 0; i < Args.size(); i++) {
339 StringRef Arg = Args[i];
340 if (Arg.empty())
341 continue;
342 if (Arg == "-main-file-name" || Arg == "-o") {
343 i++; // Skip this argument and next one.
344 continue;
345 }
346 if (Arg.starts_with("-object-file-name") || Arg == MainFilename)
347 continue;
348 // Skip fmessage-length for reproducibility.
349 if (Arg.starts_with("-fmessage-length"))
350 continue;
351 if (PrintedOneArg)
352 OS << " ";
353 llvm::sys::printArg(OS, Arg, /*Quote=*/true);
354 PrintedOneArg = true;
355 }
356 return FlatCmdLine;
357}
358
360 DiagnosticsEngine &Diags,
361 llvm::TargetOptions &Options) {
362 const auto &CodeGenOpts = CI.getCodeGenOpts();
363 const auto &TargetOpts = CI.getTargetOpts();
364 const auto &LangOpts = CI.getLangOpts();
365 const auto &HSOpts = CI.getHeaderSearchOpts();
366 switch (LangOpts.getThreadModel()) {
367 case LangOptions::ThreadModelKind::POSIX:
368 Options.ThreadModel = llvm::ThreadModel::POSIX;
369 break;
370 case LangOptions::ThreadModelKind::Single:
371 Options.ThreadModel = llvm::ThreadModel::Single;
372 break;
373 }
374
375 // Set float ABI type.
376 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
377 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
378 "Invalid Floating Point ABI!");
379 Options.FloatABIType =
380 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
381 .Case("soft", llvm::FloatABI::Soft)
382 .Case("softfp", llvm::FloatABI::Soft)
383 .Case("hard", llvm::FloatABI::Hard)
384 .Default(llvm::FloatABI::Default);
385
386 // Set FP fusion mode.
387 switch (LangOpts.getDefaultFPContractMode()) {
388 case LangOptions::FPM_Off:
389 // Preserve any contraction performed by the front-end. (Strict performs
390 // splitting of the muladd intrinsic in the backend.)
391 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
392 break;
393 case LangOptions::FPM_On:
394 case LangOptions::FPM_FastHonorPragmas:
395 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
396 break;
397 case LangOptions::FPM_Fast:
398 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
399 break;
400 }
401
402 Options.BinutilsVersion =
403 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
404 Options.UseInitArray = CodeGenOpts.UseInitArray;
405 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
406
407 // Set EABI version.
408 Options.EABIVersion = TargetOpts.EABIVersion;
409
410 if (CodeGenOpts.hasSjLjExceptions())
411 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
412 if (CodeGenOpts.hasSEHExceptions())
413 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
414 if (CodeGenOpts.hasDWARFExceptions())
415 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
416 if (CodeGenOpts.hasWasmExceptions())
417 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
418
419 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
420 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
421 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
422 Options.UnsafeFPMath = LangOpts.AllowFPReassoc && LangOpts.AllowRecip &&
423 LangOpts.NoSignedZero && LangOpts.ApproxFunc &&
424 (LangOpts.getDefaultFPContractMode() ==
425 LangOptions::FPModeKind::FPM_Fast ||
426 LangOpts.getDefaultFPContractMode() ==
427 LangOptions::FPModeKind::FPM_FastHonorPragmas);
428
429 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
430 Options.BBSections =
431 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
432 .Case("all", llvm::BasicBlockSection::All)
433 .StartsWith("list=", llvm::BasicBlockSection::List)
434 .Case("none", llvm::BasicBlockSection::None)
435 .Default(llvm::BasicBlockSection::None);
436
437 if (Options.BBSections == llvm::BasicBlockSection::List) {
438 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
439 MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
440 if (!MBOrErr) {
441 Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
442 << MBOrErr.getError().message();
443 return false;
444 }
445 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
446 }
447
448 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
449 Options.FunctionSections = CodeGenOpts.FunctionSections;
450 Options.DataSections = CodeGenOpts.DataSections;
451 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
452 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
453 Options.UniqueBasicBlockSectionNames =
454 CodeGenOpts.UniqueBasicBlockSectionNames;
455 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
456 Options.TLSSize = CodeGenOpts.TLSSize;
457 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
458 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
459 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
460 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
461 Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
462 Options.EmitAddrsig = CodeGenOpts.Addrsig;
463 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
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;
469 Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
470 Options.Hotpatch = CodeGenOpts.HotPatch;
471 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
472 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
473
474 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
475 case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
476 Options.SwiftAsyncFramePointer =
477 SwiftAsyncFramePointerMode::DeploymentBased;
478 break;
479
480 case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
481 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
482 break;
483
484 case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
485 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
486 break;
487 }
488
489 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
490 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
491 Options.MCOptions.EmitCompactUnwindNonCanonical =
492 CodeGenOpts.EmitCompactUnwindNonCanonical;
493 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
494 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
495 Options.MCOptions.MCUseDwarfDirectory =
496 CodeGenOpts.NoDwarfDirectoryAsm
497 ? llvm::MCTargetOptions::DisableDwarfDirectory
498 : llvm::MCTargetOptions::EnableDwarfDirectory;
499 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
500 Options.MCOptions.MCIncrementalLinkerCompatible =
501 CodeGenOpts.IncrementalLinkerCompatible;
502 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
503 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
504 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
505 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
506 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
507 Options.MCOptions.Crel = CodeGenOpts.Crel;
508 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
509 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
510 Options.MCOptions.CompressDebugSections =
511 CodeGenOpts.getCompressDebugSections();
512 if (CodeGenOpts.OutputAsmVariant != 3) // 3 (default): not specified
513 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
514 Options.MCOptions.ABIName = TargetOpts.ABI;
515 for (const auto &Entry : HSOpts.UserEntries)
516 if (!Entry.IsFramework &&
517 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
518 Entry.Group == frontend::IncludeDirGroup::Angled ||
519 Entry.Group == frontend::IncludeDirGroup::System))
520 Options.MCOptions.IASSearchPaths.push_back(
521 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
522 Options.MCOptions.Argv0 = CodeGenOpts.Argv0 ? CodeGenOpts.Argv0 : "";
523 Options.MCOptions.CommandlineArgs = flattenClangCommandLine(
524 CodeGenOpts.CommandLineArgs, CodeGenOpts.MainFileName);
525 Options.MCOptions.AsSecureLogFile = CodeGenOpts.AsSecureLogFile;
526 Options.MCOptions.PPCUseFullRegisterNames =
527 CodeGenOpts.PPCUseFullRegisterNames;
528 Options.MisExpect = CodeGenOpts.MisExpect;
529
530 return true;
531}
532
533static std::optional<GCOVOptions>
534getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts) {
535 if (CodeGenOpts.CoverageNotesFile.empty() &&
536 CodeGenOpts.CoverageDataFile.empty())
537 return std::nullopt;
538 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
539 // LLVM's -default-gcov-version flag is set to something invalid.
540 GCOVOptions Options;
541 Options.EmitNotes = !CodeGenOpts.CoverageNotesFile.empty();
542 Options.EmitData = !CodeGenOpts.CoverageDataFile.empty();
543 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
544 Options.NoRedZone = CodeGenOpts.DisableRedZone;
545 Options.Filter = CodeGenOpts.ProfileFilterFiles;
546 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
547 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
548 return Options;
549}
550
551static std::optional<InstrProfOptions>
553 const LangOptions &LangOpts) {
554 if (!CodeGenOpts.hasProfileClangInstr())
555 return std::nullopt;
556 InstrProfOptions Options;
557 Options.NoRedZone = CodeGenOpts.DisableRedZone;
558 Options.InstrProfileOutput = CodeGenOpts.ContinuousProfileSync
559 ? ("%c" + CodeGenOpts.InstrProfileOutput)
560 : CodeGenOpts.InstrProfileOutput;
561 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
562 return Options;
563}
564
565static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
567 BackendArgs.push_back("clang"); // Fake program name.
568 if (!CodeGenOpts.DebugPass.empty()) {
569 BackendArgs.push_back("-debug-pass");
570 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
571 }
572 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
573 BackendArgs.push_back("-limit-float-precision");
574 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
575 }
576 // Check for the default "clang" invocation that won't set any cl::opt values.
577 // Skip trying to parse the command line invocation to avoid the issues
578 // described below.
579 if (BackendArgs.size() == 1)
580 return;
581 BackendArgs.push_back(nullptr);
582 // FIXME: The command line parser below is not thread-safe and shares a global
583 // state, so this call might crash or overwrite the options of another Clang
584 // instance in the same process.
585 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
586 BackendArgs.data());
587}
588
589void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
590 // Create the TargetMachine for generating code.
591 std::string Error;
592 const llvm::Triple &Triple = TheModule->getTargetTriple();
593 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
594 if (!TheTarget) {
595 if (MustCreateTM)
596 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
597 return;
598 }
599
600 std::optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
601 std::string FeaturesStr =
602 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
603 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
604 std::optional<CodeGenOptLevel> OptLevelOrNone =
605 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
606 assert(OptLevelOrNone && "Invalid optimization level!");
607 CodeGenOptLevel OptLevel = *OptLevelOrNone;
608
609 llvm::TargetOptions Options;
610 if (!initTargetOptions(CI, Diags, Options))
611 return;
612 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
613 Options, RM, CM, OptLevel));
614 if (TM)
615 TM->setLargeDataThreshold(CodeGenOpts.LargeDataThreshold);
616}
617
618bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
619 BackendAction Action,
620 raw_pwrite_stream &OS,
621 raw_pwrite_stream *DwoOS) {
622 // Add LibraryInfo.
623 std::unique_ptr<TargetLibraryInfoImpl> TLII(
624 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
625 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
626
627 // Normal mode, emit a .s or .o file by running the code generator. Note,
628 // this also adds codegenerator level optimization passes.
629 CodeGenFileType CGFT = getCodeGenFileType(Action);
630
631 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
632 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
633 Diags.Report(diag::err_fe_unable_to_interface_with_target);
634 return false;
635 }
636
637 return true;
638}
639
640static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
641 switch (Opts.OptimizationLevel) {
642 default:
643 llvm_unreachable("Invalid optimization level!");
644
645 case 0:
646 return OptimizationLevel::O0;
647
648 case 1:
649 return OptimizationLevel::O1;
650
651 case 2:
652 switch (Opts.OptimizeSize) {
653 default:
654 llvm_unreachable("Invalid optimization level for size!");
655
656 case 0:
657 return OptimizationLevel::O2;
658
659 case 1:
660 return OptimizationLevel::Os;
661
662 case 2:
663 return OptimizationLevel::Oz;
664 }
665
666 case 3:
667 return OptimizationLevel::O3;
668 }
669}
670
671static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts,
672 PassBuilder &PB) {
673 // If the back-end supports KCFI operand bundle lowering, skip KCFIPass.
674 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
675 TargetTriple.isAArch64(64) || TargetTriple.isRISCV())
676 return;
677
678 // Ensure we lower KCFI operand bundles with -O0.
679 PB.registerOptimizerLastEPCallback(
680 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
681 if (Level == OptimizationLevel::O0 &&
682 LangOpts.Sanitize.has(SanitizerKind::KCFI))
683 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
684 });
685
686 // When optimizations are requested, run KCIFPass after InstCombine to
687 // avoid unnecessary checks.
688 PB.registerPeepholeEPCallback(
689 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
690 if (Level != OptimizationLevel::O0 &&
691 LangOpts.Sanitize.has(SanitizerKind::KCFI))
692 FPM.addPass(KCFIPass());
693 });
694}
695
696static void addSanitizers(const Triple &TargetTriple,
697 const CodeGenOptions &CodeGenOpts,
698 const LangOptions &LangOpts, PassBuilder &PB) {
699 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
700 ThinOrFullLTOPhase) {
701 if (CodeGenOpts.hasSanitizeCoverage()) {
702 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
703 MPM.addPass(SanitizerCoveragePass(
704 SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
706 }
707
708 if (CodeGenOpts.hasSanitizeBinaryMetadata()) {
709 MPM.addPass(SanitizerBinaryMetadataPass(
712 }
713
714 auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
715 if (LangOpts.Sanitize.has(Mask)) {
716 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
717 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
718
719 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
720 CodeGenOpts.SanitizeMemoryParamRetval);
721 MPM.addPass(MemorySanitizerPass(options));
722 if (Level != OptimizationLevel::O0) {
723 // MemorySanitizer inserts complex instrumentation that mostly follows
724 // the logic of the original code, but operates on "shadow" values. It
725 // can benefit from re-running some general purpose optimization
726 // passes.
727 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
728 FunctionPassManager FPM;
729 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
730 FPM.addPass(InstCombinePass());
731 FPM.addPass(JumpThreadingPass());
732 FPM.addPass(GVNPass());
733 FPM.addPass(InstCombinePass());
734 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
735 }
736 }
737 };
738 MSanPass(SanitizerKind::Memory, false);
739 MSanPass(SanitizerKind::KernelMemory, true);
740
741 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
742 MPM.addPass(ModuleThreadSanitizerPass());
743 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
744 }
745
746 if (LangOpts.Sanitize.has(SanitizerKind::Type))
747 MPM.addPass(TypeSanitizerPass());
748
749 if (LangOpts.Sanitize.has(SanitizerKind::NumericalStability))
750 MPM.addPass(NumericalStabilitySanitizerPass());
751
752 if (LangOpts.Sanitize.has(SanitizerKind::Realtime))
753 MPM.addPass(RealtimeSanitizerPass());
754
755 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
756 if (LangOpts.Sanitize.has(Mask)) {
757 bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
758 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
759 llvm::AsanDtorKind DestructorKind =
760 CodeGenOpts.getSanitizeAddressDtor();
761 AddressSanitizerOptions Opts;
762 Opts.CompileKernel = CompileKernel;
763 Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
764 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
765 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
766 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
767 DestructorKind));
768 }
769 };
770 ASanPass(SanitizerKind::Address, false);
771 ASanPass(SanitizerKind::KernelAddress, true);
772
773 auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
774 if (LangOpts.Sanitize.has(Mask)) {
775 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
776 MPM.addPass(HWAddressSanitizerPass(
777 {CompileKernel, Recover,
778 /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
779 }
780 };
781 HWASanPass(SanitizerKind::HWAddress, false);
782 HWASanPass(SanitizerKind::KernelHWAddress, true);
783
784 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
785 MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
786 }
787 };
789 PB.registerOptimizerEarlyEPCallback(
790 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
791 ThinOrFullLTOPhase Phase) {
792 ModulePassManager NewMPM;
793 SanitizersCallback(NewMPM, Level, Phase);
794 if (!NewMPM.isEmpty()) {
795 // Sanitizers can abandon<GlobalsAA>.
796 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
797 MPM.addPass(std::move(NewMPM));
798 }
799 });
800 } else {
801 // LastEP does not need GlobalsAA.
802 PB.registerOptimizerLastEPCallback(SanitizersCallback);
803 }
804
805 // SanitizeSkipHotCutoffs: doubles with range [0, 1]
806 // Opts.cutoffs: unsigned ints with range [0, 1000000]
807 auto ScaledCutoffs = CodeGenOpts.SanitizeSkipHotCutoffs.getAllScaled(1000000);
808 uint64_t AllowRuntimeCheckSkipHotCutoff =
809 CodeGenOpts.AllowRuntimeCheckSkipHotCutoff.value_or(0.0) * 1000000;
810 // TODO: remove IsRequested()
811 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
812 CodeGenOpts.AllowRuntimeCheckSkipHotCutoff.has_value()) {
813 // We want to call it after inline, which is about OptimizerEarlyEPCallback.
814 PB.registerOptimizerEarlyEPCallback(
815 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
816 ModulePassManager &MPM, OptimizationLevel Level,
817 ThinOrFullLTOPhase Phase) {
818 LowerAllowCheckPass::Options Opts;
819 // TODO: after removing IsRequested(), make this unconditional
820 if (ScaledCutoffs.has_value())
821 Opts.cutoffs = ScaledCutoffs.value();
822 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
823 MPM.addPass(
824 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
825 });
826 }
827}
828
829void EmitAssemblyHelper::RunOptimizationPipeline(
830 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
831 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
832 std::optional<PGOOptions> PGOOpt;
833
834 if (CodeGenOpts.hasProfileIRInstr())
835 // -fprofile-generate.
836 PGOOpt = PGOOptions(getProfileGenName(CodeGenOpts), "", "",
837 CodeGenOpts.MemoryProfileUsePath, nullptr,
838 PGOOptions::IRInstr, PGOOptions::NoCSAction,
839 ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling,
840 /*PseudoProbeForProfiling=*/false,
841 CodeGenOpts.AtomicProfileUpdate);
842 else if (CodeGenOpts.hasProfileIRUse()) {
843 // -fprofile-use.
844 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
845 : PGOOptions::NoCSAction;
846 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
847 CodeGenOpts.ProfileRemappingFile,
848 CodeGenOpts.MemoryProfileUsePath, VFS,
849 PGOOptions::IRUse, CSAction, ClPGOColdFuncAttr,
850 CodeGenOpts.DebugInfoForProfiling);
851 } else if (!CodeGenOpts.SampleProfileFile.empty())
852 // -fprofile-sample-use
853 PGOOpt = PGOOptions(
854 CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
855 CodeGenOpts.MemoryProfileUsePath, VFS, PGOOptions::SampleUse,
856 PGOOptions::NoCSAction, ClPGOColdFuncAttr,
857 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
858 else if (!CodeGenOpts.MemoryProfileUsePath.empty())
859 // -fmemory-profile-use (without any of the above options)
860 PGOOpt = PGOOptions("", "", "", CodeGenOpts.MemoryProfileUsePath, VFS,
861 PGOOptions::NoAction, PGOOptions::NoCSAction,
862 ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling);
863 else if (CodeGenOpts.PseudoProbeForProfiling)
864 // -fpseudo-probe-for-profiling
865 PGOOpt =
866 PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
867 PGOOptions::NoAction, PGOOptions::NoCSAction,
868 ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling, true);
869 else if (CodeGenOpts.DebugInfoForProfiling)
870 // -fdebug-info-for-profiling
871 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
872 PGOOptions::NoAction, PGOOptions::NoCSAction,
873 ClPGOColdFuncAttr, true);
874
875 // Check to see if we want to generate a CS profile.
876 if (CodeGenOpts.hasProfileCSIRInstr()) {
877 assert(!CodeGenOpts.hasProfileCSIRUse() &&
878 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
879 "the same time");
880 if (PGOOpt) {
881 assert(PGOOpt->Action != PGOOptions::IRInstr &&
882 PGOOpt->Action != PGOOptions::SampleUse &&
883 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
884 " pass");
885 PGOOpt->CSProfileGenFile = getProfileGenName(CodeGenOpts);
886 PGOOpt->CSAction = PGOOptions::CSIRInstr;
887 } else
888 PGOOpt = PGOOptions("", getProfileGenName(CodeGenOpts), "",
889 /*MemoryProfile=*/"", nullptr, PGOOptions::NoAction,
890 PGOOptions::CSIRInstr, ClPGOColdFuncAttr,
891 CodeGenOpts.DebugInfoForProfiling);
892 }
893 if (TM)
894 TM->setPGOOption(PGOOpt);
895
896 PipelineTuningOptions PTO;
897 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
898 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
899 // For historical reasons, loop interleaving is set to mirror setting for loop
900 // unrolling.
901 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
902 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
903 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
904 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
905 // Only enable CGProfilePass when using integrated assembler, since
906 // non-integrated assemblers don't recognize .cgprofile section.
907 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
908 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
909
910 LoopAnalysisManager LAM;
911 FunctionAnalysisManager FAM;
912 CGSCCAnalysisManager CGAM;
913 ModuleAnalysisManager MAM;
914
915 bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
916 PassInstrumentationCallbacks PIC;
917 PrintPassOptions PrintPassOpts;
918 PrintPassOpts.Indent = DebugPassStructure;
919 PrintPassOpts.SkipAnalyses = DebugPassStructure;
920 StandardInstrumentations SI(
921 TheModule->getContext(),
922 (CodeGenOpts.DebugPassManager || DebugPassStructure),
923 CodeGenOpts.VerifyEach, PrintPassOpts);
924 SI.registerCallbacks(PIC, &MAM);
925 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
926
927 // Handle the assignment tracking feature options.
928 switch (CodeGenOpts.getAssignmentTrackingMode()) {
929 case CodeGenOptions::AssignmentTrackingOpts::Forced:
930 PB.registerPipelineStartEPCallback(
931 [&](ModulePassManager &MPM, OptimizationLevel Level) {
932 MPM.addPass(AssignmentTrackingPass());
933 });
934 break;
935 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
936 // Disable assignment tracking in LTO builds for now as the performance
937 // cost is too high. Disable for LLDB tuning due to llvm.org/PR43126.
938 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
939 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
940 PB.registerPipelineStartEPCallback(
941 [&](ModulePassManager &MPM, OptimizationLevel Level) {
942 // Only use assignment tracking if optimisations are enabled.
943 if (Level != OptimizationLevel::O0)
944 MPM.addPass(AssignmentTrackingPass());
945 });
946 }
947 break;
948 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
949 break;
950 }
951
952 // Enable verify-debuginfo-preserve-each for new PM.
953 DebugifyEachInstrumentation Debugify;
954 DebugInfoPerPass DebugInfoBeforePass;
955 if (CodeGenOpts.EnableDIPreservationVerify) {
956 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
957 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
958
959 if (!CodeGenOpts.DIBugsReportFilePath.empty())
960 Debugify.setOrigDIVerifyBugsReportFilePath(
961 CodeGenOpts.DIBugsReportFilePath);
962 Debugify.registerCallbacks(PIC, MAM);
963
964#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
965 // If we're using debug location coverage tracking, mark all the
966 // instructions coming out of the frontend without a DebugLoc as being
967 // compiler-generated, to prevent both those instructions and new
968 // instructions that inherit their location from being treated as
969 // incorrectly empty locations.
970 for (Function &F : *TheModule) {
971 if (!F.getSubprogram())
972 continue;
973 for (BasicBlock &BB : F)
974 for (Instruction &I : BB)
975 if (!I.getDebugLoc())
976 I.setDebugLoc(DebugLoc::getCompilerGenerated());
977 }
978#endif
979 }
980 // Attempt to load pass plugins and register their callbacks with PB.
981 for (auto &PluginFN : CodeGenOpts.PassPlugins) {
982 auto PassPlugin = PassPlugin::Load(PluginFN);
983 if (PassPlugin) {
984 PassPlugin->registerPassBuilderCallbacks(PB);
985 } else {
986 Diags.Report(diag::err_fe_unable_to_load_plugin)
987 << PluginFN << toString(PassPlugin.takeError());
988 }
989 }
990 for (const auto &PassCallback : CodeGenOpts.PassBuilderCallbacks)
991 PassCallback(PB);
992#define HANDLE_EXTENSION(Ext) \
993 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
994#include "llvm/Support/Extension.def"
995
996 // Register the target library analysis directly and give it a customized
997 // preset TLI.
998 std::unique_ptr<TargetLibraryInfoImpl> TLII(
999 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1000 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1001
1002 // Register all the basic analyses with the managers.
1003 PB.registerModuleAnalyses(MAM);
1004 PB.registerCGSCCAnalyses(CGAM);
1005 PB.registerFunctionAnalyses(FAM);
1006 PB.registerLoopAnalyses(LAM);
1007 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1008
1009 ModulePassManager MPM;
1010 // Add a verifier pass, before any other passes, to catch CodeGen issues.
1011 if (CodeGenOpts.VerifyModule)
1012 MPM.addPass(VerifierPass());
1013
1014 if (!CodeGenOpts.DisableLLVMPasses) {
1015 // Map our optimization levels into one of the distinct levels used to
1016 // configure the pipeline.
1017 OptimizationLevel Level = mapToLevel(CodeGenOpts);
1018
1019 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1020 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1021
1022 if (LangOpts.ObjCAutoRefCount) {
1023 PB.registerPipelineStartEPCallback(
1024 [](ModulePassManager &MPM, OptimizationLevel Level) {
1025 if (Level != OptimizationLevel::O0)
1026 MPM.addPass(
1027 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1028 });
1029 PB.registerScalarOptimizerLateEPCallback(
1030 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1031 if (Level != OptimizationLevel::O0)
1032 FPM.addPass(ObjCARCOptPass());
1033 });
1034 }
1035
1036 // If we reached here with a non-empty index file name, then the index
1037 // file was empty and we are not performing ThinLTO backend compilation
1038 // (used in testing in a distributed build environment).
1039 bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
1040 // If so drop any the type test assume sequences inserted for whole program
1041 // vtables so that codegen doesn't complain.
1042 if (IsThinLTOPostLink)
1043 PB.registerPipelineStartEPCallback(
1044 [](ModulePassManager &MPM, OptimizationLevel Level) {
1045 MPM.addPass(LowerTypeTestsPass(
1046 /*ExportSummary=*/nullptr,
1047 /*ImportSummary=*/nullptr,
1048 /*DropTypeTests=*/lowertypetests::DropTestKind::Assume));
1049 });
1050
1051 // Register callbacks to schedule sanitizer passes at the appropriate part
1052 // of the pipeline.
1053 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1054 PB.registerScalarOptimizerLateEPCallback([this](FunctionPassManager &FPM,
1055 OptimizationLevel Level) {
1056 BoundsCheckingPass::Options Options;
1057 if (CodeGenOpts.SanitizeSkipHotCutoffs[SanitizerKind::SO_LocalBounds] ||
1059 static_assert(SanitizerKind::SO_LocalBounds <=
1060 std::numeric_limits<
1061 decltype(Options.GuardKind)::value_type>::max(),
1062 "Update type of llvm.allow.ubsan.check to represent "
1063 "SanitizerKind::SO_LocalBounds.");
1064 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1065 }
1066 Options.Merge =
1067 CodeGenOpts.SanitizeMergeHandlers.has(SanitizerKind::LocalBounds);
1068 if (!CodeGenOpts.SanitizeTrap.has(SanitizerKind::LocalBounds)) {
1069 Options.Rt = {
1070 /*MinRuntime=*/static_cast<bool>(
1071 CodeGenOpts.SanitizeMinimalRuntime),
1072 /*MayReturn=*/
1073 CodeGenOpts.SanitizeRecover.has(SanitizerKind::LocalBounds),
1074 };
1075 }
1076 FPM.addPass(BoundsCheckingPass(Options));
1077 });
1078
1079 // Don't add sanitizers if we are here from ThinLTO PostLink. That already
1080 // done on PreLink stage.
1081 if (!IsThinLTOPostLink) {
1082 addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
1083 addKCFIPass(TargetTriple, LangOpts, PB);
1084 }
1085
1086 if (std::optional<GCOVOptions> Options =
1087 getGCOVOptions(CodeGenOpts, LangOpts))
1088 PB.registerPipelineStartEPCallback(
1089 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1090 MPM.addPass(GCOVProfilerPass(*Options));
1091 });
1092 if (std::optional<InstrProfOptions> Options =
1093 getInstrProfOptions(CodeGenOpts, LangOpts))
1094 PB.registerPipelineStartEPCallback(
1095 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1096 MPM.addPass(InstrProfilingLoweringPass(*Options, false));
1097 });
1098
1099 // TODO: Consider passing the MemoryProfileOutput to the pass builder via
1100 // the PGOOptions, and set this up there.
1101 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1102 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1103 OptimizationLevel Level,
1104 ThinOrFullLTOPhase) {
1105 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1106 MPM.addPass(ModuleMemProfilerPass());
1107 });
1108 }
1109
1110 if (CodeGenOpts.FatLTO) {
1111 MPM.addPass(PB.buildFatLTODefaultPipeline(
1112 Level, PrepareForThinLTO,
1113 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1114 } else if (PrepareForThinLTO) {
1115 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1116 } else if (PrepareForLTO) {
1117 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1118 } else {
1119 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1120 }
1121 }
1122
1123 // Link against bitcodes supplied via the -mlink-builtin-bitcode option
1124 if (CodeGenOpts.LinkBitcodePostopt)
1125 MPM.addPass(LinkInModulesPass(BC));
1126
1127 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1128 LangOpts.HIPStdParInterposeAlloc)
1129 MPM.addPass(HipStdParAllocationInterpositionPass());
1130
1131 // Add a verifier pass if requested. We don't have to do this if the action
1132 // requires code generation because there will already be a verifier pass in
1133 // the code-generation pipeline.
1134 // Since we already added a verifier pass above, this
1135 // might even not run the analysis, if previous passes caused no changes.
1136 if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
1137 MPM.addPass(VerifierPass());
1138
1139 if (Action == Backend_EmitBC || Action == Backend_EmitLL ||
1140 CodeGenOpts.FatLTO) {
1141 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1142 if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1143 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1144 CodeGenOpts.EnableSplitLTOUnit);
1145 if (Action == Backend_EmitBC) {
1146 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1147 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1148 if (!ThinLinkOS)
1149 return;
1150 }
1151 MPM.addPass(ThinLTOBitcodeWriterPass(
1152 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
1153 } else if (Action == Backend_EmitLL) {
1154 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1155 /*EmitLTOSummary=*/true));
1156 }
1157 } else {
1158 // Emit a module summary by default for Regular LTO except for ld64
1159 // targets
1160 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1161 if (EmitLTOSummary) {
1162 if (!TheModule->getModuleFlag("ThinLTO") && !CodeGenOpts.UnifiedLTO)
1163 TheModule->addModuleFlag(llvm::Module::Error, "ThinLTO", uint32_t(0));
1164 if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1165 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1166 uint32_t(1));
1167 }
1168 if (Action == Backend_EmitBC) {
1169 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1170 EmitLTOSummary));
1171 } else if (Action == Backend_EmitLL) {
1172 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1173 EmitLTOSummary));
1174 }
1175 }
1176
1177 if (shouldEmitUnifiedLTOModueFlag())
1178 TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", uint32_t(1));
1179 }
1180
1181 // FIXME: This should eventually be replaced by a first-class driver option.
1182 // This should be done for both clang and flang simultaneously.
1183 // Print a textual, '-passes=' compatible, representation of pipeline if
1184 // requested.
1185 if (PrintPipelinePasses) {
1186 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1187 auto PassName = PIC.getPassNameForClassName(ClassName);
1188 return PassName.empty() ? ClassName : PassName;
1189 });
1190 outs() << "\n";
1191 return;
1192 }
1193
1194 // Now that we have all of the passes ready, run them.
1195 {
1196 PrettyStackTraceString CrashInfo("Optimizer");
1197 llvm::TimeTraceScope TimeScope("Optimizer");
1198 Timer timer;
1199 if (CI.getCodeGenOpts().TimePasses) {
1200 timer.init("optimizer", "Optimizer", CI.getTimerGroup());
1201 CI.getFrontendTimer().yieldTo(timer);
1202 }
1203 MPM.run(*TheModule, MAM);
1204 if (CI.getCodeGenOpts().TimePasses)
1205 timer.yieldTo(CI.getFrontendTimer());
1206 }
1207}
1208
1209void EmitAssemblyHelper::RunCodegenPipeline(
1210 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1211 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1212 // We still use the legacy PM to run the codegen pipeline since the new PM
1213 // does not work with the codegen pipeline.
1214 // FIXME: make the new PM work with the codegen pipeline.
1215 legacy::PassManager CodeGenPasses;
1216
1217 // Append any output we need to the pass manager.
1218 switch (Action) {
1220 case Backend_EmitMCNull:
1221 case Backend_EmitObj:
1222 CodeGenPasses.add(
1223 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1224 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1225 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1226 if (!DwoOS)
1227 return;
1228 }
1229 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1230 DwoOS ? &DwoOS->os() : nullptr))
1231 // FIXME: Should we handle this error differently?
1232 return;
1233 break;
1234 default:
1235 return;
1236 }
1237
1238 // If -print-pipeline-passes is requested, don't run the legacy pass manager.
1239 // FIXME: when codegen is switched to use the new pass manager, it should also
1240 // emit pass names here.
1241 if (PrintPipelinePasses) {
1242 return;
1243 }
1244
1245 {
1246 PrettyStackTraceString CrashInfo("Code generation");
1247 llvm::TimeTraceScope TimeScope("CodeGenPasses");
1248 Timer timer;
1249 if (CI.getCodeGenOpts().TimePasses) {
1250 timer.init("codegen", "Machine code generation", CI.getTimerGroup());
1251 CI.getFrontendTimer().yieldTo(timer);
1252 }
1253 CodeGenPasses.run(*TheModule);
1254 if (CI.getCodeGenOpts().TimePasses)
1255 timer.yieldTo(CI.getFrontendTimer());
1256 }
1257}
1258
1259void EmitAssemblyHelper::emitAssembly(BackendAction Action,
1260 std::unique_ptr<raw_pwrite_stream> OS,
1261 BackendConsumer *BC) {
1262 setCommandLineOpts(CodeGenOpts);
1263
1264 bool RequiresCodeGen = actionRequiresCodeGen(Action);
1265 CreateTargetMachine(RequiresCodeGen);
1266
1267 if (RequiresCodeGen && !TM)
1268 return;
1269 if (TM)
1270 TheModule->setDataLayout(TM->createDataLayout());
1271
1272 // Before executing passes, print the final values of the LLVM options.
1273 cl::PrintOptionValues();
1274
1275 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1276 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1277 RunCodegenPipeline(Action, OS, DwoOS);
1278
1279 if (ThinLinkOS)
1280 ThinLinkOS->keep();
1281 if (DwoOS)
1282 DwoOS->keep();
1283}
1284
1285static void
1286runThinLTOBackend(CompilerInstance &CI, ModuleSummaryIndex *CombinedIndex,
1287 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1288 std::string SampleProfile, std::string ProfileRemapping,
1289 BackendAction Action) {
1290 DiagnosticsEngine &Diags = CI.getDiagnostics();
1291 const auto &CGOpts = CI.getCodeGenOpts();
1292 const auto &TOpts = CI.getTargetOpts();
1293 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1294 ModuleToDefinedGVSummaries;
1295 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1296
1297 setCommandLineOpts(CGOpts);
1298
1299 // We can simply import the values mentioned in the combined index, since
1300 // we should only invoke this using the individual indexes written out
1301 // via a WriteIndexesThinBackend.
1302 FunctionImporter::ImportIDTable ImportIDs;
1303 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1304 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1305 return;
1306
1307 auto AddStream = [&](size_t Task, const Twine &ModuleName) {
1308 return std::make_unique<CachedFileStream>(std::move(OS),
1309 CGOpts.ObjectFilenameForDebug);
1310 };
1311 lto::Config Conf;
1312 if (CGOpts.SaveTempsFilePrefix != "") {
1313 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1314 /* UseInputModulePath */ false)) {
1315 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1316 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1317 << '\n';
1318 });
1319 }
1320 }
1321 Conf.CPU = TOpts.CPU;
1322 Conf.CodeModel = getCodeModel(CGOpts);
1323 Conf.MAttrs = TOpts.Features;
1324 Conf.RelocModel = CGOpts.RelocationModel;
1325 std::optional<CodeGenOptLevel> OptLevelOrNone =
1326 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1327 assert(OptLevelOrNone && "Invalid optimization level!");
1328 Conf.CGOptLevel = *OptLevelOrNone;
1329 Conf.OptLevel = CGOpts.OptimizationLevel;
1330 initTargetOptions(CI, Diags, Conf.Options);
1331 Conf.SampleProfile = std::move(SampleProfile);
1332 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1333 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1334 // For historical reasons, loop interleaving is set to mirror setting for loop
1335 // unrolling.
1336 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1337 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1338 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1339 // Only enable CGProfilePass when using integrated assembler, since
1340 // non-integrated assemblers don't recognize .cgprofile section.
1341 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1342
1343 // Context sensitive profile.
1344 if (CGOpts.hasProfileCSIRInstr()) {
1345 Conf.RunCSIRInstr = true;
1346 Conf.CSIRProfile = getProfileGenName(CGOpts);
1347 } else if (CGOpts.hasProfileCSIRUse()) {
1348 Conf.RunCSIRInstr = false;
1349 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1350 }
1351
1352 Conf.ProfileRemapping = std::move(ProfileRemapping);
1353 Conf.DebugPassManager = CGOpts.DebugPassManager;
1354 Conf.VerifyEach = CGOpts.VerifyEach;
1355 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1356 Conf.RemarksFilename = CGOpts.OptRecordFile;
1357 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1358 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1359 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1360 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1361 switch (Action) {
1363 Conf.PreCodeGenModuleHook = [](size_t Task, const llvm::Module &Mod) {
1364 return false;
1365 };
1366 break;
1367 case Backend_EmitLL:
1368 Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
1369 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1370 return false;
1371 };
1372 break;
1373 case Backend_EmitBC:
1374 Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
1375 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1376 return false;
1377 };
1378 break;
1379 default:
1380 Conf.CGFileType = getCodeGenFileType(Action);
1381 break;
1382 }
1383 if (Error E =
1384 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1385 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1386 /*ModuleMap=*/nullptr, Conf.CodeGenOnly,
1387 /*IRAddStream=*/nullptr, CGOpts.CmdArgs)) {
1388 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1389 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1390 });
1391 }
1392}
1393
1395 StringRef TDesc, llvm::Module *M,
1396 BackendAction Action,
1398 std::unique_ptr<raw_pwrite_stream> OS,
1399 BackendConsumer *BC) {
1400 llvm::TimeTraceScope TimeScope("Backend");
1401 DiagnosticsEngine &Diags = CI.getDiagnostics();
1402
1403 std::unique_ptr<llvm::Module> EmptyModule;
1404 if (!CGOpts.ThinLTOIndexFile.empty()) {
1405 // If we are performing a ThinLTO importing compile, load the function index
1406 // into memory and pass it into runThinLTOBackend, which will run the
1407 // function importer and invoke LTO passes.
1408 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1409 if (Error E = llvm::getModuleSummaryIndexForFile(
1410 CGOpts.ThinLTOIndexFile,
1411 /*IgnoreEmptyThinLTOIndexFile*/ true)
1412 .moveInto(CombinedIndex)) {
1413 logAllUnhandledErrors(std::move(E), errs(),
1414 "Error loading index file '" +
1415 CGOpts.ThinLTOIndexFile + "': ");
1416 return;
1417 }
1418
1419 // A null CombinedIndex means we should skip ThinLTO compilation
1420 // (LLVM will optionally ignore empty index files, returning null instead
1421 // of an error).
1422 if (CombinedIndex) {
1423 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1424 runThinLTOBackend(CI, CombinedIndex.get(), M, std::move(OS),
1426 Action);
1427 return;
1428 }
1429 // Distributed indexing detected that nothing from the module is needed
1430 // for the final linking. So we can skip the compilation. We sill need to
1431 // output an empty object file to make sure that a linker does not fail
1432 // trying to read it. Also for some features, like CFI, we must skip
1433 // the compilation as CombinedIndex does not contain all required
1434 // information.
1435 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1436 EmptyModule->setTargetTriple(M->getTargetTriple());
1437 M = EmptyModule.get();
1438 }
1439 }
1440
1441 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1442 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1443
1444 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1445 // DataLayout.
1446 if (AsmHelper.TM) {
1447 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1448 if (DLDesc != TDesc) {
1449 unsigned DiagID = Diags.getCustomDiagID(
1450 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1451 "expected target description '%1'");
1452 Diags.Report(DiagID) << DLDesc << TDesc;
1453 }
1454 }
1455}
1456
1457// With -fembed-bitcode, save a copy of the llvm IR as data in the
1458// __LLVM,__bitcode section.
1459void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1460 llvm::MemoryBufferRef Buf) {
1461 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1462 return;
1463 llvm::embedBitcodeInModule(
1464 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1465 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1466 CGOpts.CmdArgs);
1467}
1468
1469void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1470 DiagnosticsEngine &Diags) {
1471 if (CGOpts.OffloadObjects.empty())
1472 return;
1473
1474 for (StringRef OffloadObject : CGOpts.OffloadObjects) {
1475 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1476 llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1477 if (ObjectOrErr.getError()) {
1478 auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1479 "could not open '%0' for embedding");
1480 Diags.Report(DiagID) << OffloadObject;
1481 return;
1482 }
1483
1484 llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading",
1485 Align(object::OffloadBinary::getAlignment()));
1486 }
1487}
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 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 void setCommandLineOpts(const CodeGenOptions &CodeGenOpts)
static CodeGenFileType getCodeGenFileType(BackendAction Action)
static std::string flattenClangCommandLine(ArrayRef< std::string > Args, StringRef MainFilename)
Defines the Diagnostic-related interfaces.
IndirectLocalPath & Path
Expr * E
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)
Definition: SourceCode.cpp:201
Defines the clang::TargetOptions class.
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
TargetOptions & getTargetOpts()
HeaderSearchOptions & getHeaderSearchOpts()
LangOptions & getLangOpts()
CodeGenOptions & getCodeGenOpts()
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1529
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:904
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:440
std::vector< std::string > NoSanitizeFiles
Paths to files specifying which objects (files, functions, variables) should not be instrumented.
Definition: LangOptions.h:446
std::optional< std::vector< unsigned > > getAllScaled(unsigned ScalingFactor) const
Definition: Sanitizers.cpp:46
Options for controlling the target.
Definition: TargetOptions.h:26
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
Definition: TargetOptions.h:58
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:45
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
llvm::EABI EABIVersion
The EABI version to use.
Definition: TargetOptions.h:48
Create and return a pass that links in Moduels from a provided BackendConsumer to a given primary Mod...
@ VFS
Remove unused -ivfsoverlay arguments.
The JSON file list parser is used to communicate input to InstallAPI.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
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 EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
BackendAction
Definition: BackendUtil.h:33
@ Backend_EmitAssembly
Emit native assembly files.
Definition: BackendUtil.h:34
@ Backend_EmitLL
Emit human-readable LLVM assembly.
Definition: BackendUtil.h:36
@ Backend_EmitBC
Emit LLVM bitcode files.
Definition: BackendUtil.h:35
@ Backend_EmitObj
Emit native object files.
Definition: BackendUtil.h:39
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
Definition: BackendUtil.h:38
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
Definition: BackendUtil.h:37
const FunctionProtoType * T
unsigned int uint32_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
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.
Definition: Sanitizers.h:174