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
9#include "clang/CodeGen/BackendUtil.h"
10#include "BackendConsumer.h"
11#include "LinkInModulesPass.h"
12#include "clang/Basic/CodeGenOptions.h"
13#include "clang/Basic/Diagnostic.h"
14#include "clang/Basic/DiagnosticFrontend.h"
15#include "clang/Basic/LangOptions.h"
16#include "clang/Basic/TargetOptions.h"
17#include "clang/Frontend/Utils.h"
18#include "clang/Lex/HeaderSearchOptions.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Analysis/GlobalsModRef.h"
22#include "llvm/Analysis/RuntimeLibcallInfo.h"
23#include "llvm/Analysis/TargetLibraryInfo.h"
24#include "llvm/Analysis/TargetTransformInfo.h"
25#include "llvm/BinaryFormat/ELF.h"
26#include "llvm/Bitcode/BitcodeReader.h"
27#include "llvm/Bitcode/BitcodeWriter.h"
28#include "llvm/Bitcode/BitcodeWriterPass.h"
29#include "llvm/CodeGen/MachineModuleInfo.h"
30#include "llvm/CodeGen/TargetSubtargetInfo.h"
31#include "llvm/Config/llvm-config.h"
32#include "llvm/Frontend/Driver/CodeGenOptions.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DebugInfo.h"
35#include "llvm/IR/LLVMRemarkStreamer.h"
36#include "llvm/IR/LegacyPassManager.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/ModuleSummaryIndex.h"
39#include "llvm/IR/PassManager.h"
40#include "llvm/IR/Verifier.h"
41#include "llvm/IRPrinter/IRPrintingPasses.h"
42#include "llvm/LTO/LTOBackend.h"
43#include "llvm/MC/TargetRegistry.h"
44#include "llvm/Object/OffloadBinary.h"
45#include "llvm/Passes/PassBuilder.h"
46#include "llvm/Passes/StandardInstrumentations.h"
47#include "llvm/Plugins/PassPlugin.h"
48#include "llvm/ProfileData/InstrProfCorrelator.h"
49#include "llvm/Support/BuryPointer.h"
50#include "llvm/Support/CodeGen.h"
51#include "llvm/Support/CommandLine.h"
52#include "llvm/Support/Compiler.h"
53#include "llvm/Support/IOSandbox.h"
54#include "llvm/Support/MemoryBuffer.h"
55#include "llvm/Support/PrettyStackTrace.h"
56#include "llvm/Support/Program.h"
57#include "llvm/Support/TimeProfiler.h"
58#include "llvm/Support/Timer.h"
59#include "llvm/Support/ToolOutputFile.h"
60#include "llvm/Support/VirtualFileSystem.h"
61#include "llvm/Support/raw_ostream.h"
62#include "llvm/Target/TargetMachine.h"
63#include "llvm/Target/TargetOptions.h"
64#include "llvm/TargetParser/SubtargetFeature.h"
65#include "llvm/TargetParser/Triple.h"
66#include "llvm/Transforms/HipStdPar/HipStdPar.h"
67#include "llvm/Transforms/IPO/EmbedBitcodePass.h"
68#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
69#include "llvm/Transforms/IPO/LowerTypeTests.h"
70#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
71#include "llvm/Transforms/InstCombine/InstCombine.h"
72#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
73#include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
74#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
75#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
76#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
77#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
78#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
79#include "llvm/Transforms/Instrumentation/KCFI.h"
80#include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
81#include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
82#include "llvm/Transforms/Instrumentation/MemProfUse.h"
83#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
84#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
85#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
86#include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
87#include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
88#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
89#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
90#include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
91#include "llvm/Transforms/ObjCARC.h"
92#include "llvm/Transforms/Scalar/EarlyCSE.h"
93#include "llvm/Transforms/Scalar/GVN.h"
94#include "llvm/Transforms/Scalar/JumpThreading.h"
95#include "llvm/Transforms/Utils/AssignGUID.h"
96#include "llvm/Transforms/Utils/Debugify.h"
97#include "llvm/Transforms/Utils/DynamicDebugging.h"
98#include "llvm/Transforms/Utils/ModuleUtils.h"
99#include <limits>
100#include <memory>
101#include <optional>
102using namespace clang;
103using namespace llvm;
104
105#define HANDLE_EXTENSION(Ext) \
106 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
107#include "llvm/Support/Extension.def"
108
109namespace llvm {
110// Experiment to move sanitizers earlier.
111static cl::opt<bool> ClSanitizeOnOptimizerEarlyEP(
112 "sanitizer-early-opt-ep", cl::Optional,
113 cl::desc("Insert sanitizers on OptimizerEarlyEP."));
114
115// Experiment to mark cold functions as optsize/minsize/optnone.
116// TODO: remove once this is exposed as a proper driver flag.
117static cl::opt<PGOOptions::ColdFuncOpt> ClPGOColdFuncAttr(
118 "pgo-cold-func-opt", cl::init(Val: PGOOptions::ColdFuncOpt::Default), cl::Hidden,
119 cl::desc(
120 "Function attribute to apply to cold functions as determined by PGO"),
121 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default, "default",
122 "Default (no attribute)"),
123 clEnumValN(PGOOptions::ColdFuncOpt::OptSize, "optsize",
124 "Mark cold functions with optsize."),
125 clEnumValN(PGOOptions::ColdFuncOpt::MinSize, "minsize",
126 "Mark cold functions with minsize."),
127 clEnumValN(PGOOptions::ColdFuncOpt::OptNone, "optnone",
128 "Mark cold functions with optnone.")));
129
130LLVM_ABI extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
131 ProfileCorrelate;
132} // namespace llvm
133namespace clang {
134extern llvm::cl::opt<bool> ClSanitizeGuardChecks;
135}
136
137// Path and name of file used for profile generation
138static std::string getProfileGenName(const CodeGenOptions &CodeGenOpts) {
139 std::string FileName = CodeGenOpts.InstrProfileOutput.empty()
140 ? llvm::driver::getDefaultProfileGenName()
141 : CodeGenOpts.InstrProfileOutput;
142 if (CodeGenOpts.ContinuousProfileSync)
143 FileName = "%c" + FileName;
144 return FileName;
145}
146
147namespace {
148
149class EmitAssemblyHelper {
150 CompilerInstance &CI;
151 DiagnosticsEngine &Diags;
152 const CodeGenOptions &CodeGenOpts;
153 const clang::TargetOptions &TargetOpts;
154 const LangOptions &LangOpts;
155 llvm::Module *TheModule;
156 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
157
158 std::unique_ptr<raw_pwrite_stream> OS;
159
160 Triple TargetTriple;
161
162 TargetIRAnalysis getTargetIRAnalysis() const {
163 if (TM)
164 return TM->getTargetIRAnalysis();
165
166 return TargetIRAnalysis();
167 }
168
169 /// Generates the TargetMachine.
170 /// Leaves TM unchanged if it is unable to create the target machine.
171 /// Some of our clang tests specify triples which are not built
172 /// into clang. This is okay because these tests check the generated
173 /// IR, and they require DataLayout which depends on the triple.
174 /// In this case, we allow this method to fail and not report an error.
175 /// When MustCreateTM is used, we print an error if we are unable to load
176 /// the requested target.
177 void CreateTargetMachine(bool MustCreateTM);
178
179 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
180 std::error_code EC;
181 auto F = std::make_unique<llvm::ToolOutputFile>(args&: Path, args&: EC,
182 args: llvm::sys::fs::OF_None);
183 if (EC) {
184 Diags.Report(DiagID: diag::err_fe_unable_to_open_output) << Path << EC.message();
185 F.reset();
186 }
187 return F;
188 }
189
190 void RunOptimizationPipeline(
191 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
192 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
193 void RunCodegenPipeline(BackendAction Action,
194 std::unique_ptr<raw_pwrite_stream> &OS,
195 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
196 void RunCodegenPipelineLegacy(BackendAction Action,
197 std::unique_ptr<raw_pwrite_stream> &OS,
198 std::unique_ptr<llvm::ToolOutputFile> &DwoOS,
199 CodeGenFileType CGFT);
200 void RunCodegenPipelineNewPM(BackendAction Action,
201 std::unique_ptr<raw_pwrite_stream> &OS,
202 std::unique_ptr<llvm::ToolOutputFile> &DwoOS,
203 CodeGenFileType CGFT);
204 void TimeCodegenPasses(llvm::function_ref<void()> RunPasses);
205
206 /// Check whether we should emit a module summary for regular LTO.
207 /// The module summary should be emitted by default for regular LTO
208 /// except for ld64 targets.
209 ///
210 /// \return True if the module summary should be emitted.
211 bool shouldEmitRegularLTOSummary() const {
212 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
213 TargetTriple.getVendor() != llvm::Triple::Apple;
214 }
215
216 /// Check whether we should emit a flag for UnifiedLTO.
217 /// The UnifiedLTO module flag should be set when UnifiedLTO is enabled for
218 /// ThinLTO or Full LTO with module summaries.
219 bool shouldEmitUnifiedLTOModueFlag() const {
220 return CodeGenOpts.UnifiedLTO &&
221 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
222 }
223
224public:
225 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
226 llvm::Module *M,
227 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
228 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
229 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
230 TheModule(M), VFS(std::move(VFS)),
231 TargetTriple(TheModule->getTargetTriple()) {}
232
233 ~EmitAssemblyHelper() {
234 if (CodeGenOpts.DisableFree)
235 BuryPointer(Ptr: std::move(TM));
236 }
237
238 std::unique_ptr<TargetMachine> TM;
239
240 // Emit output using the new pass manager for the optimization pipeline.
241 void emitAssembly(BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
242 BackendConsumer *BC);
243};
244} // namespace
245
246static SanitizerCoverageOptions
247getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
248 SanitizerCoverageOptions Opts;
249 Opts.CoverageType =
250 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
251 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
252 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
253 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
254 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
255 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
256 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
257 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
258 Opts.TracePCEntryExit = CGOpts.SanitizeCoverageTracePCEntryExit;
259 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
260 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
261 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
262 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
263 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
264 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
265 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
266 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
267 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
268 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
269 return Opts;
270}
271
272static SanitizerBinaryMetadataOptions
273getSanitizerBinaryMetadataOptions(const CodeGenOptions &CGOpts) {
274 SanitizerBinaryMetadataOptions Opts;
275 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
276 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
277 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
278 return Opts;
279}
280
281// Check if ASan should use GC-friendly instrumentation for globals.
282// First of all, there is no point if -fdata-sections is off (expect for MachO,
283// where this is not a factor). Also, on ELF this feature requires an assembler
284// extension that only works with -integrated-as at the moment.
285static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
286 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
287 return false;
288 switch (T.getObjectFormat()) {
289 case Triple::MachO:
290 case Triple::COFF:
291 return true;
292 case Triple::ELF:
293 return !CGOpts.DisableIntegratedAS;
294 case Triple::GOFF:
295 llvm::report_fatal_error(reason: "ASan not implemented for GOFF");
296 case Triple::XCOFF:
297 llvm::report_fatal_error(reason: "ASan not implemented for XCOFF.");
298 case Triple::Wasm:
299 case Triple::DXContainer:
300 case Triple::SPIRV:
301 case Triple::UnknownObjectFormat:
302 break;
303 }
304 return false;
305}
306
307static std::optional<llvm::CodeModel::Model>
308getCodeModel(const CodeGenOptions &CodeGenOpts) {
309 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
310 .Case(S: "tiny", Value: llvm::CodeModel::Tiny)
311 .Case(S: "small", Value: llvm::CodeModel::Small)
312 .Case(S: "kernel", Value: llvm::CodeModel::Kernel)
313 .Case(S: "medium", Value: llvm::CodeModel::Medium)
314 .Case(S: "large", Value: llvm::CodeModel::Large)
315 .Cases(CaseStrings: {"default", ""}, Value: ~1u)
316 .Default(Value: ~0u);
317 assert(CodeModel != ~0u && "invalid code model!");
318 if (CodeModel == ~1u)
319 return std::nullopt;
320 return static_cast<llvm::CodeModel::Model>(CodeModel);
321}
322
323static CodeGenFileType getCodeGenFileType(BackendAction Action) {
324 if (Action == Backend_EmitObj)
325 return CodeGenFileType::ObjectFile;
326 else if (Action == Backend_EmitMCNull)
327 return CodeGenFileType::Null;
328 else {
329 assert(Action == Backend_EmitAssembly && "Invalid action!");
330 return CodeGenFileType::AssemblyFile;
331 }
332}
333
334static bool actionRequiresCodeGen(BackendAction Action) {
335 return Action != Backend_EmitNothing && Action != Backend_EmitBC &&
336 Action != Backend_EmitLL;
337}
338
339static std::string flattenClangCommandLine(ArrayRef<std::string> Args,
340 StringRef MainFilename,
341 ArrayRef<StringRef> InputFiles) {
342 if (Args.empty())
343 return std::string{};
344
345 std::string FlatCmdLine;
346 raw_string_ostream OS(FlatCmdLine);
347 bool PrintedOneArg = false;
348 if (!StringRef(Args[0]).contains(Other: "-cc1")) {
349 llvm::sys::printArg(OS, Arg: "-cc1", /*Quote=*/true);
350 PrintedOneArg = true;
351 }
352 for (unsigned i = 0; i < Args.size(); i++) {
353 StringRef Arg = Args[i];
354 if (Arg.empty())
355 continue;
356 if (Arg == "-main-file-name" || Arg == "-o") {
357 i++; // Skip this argument and next one.
358 continue;
359 }
360 if (Arg.starts_with(Prefix: "-object-file-name"))
361 continue;
362 // Strip the source positional, matching either MainFilename (the
363 // -main-file-name basename) or one of the resolved frontend input paths
364 // (which is what the cc1 positional looks like for an absolute driver
365 // input). Avoid a generic basename match: it would also strip values of
366 // args like `-include <path>` whose trailing component happens to equal
367 // the source basename.
368 if (Arg == MainFilename || llvm::is_contained(Range&: InputFiles, Element: Arg))
369 continue;
370 // Skip fmessage-length for reproducibility.
371 if (Arg.starts_with(Prefix: "-fmessage-length"))
372 continue;
373 if (PrintedOneArg)
374 OS << " ";
375 llvm::sys::printArg(OS, Arg, /*Quote=*/true);
376 PrintedOneArg = true;
377 }
378 return FlatCmdLine;
379}
380
381static bool initTargetOptions(const CompilerInstance &CI,
382 DiagnosticsEngine &Diags,
383 llvm::TargetOptions &Options) {
384 const auto &CodeGenOpts = CI.getCodeGenOpts();
385 const auto &TargetOpts = CI.getTargetOpts();
386 const auto &LangOpts = CI.getLangOpts();
387 const auto &HSOpts = CI.getHeaderSearchOpts();
388 switch (LangOpts.getThreadModel()) {
389 case LangOptions::ThreadModelKind::POSIX:
390 Options.ThreadModel = llvm::ThreadModel::POSIX;
391 break;
392 case LangOptions::ThreadModelKind::Single:
393 Options.ThreadModel = llvm::ThreadModel::Single;
394 break;
395 }
396
397 // Set FP fusion mode.
398 switch (LangOpts.getDefaultFPContractMode()) {
399 case LangOptions::FPM_Off:
400 // Preserve any contraction performed by the front-end. (Strict performs
401 // splitting of the muladd intrinsic in the backend.)
402 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
403 break;
404 case LangOptions::FPM_On:
405 case LangOptions::FPM_FastHonorPragmas:
406 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
407 break;
408 case LangOptions::FPM_Fast:
409 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
410 break;
411 }
412
413 Options.BinutilsVersion =
414 llvm::TargetMachine::parseBinutilsVersion(Version: CodeGenOpts.BinutilsVersion);
415 Options.UseInitArray = CodeGenOpts.UseInitArray;
416 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
417
418 // Set EABI version.
419 Options.EABIVersion = TargetOpts.EABIVersion;
420
421 if (CodeGenOpts.hasSjLjExceptions())
422 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
423 if (CodeGenOpts.hasSEHExceptions())
424 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
425 if (CodeGenOpts.hasDWARFExceptions())
426 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
427 if (CodeGenOpts.hasWasmExceptions())
428 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
429
430 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
431
432 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
433 Options.BBSections =
434 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
435 .Case(S: "all", Value: llvm::BasicBlockSection::All)
436 .StartsWith(S: "list=", Value: llvm::BasicBlockSection::List)
437 .Case(S: "none", Value: llvm::BasicBlockSection::None)
438 .Default(Value: llvm::BasicBlockSection::None);
439
440 if (Options.BBSections == llvm::BasicBlockSection::List) {
441 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
442 CI.getVirtualFileSystem().getBufferForFile(
443 Name: CodeGenOpts.BBSections.substr(pos: 5));
444 if (!MBOrErr) {
445 Diags.Report(DiagID: diag::err_fe_unable_to_load_basic_block_sections_file)
446 << MBOrErr.getError().message();
447 return false;
448 }
449 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
450 }
451
452 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
453 Options.EnableStaticDataPartitioning =
454 CodeGenOpts.PartitionStaticDataSections;
455 Options.FunctionSections = CodeGenOpts.FunctionSections;
456 Options.DataSections = CodeGenOpts.DataSections;
457 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
458 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
459 Options.UniqueBasicBlockSectionNames =
460 CodeGenOpts.UniqueBasicBlockSectionNames;
461 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
462 Options.TLSSize = CodeGenOpts.TLSSize;
463 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
464 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
465 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
466 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
467 Options.StackUsageFile = CodeGenOpts.StackUsageFile;
468 Options.EmitAddrsig = CodeGenOpts.Addrsig;
469 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
470 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
471 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
472 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
473 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
474 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
475 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
476 Options.ObjectFilenameForDebug =
477 CodeGenOpts.remapDebugPathPrefix(Path: CodeGenOpts.ObjectFilenameForDebug);
478 Options.Hotpatch = CodeGenOpts.HotPatch;
479 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
480 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
481 Options.VecLib =
482 convertDriverVectorLibraryToVectorLibrary(VecLib: CodeGenOpts.getVecLib());
483
484 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
485 case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
486 Options.SwiftAsyncFramePointer =
487 SwiftAsyncFramePointerMode::DeploymentBased;
488 break;
489
490 case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
491 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
492 break;
493
494 case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
495 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
496 break;
497 }
498
499 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
500 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
501 Options.MCOptions.EmitCompactUnwindNonCanonical =
502 CodeGenOpts.EmitCompactUnwindNonCanonical;
503 Options.MCOptions.EmitSFrameUnwind = CodeGenOpts.EmitSFrameUnwind;
504 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
505 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
506 Options.MCOptions.MCUseDwarfDirectory =
507 CodeGenOpts.NoDwarfDirectoryAsm
508 ? llvm::MCTargetOptions::DisableDwarfDirectory
509 : llvm::MCTargetOptions::EnableDwarfDirectory;
510 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
511 Options.MCOptions.MCIncrementalLinkerCompatible =
512 CodeGenOpts.IncrementalLinkerCompatible;
513 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
514 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
515 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
516 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
517 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
518 Options.MCOptions.Crel = CodeGenOpts.Crel;
519 Options.MCOptions.RelocSectionSym = CodeGenOpts.getRelocSectionSym();
520 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
521 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
522 Options.MCOptions.CompressDebugSections =
523 CodeGenOpts.getCompressDebugSections();
524 if (CodeGenOpts.OutputAsmVariant != 3) // 3 (default): not specified
525 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
526 Options.MCOptions.ABIName = TargetOpts.ABI;
527 for (const auto &Entry : HSOpts.UserEntries)
528 if (!Entry.IsFramework &&
529 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
530 Entry.Group == frontend::IncludeDirGroup::Angled ||
531 Entry.Group == frontend::IncludeDirGroup::System))
532 Options.MCOptions.IASSearchPaths.push_back(
533 x: Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
534 Options.MCOptions.Argv0 = CodeGenOpts.Argv0 ? CodeGenOpts.Argv0 : "";
535 // Pass the resolved frontend inputs so flattenClangCommandLine can strip
536 // the cc1 source positional even when the driver received an absolute path
537 // (which won't match CodeGenOpts.MainFileName, that's just the basename).
538 SmallVector<StringRef, 1> InputFiles;
539 for (const auto &Input : CI.getFrontendOpts().Inputs)
540 if (Input.isFile())
541 InputFiles.push_back(Elt: Input.getFile());
542 Options.MCOptions.CommandlineArgs = flattenClangCommandLine(
543 Args: CodeGenOpts.CommandLineArgs, MainFilename: CodeGenOpts.MainFileName, InputFiles);
544 Options.MCOptions.AsSecureLogFile = CodeGenOpts.AsSecureLogFile;
545 Options.MCOptions.PPCUseFullRegisterNames =
546 CodeGenOpts.PPCUseFullRegisterNames;
547 Options.MisExpect = CodeGenOpts.MisExpect;
548
549 return true;
550}
551
552static std::optional<GCOVOptions>
553getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts) {
554 if (CodeGenOpts.CoverageNotesFile.empty() &&
555 CodeGenOpts.CoverageDataFile.empty())
556 return std::nullopt;
557 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
558 // LLVM's -default-gcov-version flag is set to something invalid.
559 GCOVOptions Options;
560 Options.EmitNotes = !CodeGenOpts.CoverageNotesFile.empty();
561 Options.EmitData = !CodeGenOpts.CoverageDataFile.empty();
562 llvm::copy(Range: CodeGenOpts.CoverageVersion, Out: std::begin(arr&: Options.Version));
563 Options.NoRedZone = CodeGenOpts.DisableRedZone;
564 Options.Filter = CodeGenOpts.ProfileFilterFiles;
565 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
566 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
567 return Options;
568}
569
570static std::optional<InstrProfOptions>
571getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
572 const LangOptions &LangOpts) {
573 if (!CodeGenOpts.hasProfileClangInstr())
574 return std::nullopt;
575 InstrProfOptions Options;
576 Options.NoRedZone = CodeGenOpts.DisableRedZone;
577 Options.InstrProfileOutput = CodeGenOpts.ContinuousProfileSync
578 ? ("%c" + CodeGenOpts.InstrProfileOutput)
579 : CodeGenOpts.InstrProfileOutput;
580 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
581 return Options;
582}
583
584static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts,
585 vfs::FileSystem &VFS) {
586 SmallVector<const char *, 16> BackendArgs;
587 BackendArgs.push_back(Elt: "clang"); // Fake program name.
588 if (!CodeGenOpts.DebugPass.empty()) {
589 BackendArgs.push_back(Elt: "-debug-pass");
590 BackendArgs.push_back(Elt: CodeGenOpts.DebugPass.c_str());
591 }
592 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
593 BackendArgs.push_back(Elt: "-limit-float-precision");
594 BackendArgs.push_back(Elt: CodeGenOpts.LimitFloatPrecision.c_str());
595 }
596
597 // Check for the default "clang" invocation that won't set any cl::opt values.
598 // Skip trying to parse the command line invocation to avoid the issues
599 // described below.
600 if (BackendArgs.size() == 1)
601 return;
602 BackendArgs.push_back(Elt: nullptr);
603 // FIXME: The command line parser below is not thread-safe and shares a global
604 // state, so this call might crash or overwrite the options of another Clang
605 // instance in the same process.
606 llvm::cl::ParseCommandLineOptions(argc: BackendArgs.size() - 1, argv: BackendArgs.data(),
607 /*Overview=*/"", /*Errs=*/nullptr,
608 /*VFS=*/&VFS);
609}
610
611void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
612 // Create the TargetMachine for generating code.
613 std::string Error;
614 const llvm::Triple &Triple = TheModule->getTargetTriple();
615 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(TheTriple: Triple, Error);
616 if (!TheTarget) {
617 if (MustCreateTM)
618 Diags.Report(DiagID: diag::err_fe_unable_to_create_target) << Error;
619 return;
620 }
621
622 std::optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
623 std::string FeaturesStr =
624 llvm::join(Begin: TargetOpts.Features.begin(), End: TargetOpts.Features.end(), Separator: ",");
625 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
626 std::optional<CodeGenOptLevel> OptLevelOrNone =
627 CodeGenOpt::getLevel(OL: CodeGenOpts.OptimizationLevel);
628 assert(OptLevelOrNone && "Invalid optimization level!");
629 CodeGenOptLevel OptLevel = *OptLevelOrNone;
630
631 llvm::TargetOptions Options;
632 if (!initTargetOptions(CI, Diags, Options))
633 return;
634 TM.reset(p: TheTarget->createTargetMachine(TT: Triple, CPU: TargetOpts.CPU, Features: FeaturesStr,
635 Options, RM, CM, OL: OptLevel));
636 if (TM)
637 TM->setLargeDataThreshold(CodeGenOpts.LargeDataThreshold);
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 return OptimizationLevel::O2;
653
654 case 3:
655 return OptimizationLevel::O3;
656 }
657}
658
659static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts,
660 PassBuilder &PB) {
661 // If the back-end supports KCFI operand bundle lowering, skip KCFIPass.
662 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
663 TargetTriple.isAArch64(PointerWidth: 64) || TargetTriple.isRISCV() ||
664 TargetTriple.isARM() || TargetTriple.isThumb() ||
665 TargetTriple.getArch() == llvm::Triple::hexagon)
666 return;
667
668 // Ensure we lower KCFI operand bundles with -O0.
669 PB.registerOptimizerLastEPCallback(
670 C: [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
671 if (Level == OptimizationLevel::O0 &&
672 LangOpts.Sanitize.has(K: SanitizerKind::KCFI))
673 MPM.addPass(Pass: createModuleToFunctionPassAdaptor(Pass: KCFIPass()));
674 });
675
676 // When optimizations are requested, run KCIFPass after InstCombine to
677 // avoid unnecessary checks.
678 PB.registerPeepholeEPCallback(
679 C: [&](FunctionPassManager &FPM, OptimizationLevel Level) {
680 if (Level != OptimizationLevel::O0 &&
681 LangOpts.Sanitize.has(K: SanitizerKind::KCFI))
682 FPM.addPass(Pass: KCFIPass());
683 });
684}
685
686static void addSanitizers(const Triple &TargetTriple,
687 const CodeGenOptions &CodeGenOpts,
688 const LangOptions &LangOpts, PassBuilder &PB) {
689 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
690 ThinOrFullLTOPhase) {
691 if (CodeGenOpts.hasSanitizeCoverage()) {
692 auto SancovOpts = getSancovOptsFromCGOpts(CGOpts: CodeGenOpts);
693 MPM.addPass(
694 Pass: SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
695 CodeGenOpts.SanitizeCoverageAllowlistFiles,
696 CodeGenOpts.SanitizeCoverageIgnorelistFiles));
697 }
698
699 if (CodeGenOpts.hasSanitizeBinaryMetadata()) {
700 MPM.addPass(Pass: SanitizerBinaryMetadataPass(
701 getSanitizerBinaryMetadataOptions(CGOpts: CodeGenOpts),
702 PB.getVirtualFileSystemPtr(),
703 CodeGenOpts.SanitizeMetadataIgnorelistFiles));
704 }
705
706 auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
707 if (LangOpts.Sanitize.has(K: Mask)) {
708 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
709 bool Recover = CodeGenOpts.SanitizeRecover.has(K: Mask);
710
711 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
712 CodeGenOpts.SanitizeMemoryParamRetval);
713 MPM.addPass(Pass: MemorySanitizerPass(options));
714 if (Level != OptimizationLevel::O0) {
715 // MemorySanitizer inserts complex instrumentation that mostly follows
716 // the logic of the original code, but operates on "shadow" values. It
717 // can benefit from re-running some general purpose optimization
718 // passes.
719 MPM.addPass(Pass: RequireAnalysisPass<GlobalsAA, llvm::Module>());
720 FunctionPassManager FPM;
721 FPM.addPass(Pass: EarlyCSEPass(true /* Enable mem-ssa. */));
722 FPM.addPass(Pass: InstCombinePass());
723 FPM.addPass(Pass: JumpThreadingPass());
724 FPM.addPass(Pass: GVNPass());
725 FPM.addPass(Pass: InstCombinePass());
726 MPM.addPass(Pass: createModuleToFunctionPassAdaptor(Pass: std::move(FPM)));
727 }
728 }
729 };
730 MSanPass(SanitizerKind::Memory, false);
731 MSanPass(SanitizerKind::KernelMemory, true);
732
733 if (LangOpts.Sanitize.has(K: SanitizerKind::Thread)) {
734 MPM.addPass(Pass: ModuleThreadSanitizerPass());
735 MPM.addPass(Pass: createModuleToFunctionPassAdaptor(Pass: ThreadSanitizerPass()));
736 }
737
738 if (LangOpts.Sanitize.has(K: SanitizerKind::Type))
739 MPM.addPass(Pass: TypeSanitizerPass());
740
741 if (LangOpts.Sanitize.has(K: SanitizerKind::NumericalStability))
742 MPM.addPass(Pass: NumericalStabilitySanitizerPass());
743
744 if (LangOpts.Sanitize.has(K: SanitizerKind::Realtime))
745 MPM.addPass(Pass: RealtimeSanitizerPass());
746
747 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
748 if (LangOpts.Sanitize.has(K: Mask)) {
749 bool UseGlobalGC = asanUseGlobalsGC(T: TargetTriple, CGOpts: CodeGenOpts);
750 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
751 llvm::AsanDtorKind DestructorKind =
752 CodeGenOpts.getSanitizeAddressDtor();
753 AddressSanitizerOptions Opts;
754 Opts.CompileKernel = CompileKernel;
755 Opts.Recover = CodeGenOpts.SanitizeRecover.has(K: Mask);
756 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
757 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
758 MPM.addPass(Pass: AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
759 DestructorKind));
760 }
761 };
762 ASanPass(SanitizerKind::Address, false);
763 ASanPass(SanitizerKind::KernelAddress, true);
764
765 auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
766 if (LangOpts.Sanitize.has(K: Mask)) {
767 bool Recover = CodeGenOpts.SanitizeRecover.has(K: Mask);
768 MPM.addPass(Pass: HWAddressSanitizerPass(
769 {CompileKernel, Recover,
770 /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
771 }
772 };
773 HWASanPass(SanitizerKind::HWAddress, false);
774 HWASanPass(SanitizerKind::KernelHWAddress, true);
775
776 if (LangOpts.Sanitize.has(K: SanitizerKind::DataFlow)) {
777 MPM.addPass(Pass: DataFlowSanitizerPass(LangOpts.NoSanitizeFiles,
778 PB.getVirtualFileSystemPtr()));
779 }
780 };
781 if (ClSanitizeOnOptimizerEarlyEP) {
782 PB.registerOptimizerEarlyEPCallback(
783 C: [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
784 ThinOrFullLTOPhase Phase) {
785 ModulePassManager NewMPM;
786 SanitizersCallback(NewMPM, Level, Phase);
787 if (!NewMPM.isEmpty()) {
788 // Sanitizers can abandon<GlobalsAA>.
789 NewMPM.addPass(Pass: RequireAnalysisPass<GlobalsAA, llvm::Module>());
790 MPM.addPass(Pass: std::move(NewMPM));
791 }
792 });
793 } else {
794 // LastEP does not need GlobalsAA.
795 PB.registerOptimizerLastEPCallback(C: SanitizersCallback);
796 }
797}
798
799void addLowerAllowCheckPass(const CodeGenOptions &CodeGenOpts,
800 const LangOptions &LangOpts, PassBuilder &PB) {
801 // SanitizeSkipHotCutoffs: doubles with range [0, 1]
802 // Opts.cutoffs: unsigned ints with range [0, 1000000]
803 auto ScaledCutoffs = CodeGenOpts.SanitizeSkipHotCutoffs.getAllScaled(ScalingFactor: 1000000);
804 uint64_t AllowRuntimeCheckSkipHotCutoff =
805 CodeGenOpts.AllowRuntimeCheckSkipHotCutoff.value_or(u: 0.0) * 1000000;
806 // Only register the pass if one of the relevant sanitizers is enabled.
807 // This avoids pipeline overhead for builds that do not use these sanitizers.
808 bool LowerAllowSanitize = LangOpts.Sanitize.hasOneOf(
809 K: SanitizerKind::Address | SanitizerKind::KernelAddress |
810 SanitizerKind::Thread | SanitizerKind::Memory |
811 SanitizerKind::KernelMemory | SanitizerKind::HWAddress |
812 SanitizerKind::KernelHWAddress);
813
814 // TODO: remove IsRequested()
815 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
816 CodeGenOpts.AllowRuntimeCheckSkipHotCutoff.has_value() ||
817 LowerAllowSanitize) {
818 // We want to call it after inline, which is about OptimizerEarlyEPCallback.
819 PB.registerOptimizerEarlyEPCallback(
820 C: [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
821 ModulePassManager &MPM, OptimizationLevel Level,
822 ThinOrFullLTOPhase Phase) {
823 LowerAllowCheckPass::Options Opts;
824 // TODO: after removing IsRequested(), make this unconditional
825 if (ScaledCutoffs.has_value())
826 Opts.cutoffs = ScaledCutoffs.value();
827 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
828 MPM.addPass(
829 Pass: createModuleToFunctionPassAdaptor(Pass: LowerAllowCheckPass(Opts)));
830 });
831 }
832}
833
834void EmitAssemblyHelper::RunOptimizationPipeline(
835 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
836 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
837 std::optional<PGOOptions> PGOOpt;
838
839 if (CodeGenOpts.hasProfileIRInstr())
840 // -fprofile-generate.
841 PGOOpt = PGOOptions(getProfileGenName(CodeGenOpts), "", "",
842 CodeGenOpts.MemoryProfileUsePath, PGOOptions::IRInstr,
843 PGOOptions::NoCSAction, ClPGOColdFuncAttr,
844 CodeGenOpts.DebugInfoForProfiling,
845 /*PseudoProbeForProfiling=*/false,
846 CodeGenOpts.AtomicProfileUpdate);
847 else if (CodeGenOpts.hasProfileIRUse()) {
848 // -fprofile-use.
849 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
850 : PGOOptions::NoCSAction;
851 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
852 CodeGenOpts.ProfileRemappingFile,
853 CodeGenOpts.MemoryProfileUsePath, PGOOptions::IRUse,
854 CSAction, ClPGOColdFuncAttr,
855 CodeGenOpts.DebugInfoForProfiling);
856 } else if (!CodeGenOpts.SampleProfileFile.empty())
857 // -fprofile-sample-use
858 PGOOpt = PGOOptions(
859 CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
860 CodeGenOpts.MemoryProfileUsePath, PGOOptions::SampleUse,
861 PGOOptions::NoCSAction, ClPGOColdFuncAttr,
862 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
863 else if (!CodeGenOpts.MemoryProfileUsePath.empty())
864 // -fmemory-profile-use (without any of the above options)
865 PGOOpt = PGOOptions("", "", "", CodeGenOpts.MemoryProfileUsePath,
866 PGOOptions::NoAction, PGOOptions::NoCSAction,
867 ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling);
868 else if (CodeGenOpts.PseudoProbeForProfiling)
869 // -fpseudo-probe-for-profiling
870 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", PGOOptions::NoAction,
871 PGOOptions::NoCSAction, ClPGOColdFuncAttr,
872 CodeGenOpts.DebugInfoForProfiling, true);
873 else if (CodeGenOpts.DebugInfoForProfiling)
874 // -fdebug-info-for-profiling
875 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", PGOOptions::NoAction,
876 PGOOptions::NoCSAction, ClPGOColdFuncAttr, true);
877
878 // Check to see if we want to generate a CS profile.
879 if (CodeGenOpts.hasProfileCSIRInstr()) {
880 assert(!CodeGenOpts.hasProfileCSIRUse() &&
881 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
882 "the same time");
883 if (PGOOpt) {
884 assert(PGOOpt->Action != PGOOptions::IRInstr &&
885 PGOOpt->Action != PGOOptions::SampleUse &&
886 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
887 " pass");
888 PGOOpt->CSProfileGenFile = getProfileGenName(CodeGenOpts);
889 PGOOpt->CSAction = PGOOptions::CSIRInstr;
890 } else
891 PGOOpt = PGOOptions("", getProfileGenName(CodeGenOpts), "",
892 /*MemoryProfile=*/"", PGOOptions::NoAction,
893 PGOOptions::CSIRInstr, ClPGOColdFuncAttr,
894 CodeGenOpts.DebugInfoForProfiling);
895 }
896 if (TM)
897 TM->setPGOOption(PGOOpt);
898
899 PipelineTuningOptions PTO;
900 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
901 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
902 PTO.LoopFusion = CodeGenOpts.FuseLoops;
903 // For historical reasons, loop interleaving is set to mirror setting for loop
904 // unrolling.
905 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
906 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
907 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
908 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
909 // Only enable CGProfilePass when using integrated assembler, since
910 // non-integrated assemblers don't recognize .cgprofile section.
911 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
912 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
913 PTO.DevirtualizeSpeculatively = CodeGenOpts.DevirtualizeSpeculatively;
914
915 LoopAnalysisManager LAM;
916 FunctionAnalysisManager FAM;
917 CGSCCAnalysisManager CGAM;
918 ModuleAnalysisManager MAM;
919
920 bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
921 PassInstrumentationCallbacks PIC;
922 PrintPassOptions PrintPassOpts;
923 PrintPassOpts.Indent = DebugPassStructure;
924 PrintPassOpts.SkipAnalyses = DebugPassStructure;
925 StandardInstrumentations SI(
926 TheModule->getContext(),
927 (CodeGenOpts.DebugPassManager || DebugPassStructure),
928 CodeGenOpts.VerifyEach, PrintPassOpts);
929 SI.registerCallbacks(PIC, MAM: &MAM);
930 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC, CI.getVirtualFileSystemPtr());
931
932 // Handle the assignment tracking feature options.
933 switch (CodeGenOpts.getAssignmentTrackingMode()) {
934 case CodeGenOptions::AssignmentTrackingOpts::Forced:
935 PB.registerPipelineStartEPCallback(
936 C: [&](ModulePassManager &MPM, OptimizationLevel Level) {
937 MPM.addPass(Pass: AssignmentTrackingPass());
938 });
939 break;
940 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
941 // Disable assignment tracking in LTO builds for now as the performance
942 // cost is too high. Disable for LLDB tuning due to llvm.org/PR43126.
943 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
944 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
945 PB.registerPipelineStartEPCallback(
946 C: [&](ModulePassManager &MPM, OptimizationLevel Level) {
947 // Only use assignment tracking if optimisations are enabled.
948 if (Level != OptimizationLevel::O0)
949 MPM.addPass(Pass: AssignmentTrackingPass());
950 });
951 }
952 break;
953 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
954 break;
955 }
956
957 // Enable verify-debuginfo-preserve-each for new PM.
958 DebugifyEachInstrumentation Debugify;
959 DebugInfoPerPass DebugInfoBeforePass;
960 if (CodeGenOpts.EnableDIPreservationVerify) {
961 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
962 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
963
964 if (!CodeGenOpts.DIBugsReportFilePath.empty())
965 Debugify.setOrigDIVerifyBugsReportFilePath(
966 CodeGenOpts.DIBugsReportFilePath);
967 Debugify.registerCallbacks(PIC, MAM);
968
969#if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
970 // If we're using debug location coverage tracking, mark all the
971 // instructions coming out of the frontend without a DebugLoc as being
972 // compiler-generated, to prevent both those instructions and new
973 // instructions that inherit their location from being treated as
974 // incorrectly empty locations.
975 for (Function &F : *TheModule) {
976 if (!F.getSubprogram())
977 continue;
978 for (BasicBlock &BB : F)
979 for (Instruction &I : BB)
980 if (!I.getDebugLoc())
981 I.setDebugLoc(DebugLoc::getCompilerGenerated());
982 }
983#endif
984 }
985 // Register plugin callbacks with PB.
986 for (const std::unique_ptr<PassPlugin> &Plugin : CI.getPassPlugins())
987 Plugin->registerPassBuilderCallbacks(PB);
988 for (const auto &PassCallback : CodeGenOpts.PassBuilderCallbacks)
989 PassCallback(PB);
990#define HANDLE_EXTENSION(Ext) \
991 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
992#include "llvm/Support/Extension.def"
993
994 // Register the target library analysis directly and give it a customized
995 // preset TLI.
996 std::unique_ptr<TargetLibraryInfoImpl> TLII(
997 llvm::driver::createTLII(TargetTriple, Veclib: CodeGenOpts.getVecLib()));
998 FAM.registerPass(PassBuilder: [&] { return TargetLibraryAnalysis(*TLII); });
999
1000 // Register all the basic analyses with the managers.
1001 PB.registerModuleAnalyses(MAM);
1002 PB.registerCGSCCAnalyses(CGAM);
1003 PB.registerFunctionAnalyses(FAM);
1004 PB.registerLoopAnalyses(LAM);
1005 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1006
1007 ModulePassManager MPM;
1008 // Add a verifier pass, before any other passes, to catch CodeGen issues.
1009 if (CodeGenOpts.VerifyModule)
1010 MPM.addPass(Pass: VerifierPass());
1011
1012 if (!CodeGenOpts.DisableLLVMPasses) {
1013 // Map our optimization levels into one of the distinct levels used to
1014 // configure the pipeline.
1015 OptimizationLevel Level = mapToLevel(Opts: CodeGenOpts);
1016
1017 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1018 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1019
1020 if (LangOpts.ObjCAutoRefCount) {
1021 PB.registerPipelineStartEPCallback(
1022 C: [](ModulePassManager &MPM, OptimizationLevel Level) {
1023 if (Level != OptimizationLevel::O0)
1024 MPM.addPass(
1025 Pass: createModuleToFunctionPassAdaptor(Pass: ObjCARCExpandPass()));
1026 });
1027 PB.registerScalarOptimizerLateEPCallback(
1028 C: [](FunctionPassManager &FPM, OptimizationLevel Level) {
1029 if (Level != OptimizationLevel::O0)
1030 FPM.addPass(Pass: ObjCARCOptPass());
1031 });
1032 }
1033
1034 // If we reached here with a non-empty index file name, then the index
1035 // file was empty and we are not performing ThinLTO backend compilation
1036 // (used in testing in a distributed build environment).
1037 bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
1038 // If so drop any the type test assume sequences inserted for whole program
1039 // vtables so that codegen doesn't complain.
1040 if (IsThinLTOPostLink)
1041 PB.registerPipelineStartEPCallback(
1042 C: [](ModulePassManager &MPM, OptimizationLevel Level) {
1043 MPM.addPass(Pass: DropTypeTestsPass());
1044 });
1045
1046 // Register callbacks to schedule sanitizer passes at the appropriate part
1047 // of the pipeline.
1048 if (LangOpts.Sanitize.has(K: SanitizerKind::LocalBounds))
1049 PB.registerScalarOptimizerLateEPCallback(C: [this](FunctionPassManager &FPM,
1050 OptimizationLevel Level) {
1051 BoundsCheckingPass::Options Options;
1052 if (CodeGenOpts.SanitizeSkipHotCutoffs[SanitizerKind::SO_LocalBounds] ||
1053 ClSanitizeGuardChecks) {
1054 static_assert(SanitizerKind::SO_LocalBounds <=
1055 std::numeric_limits<
1056 decltype(Options.GuardKind)::value_type>::max(),
1057 "Update type of llvm.allow.ubsan.check to represent "
1058 "SanitizerKind::SO_LocalBounds.");
1059 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1060 }
1061 Options.Merge =
1062 CodeGenOpts.SanitizeMergeHandlers.has(K: SanitizerKind::LocalBounds);
1063 if (!CodeGenOpts.SanitizeTrap.has(K: SanitizerKind::LocalBounds)) {
1064 Options.Rt = {
1065 /*MinRuntime=*/static_cast<bool>(
1066 CodeGenOpts.SanitizeMinimalRuntime),
1067 /*MayReturn=*/
1068 CodeGenOpts.SanitizeRecover.has(K: SanitizerKind::LocalBounds),
1069 /*HandlerPreserveAllRegs=*/
1070 static_cast<bool>(CodeGenOpts.SanitizeHandlerPreserveAllRegs),
1071 };
1072 }
1073 FPM.addPass(Pass: BoundsCheckingPass(Options));
1074 });
1075
1076 if (!IsThinLTOPostLink) {
1077 // Most sanitizers only run during PreLink stage.
1078 addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
1079 addKCFIPass(TargetTriple, LangOpts, PB);
1080 addLowerAllowCheckPass(CodeGenOpts, LangOpts, PB);
1081
1082 PB.registerPipelineStartEPCallback(
1083 C: [&](ModulePassManager &MPM, OptimizationLevel Level) {
1084 if (Level == OptimizationLevel::O0 &&
1085 LangOpts.Sanitize.has(K: SanitizerKind::AllocToken)) {
1086 // With the default O0 pipeline, LibFunc attrs are not inferred,
1087 // so we insert it here because we need it for accurate memory
1088 // allocation function detection with -fsanitize=alloc-token.
1089 // Note: This could also be added to the default O0 pipeline, but
1090 // has a non-trivial effect on generated IR size (attributes).
1091 MPM.addPass(Pass: InferFunctionAttrsPass());
1092 }
1093 });
1094 }
1095
1096 if (std::optional<GCOVOptions> Options =
1097 getGCOVOptions(CodeGenOpts, LangOpts))
1098 PB.registerPipelineStartEPCallback(
1099 C: [this, Options](ModulePassManager &MPM, OptimizationLevel Level) {
1100 MPM.addPass(
1101 Pass: GCOVProfilerPass(*Options, CI.getVirtualFileSystemPtr()));
1102 });
1103 if (std::optional<InstrProfOptions> Options =
1104 getInstrProfOptions(CodeGenOpts, LangOpts))
1105 PB.registerPipelineStartEPCallback(
1106 C: [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1107 MPM.addPass(Pass: InstrProfilingLoweringPass(*Options, false));
1108 });
1109
1110 // TODO: Consider passing the MemoryProfileOutput to the pass builder via
1111 // the PGOOptions, and set this up there.
1112 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1113 PB.registerOptimizerLastEPCallback(C: [](ModulePassManager &MPM,
1114 OptimizationLevel Level,
1115 ThinOrFullLTOPhase) {
1116 MPM.addPass(Pass: createModuleToFunctionPassAdaptor(Pass: MemProfilerPass()));
1117 MPM.addPass(Pass: ModuleMemProfilerPass());
1118 });
1119 }
1120
1121 if (CodeGenOpts.FatLTO) {
1122 MPM.addPass(Pass: PB.buildFatLTODefaultPipeline(
1123 Level, ThinLTO: PrepareForThinLTO,
1124 EmitSummary: PrepareForThinLTO || shouldEmitRegularLTOSummary(),
1125 Verify: CodeGenOpts.VerifyModule));
1126 } else if (PrepareForThinLTO) {
1127 MPM.addPass(Pass: PB.buildThinLTOPreLinkDefaultPipeline(Level));
1128 } else if (PrepareForLTO) {
1129 MPM.addPass(Pass: PB.buildLTOPreLinkDefaultPipeline(Level));
1130 } else {
1131 MPM.addPass(Pass: PB.buildPerModuleDefaultPipeline(Level));
1132 }
1133 }
1134
1135 // Link against bitcodes supplied via the -mlink-builtin-bitcode option
1136 if (CodeGenOpts.LinkBitcodePostopt) {
1137 MPM.addPass(Pass: LinkInModulesPass(BC));
1138 MPM.addPass(Pass: AssignGUIDPass());
1139 }
1140
1141 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1142 LangOpts.HIPStdParInterposeAlloc)
1143 MPM.addPass(Pass: HipStdParAllocationInterpositionPass());
1144
1145 // Add a verifier pass if requested. We don't have to do this if the action
1146 // requires code generation because there will already be a verifier pass in
1147 // the code-generation pipeline.
1148 // Since we already added a verifier pass above, this
1149 // might even not run the analysis, if previous passes caused no changes.
1150 if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
1151 MPM.addPass(Pass: VerifierPass());
1152
1153 if (Action == Backend_EmitBC || Action == Backend_EmitLL ||
1154 CodeGenOpts.FatLTO) {
1155 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1156 if (!TheModule->getModuleFlag(Key: "EnableSplitLTOUnit"))
1157 TheModule->addModuleFlag(Behavior: llvm::Module::Error, Key: "EnableSplitLTOUnit",
1158 Val: CodeGenOpts.EnableSplitLTOUnit);
1159 if (Action == Backend_EmitBC) {
1160 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1161 ThinLinkOS = openOutputFile(Path: CodeGenOpts.ThinLinkBitcodeFile);
1162 if (!ThinLinkOS)
1163 return;
1164 }
1165 MPM.addPass(Pass: ThinLTOBitcodeWriterPass(
1166 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
1167 } else if (Action == Backend_EmitLL) {
1168 MPM.addPass(Pass: PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1169 /*EmitLTOSummary=*/true));
1170 }
1171 } else {
1172 // Emit a module summary by default for Regular LTO except for ld64
1173 // targets
1174 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1175 if (EmitLTOSummary) {
1176 if (!TheModule->getModuleFlag(Key: "ThinLTO") && !CodeGenOpts.UnifiedLTO)
1177 TheModule->addModuleFlag(Behavior: llvm::Module::Error, Key: "ThinLTO", Val: uint32_t(0));
1178 if (!TheModule->getModuleFlag(Key: "EnableSplitLTOUnit"))
1179 TheModule->addModuleFlag(Behavior: llvm::Module::Error, Key: "EnableSplitLTOUnit",
1180 Val: uint32_t(1));
1181 }
1182 if (Action == Backend_EmitBC) {
1183 MPM.addPass(Pass: BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1184 EmitLTOSummary));
1185 } else if (Action == Backend_EmitLL) {
1186 MPM.addPass(Pass: PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1187 EmitLTOSummary));
1188 }
1189 }
1190
1191 if (shouldEmitUnifiedLTOModueFlag() &&
1192 !TheModule->getModuleFlag(Key: "UnifiedLTO"))
1193 TheModule->addModuleFlag(Behavior: llvm::Module::Error, Key: "UnifiedLTO", Val: uint32_t(1));
1194 }
1195
1196 // FIXME: This should eventually be replaced by a first-class driver option.
1197 // This should be done for both clang and flang simultaneously.
1198 // Print a textual, '-passes=' compatible, representation of pipeline if
1199 // requested.
1200 if (PrintPipelinePasses) {
1201 MPM.printPipeline(OS&: outs(), MapClassName2PassName: [&PIC](StringRef ClassName) {
1202 auto PassName = PIC.getPassNameForClassName(ClassName);
1203 return PassName.empty() ? ClassName : PassName;
1204 });
1205 outs() << "\n";
1206 return;
1207 }
1208
1209 // Now that we have all of the passes ready, run them.
1210 {
1211 PrettyStackTraceString CrashInfo("Optimizer");
1212 llvm::TimeTraceScope TimeScope("Optimizer");
1213 Timer timer;
1214 if (CI.getCodeGenOpts().TimePasses) {
1215 timer.init(TimerName: "optimizer", TimerDescription: "Optimizer", tg&: CI.getTimerGroup());
1216 CI.getFrontendTimer().yieldTo(timer);
1217 }
1218 MPM.run(IR&: *TheModule, AM&: MAM);
1219 if (CI.getCodeGenOpts().TimePasses)
1220 timer.yieldTo(CI.getFrontendTimer());
1221 }
1222}
1223
1224void EmitAssemblyHelper::RunCodegenPipeline(
1225 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1226 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1227 if (!actionRequiresCodeGen(Action))
1228 return;
1229
1230 // Normal mode, emit a .s or .o file by running the code generator. Note,
1231 // this also adds codegenerator level optimization passes.
1232 CodeGenFileType CGFT = getCodeGenFileType(Action);
1233
1234 // Invoke pre-codegen callback from plugin, which might want to take over the
1235 // entire code generation itself.
1236 for (const std::unique_ptr<llvm::PassPlugin> &Plugin : CI.getPassPlugins()) {
1237 if (Plugin->invokePreCodeGenCallback(M&: *TheModule, TM&: *TM, CGFT, OS&: *OS))
1238 return;
1239 }
1240
1241 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1242 DwoOS = openOutputFile(Path: CodeGenOpts.SplitDwarfOutput);
1243 if (!DwoOS)
1244 return;
1245 }
1246
1247 if (CodeGenOpts.getEnableNewPMCodeGen() ==
1248 CodeGenOptions::NewPMEnablementLevel::ForceEnable ||
1249 (CodeGenOpts.getEnableNewPMCodeGen() ==
1250 CodeGenOptions::NewPMEnablementLevel::Auto &&
1251 TM->shouldDefaultToNewPM())) {
1252 RunCodegenPipelineNewPM(Action, OS, DwoOS, CGFT);
1253 } else {
1254 RunCodegenPipelineLegacy(Action, OS, DwoOS, CGFT);
1255 }
1256}
1257
1258void EmitAssemblyHelper::RunCodegenPipelineLegacy(
1259 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1260 std::unique_ptr<llvm::ToolOutputFile> &DwoOS, CodeGenFileType CGFT) {
1261 // We still use the legacy PM to run the codegen pipeline since the new PM
1262 // does not work with the codegen pipeline.
1263 // FIXME: make the new PM work with the codegen pipeline.
1264 legacy::PassManager CodeGenPasses;
1265
1266 CodeGenPasses.add(
1267 P: createTargetTransformInfoWrapperPass(TIRA: getTargetIRAnalysis()));
1268 // Add LibraryInfo.
1269 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1270 llvm::driver::createTLII(TargetTriple, Veclib: CodeGenOpts.getVecLib()));
1271 CodeGenPasses.add(P: new TargetLibraryInfoWrapperPass(*TLII));
1272
1273 const llvm::TargetOptions &Options = TM->Options;
1274 CodeGenPasses.add(
1275 P: new RuntimeLibraryInfoWrapper(Options.ExceptionModel, Options.EABIVersion,
1276 Options.MCOptions.ABIName, Options.VecLib));
1277
1278 if (TM->addPassesToEmitFile(CodeGenPasses, *OS,
1279 DwoOS ? &DwoOS->os() : nullptr, CGFT,
1280 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
1281 Diags.Report(DiagID: diag::err_fe_unable_to_interface_with_target);
1282 return;
1283 }
1284
1285 // If -print-pipeline-passes is requested, don't run the legacy pass manager.
1286 // FIXME: when codegen is switched to use the new pass manager, it should also
1287 // emit pass names here.
1288 if (PrintPipelinePasses) {
1289 return;
1290 }
1291
1292 TimeCodegenPasses(RunPasses: [&] { CodeGenPasses.run(M&: *TheModule); });
1293}
1294
1295void EmitAssemblyHelper::RunCodegenPipelineNewPM(
1296 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1297 std::unique_ptr<llvm::ToolOutputFile> &DwoOS, CodeGenFileType CGFT) {
1298 ModulePassManager MPM;
1299 MachineFunctionAnalysisManager MFAM;
1300 LoopAnalysisManager LAM;
1301 FunctionAnalysisManager FAM;
1302 CGSCCAnalysisManager CGAM;
1303 ModuleAnalysisManager MAM;
1304 CGPassBuilderOption Opt = getCGPassBuilderOption();
1305 Opt.DisableVerify = !CodeGenOpts.VerifyModule;
1306 MachineModuleInfo MMI(TM.get());
1307 PassInstrumentationCallbacks PIC;
1308 PipelineTuningOptions PTOptions;
1309 TargetMachine *TMPointer = TM.get();
1310 PassBuilder PB(TMPointer, PTOptions, std::nullopt, &PIC,
1311 CI.getVirtualFileSystemPtr());
1312 PB.registerModuleAnalyses(MAM);
1313 PB.registerCGSCCAnalyses(CGAM);
1314 PB.registerFunctionAnalyses(FAM);
1315 PB.registerLoopAnalyses(LAM);
1316 PB.registerMachineFunctionAnalyses(MFAM);
1317 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM, MFAM: &MFAM);
1318
1319 MAM.registerPass(PassBuilder: [&] { return MachineModuleAnalysis(MMI); });
1320
1321 Error BuildPipelineError =
1322 TM->buildCodeGenPipeline(MPM, MAM, Out&: *OS, DwoOut: DwoOS ? &DwoOS->os() : nullptr,
1323 FileType: CGFT, Opt, Ctx&: MMI.getContext(), PIC: &PIC);
1324 if (BuildPipelineError) {
1325 Diags.Report(DiagID: diag::err_fe_unable_to_interface_with_target);
1326 return;
1327 }
1328
1329 TimeCodegenPasses(RunPasses: [&] { MPM.run(IR&: *TheModule, AM&: MAM); });
1330}
1331
1332void EmitAssemblyHelper::TimeCodegenPasses(
1333 llvm::function_ref<void()> RunPasses) {
1334 PrettyStackTraceString CrashInfo("Code generation");
1335 llvm::TimeTraceScope TimeScope("CodeGenPasses");
1336 Timer timer;
1337 if (CI.getCodeGenOpts().TimePasses) {
1338 timer.init(TimerName: "codegen", TimerDescription: "Machine code generation", tg&: CI.getTimerGroup());
1339 CI.getFrontendTimer().yieldTo(timer);
1340 }
1341 RunPasses();
1342 if (CI.getCodeGenOpts().TimePasses)
1343 timer.yieldTo(CI.getFrontendTimer());
1344}
1345
1346void EmitAssemblyHelper::emitAssembly(BackendAction Action,
1347 std::unique_ptr<raw_pwrite_stream> OS,
1348 BackendConsumer *BC) {
1349 setCommandLineOpts(CodeGenOpts, VFS&: CI.getVirtualFileSystem());
1350
1351 bool RequiresCodeGen = actionRequiresCodeGen(Action);
1352 CreateTargetMachine(MustCreateTM: RequiresCodeGen);
1353
1354 if (RequiresCodeGen && !TM)
1355 return;
1356 if (TM)
1357 TheModule->setDataLayout(TM->createDataLayout());
1358
1359 // Before executing passes, print the final values of the LLVM options.
1360 cl::PrintOptionValues();
1361
1362 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1363 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1364 RunCodegenPipeline(Action, OS, DwoOS);
1365
1366 if (ThinLinkOS)
1367 ThinLinkOS->keep();
1368 if (DwoOS)
1369 DwoOS->keep();
1370}
1371
1372static void
1373runThinLTOBackend(CompilerInstance &CI, ModuleSummaryIndex *CombinedIndex,
1374 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1375 std::string SampleProfile, std::string ProfileRemapping,
1376 BackendAction Action) {
1377 DiagnosticsEngine &Diags = CI.getDiagnostics();
1378 const auto &CGOpts = CI.getCodeGenOpts();
1379 const auto &TOpts = CI.getTargetOpts();
1380 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1381 ModuleToDefinedGVSummaries;
1382 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1383
1384 setCommandLineOpts(CodeGenOpts: CGOpts, VFS&: CI.getVirtualFileSystem());
1385
1386 // We can simply import the values mentioned in the combined index, since
1387 // we should only invoke this using the individual indexes written out
1388 // via a WriteIndexesThinBackend.
1389 FunctionImporter::ImportIDTable ImportIDs;
1390 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1391 if (!lto::initImportList(M: *M, CombinedIndex: *CombinedIndex, ImportList))
1392 return;
1393
1394 auto AddStream = [&](size_t Task, const Twine &ModuleName) {
1395 return std::make_unique<CachedFileStream>(args: std::move(OS),
1396 args: CGOpts.ObjectFilenameForDebug);
1397 };
1398 lto::Config Conf;
1399 if (CGOpts.SaveTempsFilePrefix != "") {
1400 if (Error E = Conf.addSaveTemps(OutputFileName: CGOpts.SaveTempsFilePrefix + ".",
1401 /* UseInputModulePath */ false)) {
1402 handleAllErrors(E: std::move(E), Handlers: [&](ErrorInfoBase &EIB) {
1403 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1404 << '\n';
1405 });
1406 }
1407 }
1408 Conf.CPU = TOpts.CPU;
1409 Conf.CodeModel = getCodeModel(CodeGenOpts: CGOpts);
1410 Conf.MAttrs = TOpts.Features;
1411 Conf.RelocModel = CGOpts.RelocationModel;
1412 std::optional<CodeGenOptLevel> OptLevelOrNone =
1413 CodeGenOpt::getLevel(OL: CGOpts.OptimizationLevel);
1414 assert(OptLevelOrNone && "Invalid optimization level!");
1415 Conf.CGOptLevel = *OptLevelOrNone;
1416 Conf.OptLevel = CGOpts.OptimizationLevel;
1417 initTargetOptions(CI, Diags, Options&: Conf.Options);
1418 Conf.SampleProfile = std::move(SampleProfile);
1419 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1420 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1421 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1422 // For historical reasons, loop interleaving is set to mirror setting for loop
1423 // unrolling.
1424 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1425 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1426 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1427 // Only enable CGProfilePass when using integrated assembler, since
1428 // non-integrated assemblers don't recognize .cgprofile section.
1429 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1430
1431 // Context sensitive profile.
1432 if (CGOpts.hasProfileCSIRInstr()) {
1433 Conf.RunCSIRInstr = true;
1434 Conf.CSIRProfile = getProfileGenName(CodeGenOpts: CGOpts);
1435 } else if (CGOpts.hasProfileCSIRUse()) {
1436 Conf.RunCSIRInstr = false;
1437 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1438 }
1439
1440 Conf.ProfileRemapping = std::move(ProfileRemapping);
1441 Conf.DebugPassManager = CGOpts.DebugPassManager;
1442 Conf.VerifyEach = CGOpts.VerifyEach;
1443 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1444 Conf.RemarksFilename = CGOpts.OptRecordFile;
1445 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1446 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1447 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1448 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1449 for (auto &Plugin : CI.getPassPlugins())
1450 Conf.LoadedPassPlugins.push_back(x: Plugin.get());
1451 switch (Action) {
1452 case Backend_EmitNothing:
1453 Conf.PreCodeGenModuleHook = [](size_t Task, const llvm::Module &Mod) {
1454 return false;
1455 };
1456 break;
1457 case Backend_EmitLL:
1458 Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
1459 M->print(OS&: *OS, AAW: nullptr, ShouldPreserveUseListOrder: CGOpts.EmitLLVMUseLists);
1460 return false;
1461 };
1462 break;
1463 case Backend_EmitBC:
1464 Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
1465 WriteBitcodeToFile(M: *M, Out&: *OS, ShouldPreserveUseListOrder: CGOpts.EmitLLVMUseLists);
1466 return false;
1467 };
1468 break;
1469 default:
1470 Conf.CGFileType = getCodeGenFileType(Action);
1471 break;
1472 }
1473
1474 // FIXME: Both ExecuteAction and thinBackend set up optimization remarks for
1475 // the same context.
1476 // FIXME: This does not yet set the list of bitcode libfuncs that it isn't
1477 // safe to call. This precludes bitcode libc in distributed ThinLTO.
1478 finalizeLLVMOptimizationRemarks(Context&: M->getContext());
1479 if (Error E = thinBackend(
1480 C: Conf, Task: -1, AddStream, M&: *M, CombinedIndex: *CombinedIndex, ImportList,
1481 DefinedGlobals: ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1482 /*ModuleMap=*/nullptr, CodeGenOnly: Conf.CodeGenOnly, /*BitcodeLibFuncs=*/{},
1483 /*IRAddStream=*/nullptr, CmdArgs: CGOpts.CmdArgs)) {
1484 handleAllErrors(E: std::move(E), Handlers: [&](ErrorInfoBase &EIB) {
1485 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1486 });
1487 }
1488}
1489
1490static void createAndEmbedModuleForDynamicDebugging(
1491 CompilerInstance &CI, CodeGenOptions &CGOpts, llvm::Module *M,
1492 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, BackendConsumer *BC) {
1493 /// Helper for saving the module(s) at various dyndbg stages.
1494 auto SaveModule = [&](StringRef Name, llvm::Module &M) {
1495 if (CGOpts.SaveDynDbgTempsFilePrefix == "")
1496 return;
1497 std::error_code EC;
1498 std::string Path =
1499 Twine(CGOpts.SaveDynDbgTempsFilePrefix + "." + Name + ".ll").str();
1500 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
1501 if (EC) {
1502 // Copy -save-temps behaviour: this is a debugging option so we simply
1503 // exit if there's an issue.
1504 errs() << "failed to open " << Path << ": " << EC.message() << '\n';
1505 errs().flush();
1506 exit(status: 1);
1507 }
1508 M.print(OS, AAW: nullptr);
1509 };
1510
1511 // Compute a hash suffix for promoting static globals (once per TU).
1512 std::string PromotionSuffix;
1513 {
1514 // LLVM's hash/hash_combine is not guaranteed to be stable.
1515 MD5 Hash;
1516 // Include args in the hash else preprocessor definitions used to alter
1517 // the same source file compiled twice won't generate unique hashes.
1518 Hash.update(Data: CGOpts.CmdArgs);
1519 for (auto *CU : M->debug_compile_units()) {
1520 if (CU->getDirectory().size() > 0)
1521 Hash.update(Str: CU->getDirectory());
1522
1523 Hash.update(Str: CU->getFilename());
1524 }
1525
1526 MD5::MD5Result Result;
1527 Hash.final(Result);
1528 PromotionSuffix = ".dyndbg." + utohexstr(X: Result.low());
1529 }
1530
1531 SaveModule("dyndbg.0.input", *M);
1532 // Modify M as needed and create an "unoptimized" clone.
1533 auto UnoptM = prepareForDynamicDebugging(M, PromotionSuffix);
1534 SaveModule("dyndbg.1.inner", *UnoptM);
1535
1536 if (!CGOpts.DiscardDynamicDebuggingDebugModule) {
1537 CodeGenOptions UnoptOpts = CGOpts;
1538 UnoptOpts.OptimizationLevel = 0;
1539 UnoptOpts.OptimizeSize = 0;
1540 EmitAssemblyHelper AsmHelper(CI, UnoptOpts, UnoptM.get(), VFS);
1541
1542 // Create a buffer and ostream for the inner ELF.
1543 SmallVector<char, 0> UnoptBuf;
1544 std::unique_ptr<llvm::raw_pwrite_stream> UnoptOS =
1545 std::make_unique<llvm::raw_svector_ostream>(args&: UnoptBuf);
1546
1547 // Always run the full codegen pipeline (Backend_EmitObj). This causes
1548 // assertion failures if there's no registered backend which is why we
1549 // disable the feature if that's the case (see
1550 // warn_dyndbg_unable_to_create_target above).
1551 AsmHelper.emitAssembly(Action: Backend_EmitObj, OS: std::move(UnoptOS), BC);
1552 assert(!UnoptBuf.empty() && "Expected emitAssembly to fill UnoptBuf");
1553
1554 // Inject the inner ELF into the outer module.
1555 StringRef SR(UnoptBuf.data(), UnoptBuf.size());
1556 std::unique_ptr<MemoryBuffer> Buf =
1557 MemoryBuffer::getMemBuffer(InputData: SR, BufferName: "", RequiresNullTerminator: false);
1558
1559 GlobalVariable *EmbeddedGV =
1560 llvm::embedBufferInModule(M&: *M, Buf: *Buf, SectionName: ".debug_llvm_dyndbg", Alignment: Align(8),
1561 /*SectionExclude*/ false);
1562 // Add ELF section properties metadata.
1563 auto &C = M->getContext();
1564 auto getU32Metadata = [&C](unsigned Val) {
1565 return ConstantAsMetadata::get(C: ConstantInt::get(Context&: C, V: APInt(32, Val)));
1566 };
1567 EmbeddedGV->addMetadata(
1568 KindID: LLVMContext::MD_elf_section_properties,
1569 MD&: *MDTuple::get(Context&: C, MDs: {/*sh_type*/ getU32Metadata(ELF::SHT_LLVM_DYNDBG_ELF),
1570 /*sh_entsize*/ getU32Metadata(0)}));
1571 }
1572 SaveModule("dyndbg.2.outer", *M);
1573}
1574
1575void clang::emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts,
1576 StringRef TDesc, llvm::Module *M,
1577 BackendAction Action,
1578 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
1579 std::unique_ptr<raw_pwrite_stream> OS,
1580 BackendConsumer *BC) {
1581 llvm::TimeTraceScope TimeScope("Backend");
1582 DiagnosticsEngine &Diags = CI.getDiagnostics();
1583
1584 std::unique_ptr<llvm::Module> EmptyModule;
1585 if (!CGOpts.ThinLTOIndexFile.empty()) {
1586 // FIXME(sandboxing): Figure out how to support distributed indexing.
1587 auto BypassSandbox = sys::sandbox::scopedDisable();
1588 // If we are performing a ThinLTO importing compile, load the function index
1589 // into memory and pass it into runThinLTOBackend, which will run the
1590 // function importer and invoke LTO passes.
1591 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1592 if (Error E = llvm::getModuleSummaryIndexForFile(
1593 Path: CGOpts.ThinLTOIndexFile,
1594 /*IgnoreEmptyThinLTOIndexFile*/ true)
1595 .moveInto(Value&: CombinedIndex)) {
1596 logAllUnhandledErrors(E: std::move(E), OS&: errs(),
1597 ErrorBanner: "Error loading index file '" +
1598 CGOpts.ThinLTOIndexFile + "': ");
1599 return;
1600 }
1601
1602 // A null CombinedIndex means we should skip ThinLTO compilation
1603 // (LLVM will optionally ignore empty index files, returning null instead
1604 // of an error).
1605 if (CombinedIndex) {
1606 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1607 runThinLTOBackend(CI, CombinedIndex: CombinedIndex.get(), M, OS: std::move(OS),
1608 SampleProfile: CGOpts.SampleProfileFile, ProfileRemapping: CGOpts.ProfileRemappingFile,
1609 Action);
1610 return;
1611 }
1612 // Distributed indexing detected that nothing from the module is needed
1613 // for the final linking. So we can skip the compilation. We sill need to
1614 // output an empty object file to make sure that a linker does not fail
1615 // trying to read it. Also for some features, like CFI, we must skip
1616 // the compilation as CombinedIndex does not contain all required
1617 // information.
1618 EmptyModule = std::make_unique<llvm::Module>(args: "empty", args&: M->getContext());
1619 EmptyModule->setTargetTriple(M->getTargetTriple());
1620 M = EmptyModule.get();
1621 }
1622 }
1623
1624 bool EnableDynamicDebugging = CGOpts.DynamicDebugging;
1625 if (EnableDynamicDebugging) {
1626 // Disable dyndbg if the target isn't available as we're compiling to the
1627 // inner module (unless we're discarding it for debugging/testing).
1628 std::string Error;
1629 const llvm::Target *TheTarget =
1630 TargetRegistry::lookupTarget(TheTriple: M->getTargetTriple(), Error);
1631 if (!TheTarget && !CGOpts.DiscardDynamicDebuggingDebugModule) {
1632 Diags.Report(DiagID: diag::warn_dyndbg_unable_to_create_target) << Error;
1633 EnableDynamicDebugging = false;
1634 }
1635
1636 // Instrumentation causes issues (parts of LLVM expect certain globals to
1637 // have initializers). Intrinsics may already have been added to IR by now,
1638 // so we can't just turn it off for the inner module (we'd have to strip
1639 // them out / not clone them). TODO: Support instrumentation.
1640 if (CGOpts.getProfileInstr() != driver::ProfileInstrKind::ProfileNone) {
1641 Diags.Report(DiagID: diag::err_dyndbg_no_instrumentation);
1642 EnableDynamicDebugging = false;
1643 }
1644 }
1645 if (EnableDynamicDebugging)
1646 createAndEmbedModuleForDynamicDebugging(CI, CGOpts, M, VFS, BC);
1647
1648 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1649 AsmHelper.emitAssembly(Action, OS: std::move(OS), BC);
1650
1651 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1652 // DataLayout.
1653 if (AsmHelper.TM) {
1654 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1655 if (DLDesc != TDesc) {
1656 Diags.Report(DiagID: diag::err_data_layout_mismatch) << DLDesc << TDesc;
1657 }
1658 }
1659}
1660
1661// With -fembed-bitcode, save a copy of the llvm IR as data in the
1662// __LLVM,__bitcode section.
1663void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1664 llvm::MemoryBufferRef Buf) {
1665 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1666 return;
1667 llvm::embedBitcodeInModule(
1668 M&: *M, Buf, EmbedBitcode: CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1669 EmbedCmdline: CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1670 CmdArgs: CGOpts.CmdArgs);
1671}
1672
1673void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1674 llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags) {
1675 if (CGOpts.OffloadObjects.empty())
1676 return;
1677
1678 for (StringRef OffloadObject : CGOpts.OffloadObjects) {
1679 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1680 VFS.getBufferForFile(Name: OffloadObject);
1681 if (ObjectOrErr.getError()) {
1682 Diags.Report(DiagID: diag::err_failed_to_open_for_embedding) << OffloadObject;
1683 return;
1684 }
1685
1686 llvm::embedBufferInModule(M&: *M, Buf: **ObjectOrErr, SectionName: ".llvm.offloading",
1687 Alignment: Align(object::OffloadBinary::getAlignment()));
1688 }
1689}
1690