1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "clang/CodeGen/BackendUtil.h"
10 #include "clang/Basic/CodeGenOptions.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/FrontendDiagnostic.h"
15 #include "clang/Frontend/Utils.h"
16 #include "clang/Lex/HeaderSearchOptions.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/Bitcode/BitcodeWriter.h"
25 #include "llvm/Bitcode/BitcodeWriterPass.h"
26 #include "llvm/CodeGen/RegAllocRegistry.h"
27 #include "llvm/CodeGen/SchedulerRegistry.h"
28 #include "llvm/CodeGen/TargetSubtargetInfo.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSummaryIndex.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/LTO/LTOBackend.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/SubtargetFeature.h"
38 #include "llvm/Passes/PassBuilder.h"
39 #include "llvm/Passes/PassPlugin.h"
40 #include "llvm/Passes/StandardInstrumentations.h"
41 #include "llvm/Support/BuryPointer.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/PrettyStackTrace.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TimeProfiler.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Transforms/Coroutines.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/AlwaysInliner.h"
54 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
55 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
56 #include "llvm/Transforms/InstCombine/InstCombine.h"
57 #include "llvm/Transforms/Instrumentation.h"
58 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
59 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
60 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
61 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
62 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
63 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
64 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
65 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
66 #include "llvm/Transforms/ObjCARC.h"
67 #include "llvm/Transforms/Scalar.h"
68 #include "llvm/Transforms/Scalar/GVN.h"
69 #include "llvm/Transforms/Utils.h"
70 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
71 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
72 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
73 #include "llvm/Transforms/Utils/SymbolRewriter.h"
75 using namespace clang;
78 #define HANDLE_EXTENSION(Ext) \
79 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
80 #include "llvm/Support/Extension.def"
84 // Default filename used for profile generation.
85 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
87 class EmitAssemblyHelper {
88 DiagnosticsEngine &Diags;
89 const HeaderSearchOptions &HSOpts;
90 const CodeGenOptions &CodeGenOpts;
91 const clang::TargetOptions &TargetOpts;
92 const LangOptions &LangOpts;
95 Timer CodeGenerationTime;
97 std::unique_ptr<raw_pwrite_stream> OS;
99 TargetIRAnalysis getTargetIRAnalysis() const {
101 return TM->getTargetIRAnalysis();
103 return TargetIRAnalysis();
106 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
108 /// Generates the TargetMachine.
109 /// Leaves TM unchanged if it is unable to create the target machine.
110 /// Some of our clang tests specify triples which are not built
111 /// into clang. This is okay because these tests check the generated
112 /// IR, and they require DataLayout which depends on the triple.
113 /// In this case, we allow this method to fail and not report an error.
114 /// When MustCreateTM is used, we print an error if we are unable to load
115 /// the requested target.
116 void CreateTargetMachine(bool MustCreateTM);
118 /// Add passes necessary to emit assembly or LLVM IR.
120 /// \return True on success.
121 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
122 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
124 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
126 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
127 llvm::sys::fs::OF_None);
129 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
136 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
137 const HeaderSearchOptions &HeaderSearchOpts,
138 const CodeGenOptions &CGOpts,
139 const clang::TargetOptions &TOpts,
140 const LangOptions &LOpts, Module *M)
141 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
142 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
143 CodeGenerationTime("codegen", "Code Generation Time") {}
145 ~EmitAssemblyHelper() {
146 if (CodeGenOpts.DisableFree)
147 BuryPointer(std::move(TM));
150 std::unique_ptr<TargetMachine> TM;
152 void EmitAssembly(BackendAction Action,
153 std::unique_ptr<raw_pwrite_stream> OS);
155 void EmitAssemblyWithNewPassManager(BackendAction Action,
156 std::unique_ptr<raw_pwrite_stream> OS);
159 // We need this wrapper to access LangOpts and CGOpts from extension functions
160 // that we add to the PassManagerBuilder.
161 class PassManagerBuilderWrapper : public PassManagerBuilder {
163 PassManagerBuilderWrapper(const Triple &TargetTriple,
164 const CodeGenOptions &CGOpts,
165 const LangOptions &LangOpts)
166 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
167 LangOpts(LangOpts) {}
168 const Triple &getTargetTriple() const { return TargetTriple; }
169 const CodeGenOptions &getCGOpts() const { return CGOpts; }
170 const LangOptions &getLangOpts() const { return LangOpts; }
173 const Triple &TargetTriple;
174 const CodeGenOptions &CGOpts;
175 const LangOptions &LangOpts;
179 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
180 if (Builder.OptLevel > 0)
181 PM.add(createObjCARCAPElimPass());
184 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
185 if (Builder.OptLevel > 0)
186 PM.add(createObjCARCExpandPass());
189 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
190 if (Builder.OptLevel > 0)
191 PM.add(createObjCARCOptPass());
194 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
195 legacy::PassManagerBase &PM) {
196 PM.add(createAddDiscriminatorsPass());
199 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
200 legacy::PassManagerBase &PM) {
201 PM.add(createBoundsCheckingLegacyPass());
204 static SanitizerCoverageOptions
205 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
206 SanitizerCoverageOptions Opts;
208 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
209 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
210 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
211 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
212 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
213 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
214 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
215 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
216 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
217 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
218 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
219 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
220 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
224 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
225 legacy::PassManagerBase &PM) {
226 const PassManagerBuilderWrapper &BuilderWrapper =
227 static_cast<const PassManagerBuilderWrapper &>(Builder);
228 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
229 auto Opts = getSancovOptsFromCGOpts(CGOpts);
230 PM.add(createModuleSanitizerCoverageLegacyPassPass(Opts));
233 // Check if ASan should use GC-friendly instrumentation for globals.
234 // First of all, there is no point if -fdata-sections is off (expect for MachO,
235 // where this is not a factor). Also, on ELF this feature requires an assembler
236 // extension that only works with -integrated-as at the moment.
237 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
238 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
240 switch (T.getObjectFormat()) {
245 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
247 llvm::report_fatal_error("ASan not implemented for XCOFF.");
249 case Triple::UnknownObjectFormat:
255 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
256 legacy::PassManagerBase &PM) {
257 const PassManagerBuilderWrapper &BuilderWrapper =
258 static_cast<const PassManagerBuilderWrapper&>(Builder);
259 const Triple &T = BuilderWrapper.getTargetTriple();
260 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
261 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
262 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
263 bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
264 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
265 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
267 PM.add(createModuleAddressSanitizerLegacyPassPass(
268 /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
271 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
272 legacy::PassManagerBase &PM) {
273 PM.add(createAddressSanitizerFunctionPass(
274 /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
275 PM.add(createModuleAddressSanitizerLegacyPassPass(
276 /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
277 /*UseOdrIndicator*/ false));
280 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
281 legacy::PassManagerBase &PM) {
282 const PassManagerBuilderWrapper &BuilderWrapper =
283 static_cast<const PassManagerBuilderWrapper &>(Builder);
284 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
285 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
287 createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
290 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
291 legacy::PassManagerBase &PM) {
292 PM.add(createHWAddressSanitizerLegacyPassPass(
293 /*CompileKernel*/ true, /*Recover*/ true));
296 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
297 legacy::PassManagerBase &PM,
298 bool CompileKernel) {
299 const PassManagerBuilderWrapper &BuilderWrapper =
300 static_cast<const PassManagerBuilderWrapper&>(Builder);
301 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
302 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
303 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
304 PM.add(createMemorySanitizerLegacyPassPass(
305 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
307 // MemorySanitizer inserts complex instrumentation that mostly follows
308 // the logic of the original code, but operates on "shadow" values.
309 // It can benefit from re-running some general purpose optimization passes.
310 if (Builder.OptLevel > 0) {
311 PM.add(createEarlyCSEPass());
312 PM.add(createReassociatePass());
313 PM.add(createLICMPass());
314 PM.add(createGVNPass());
315 PM.add(createInstructionCombiningPass());
316 PM.add(createDeadStoreEliminationPass());
320 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
321 legacy::PassManagerBase &PM) {
322 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
325 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
326 legacy::PassManagerBase &PM) {
327 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
330 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
331 legacy::PassManagerBase &PM) {
332 PM.add(createThreadSanitizerLegacyPassPass());
335 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
336 legacy::PassManagerBase &PM) {
337 const PassManagerBuilderWrapper &BuilderWrapper =
338 static_cast<const PassManagerBuilderWrapper&>(Builder);
339 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
340 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
343 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
344 const CodeGenOptions &CodeGenOpts) {
345 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
347 switch (CodeGenOpts.getVecLib()) {
348 case CodeGenOptions::Accelerate:
349 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
351 case CodeGenOptions::MASSV:
352 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
354 case CodeGenOptions::SVML:
355 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
363 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
364 legacy::PassManager *MPM) {
365 llvm::SymbolRewriter::RewriteDescriptorList DL;
367 llvm::SymbolRewriter::RewriteMapParser MapParser;
368 for (const auto &MapFile : Opts.RewriteMapFiles)
369 MapParser.parse(MapFile, &DL);
371 MPM->add(createRewriteSymbolsPass(DL));
374 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
375 switch (CodeGenOpts.OptimizationLevel) {
377 llvm_unreachable("Invalid optimization level!");
379 return CodeGenOpt::None;
381 return CodeGenOpt::Less;
383 return CodeGenOpt::Default; // O2/Os/Oz
385 return CodeGenOpt::Aggressive;
389 static Optional<llvm::CodeModel::Model>
390 getCodeModel(const CodeGenOptions &CodeGenOpts) {
391 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
392 .Case("tiny", llvm::CodeModel::Tiny)
393 .Case("small", llvm::CodeModel::Small)
394 .Case("kernel", llvm::CodeModel::Kernel)
395 .Case("medium", llvm::CodeModel::Medium)
396 .Case("large", llvm::CodeModel::Large)
397 .Case("default", ~1u)
399 assert(CodeModel != ~0u && "invalid code model!");
400 if (CodeModel == ~1u)
402 return static_cast<llvm::CodeModel::Model>(CodeModel);
405 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
406 if (Action == Backend_EmitObj)
407 return CGFT_ObjectFile;
408 else if (Action == Backend_EmitMCNull)
411 assert(Action == Backend_EmitAssembly && "Invalid action!");
412 return CGFT_AssemblyFile;
416 static void initTargetOptions(llvm::TargetOptions &Options,
417 const CodeGenOptions &CodeGenOpts,
418 const clang::TargetOptions &TargetOpts,
419 const LangOptions &LangOpts,
420 const HeaderSearchOptions &HSOpts) {
421 Options.ThreadModel =
422 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
423 .Case("posix", llvm::ThreadModel::POSIX)
424 .Case("single", llvm::ThreadModel::Single);
426 // Set float ABI type.
427 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
428 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
429 "Invalid Floating Point ABI!");
430 Options.FloatABIType =
431 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
432 .Case("soft", llvm::FloatABI::Soft)
433 .Case("softfp", llvm::FloatABI::Soft)
434 .Case("hard", llvm::FloatABI::Hard)
435 .Default(llvm::FloatABI::Default);
437 // Set FP fusion mode.
438 switch (LangOpts.getDefaultFPContractMode()) {
439 case LangOptions::FPC_Off:
440 // Preserve any contraction performed by the front-end. (Strict performs
441 // splitting of the muladd intrinsic in the backend.)
442 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
444 case LangOptions::FPC_On:
445 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
447 case LangOptions::FPC_Fast:
448 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
452 Options.UseInitArray = CodeGenOpts.UseInitArray;
453 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
454 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
455 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
458 Options.EABIVersion = TargetOpts.EABIVersion;
460 if (LangOpts.SjLjExceptions)
461 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
462 if (LangOpts.SEHExceptions)
463 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
464 if (LangOpts.DWARFExceptions)
465 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
466 if (LangOpts.WasmExceptions)
467 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
469 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
470 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
471 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
472 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
473 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
474 Options.FunctionSections = CodeGenOpts.FunctionSections;
475 Options.DataSections = CodeGenOpts.DataSections;
476 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
477 Options.TLSSize = CodeGenOpts.TLSSize;
478 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
479 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
480 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
481 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
482 Options.EmitAddrsig = CodeGenOpts.Addrsig;
483 Options.EnableDebugEntryValues = CodeGenOpts.EnableDebugEntryValues;
484 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
486 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
487 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
488 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
489 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
490 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
491 Options.MCOptions.MCIncrementalLinkerCompatible =
492 CodeGenOpts.IncrementalLinkerCompatible;
493 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
494 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
495 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
496 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
497 Options.MCOptions.ABIName = TargetOpts.ABI;
498 for (const auto &Entry : HSOpts.UserEntries)
499 if (!Entry.IsFramework &&
500 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
501 Entry.Group == frontend::IncludeDirGroup::Angled ||
502 Entry.Group == frontend::IncludeDirGroup::System))
503 Options.MCOptions.IASSearchPaths.push_back(
504 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
506 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
507 if (CodeGenOpts.DisableGCov)
509 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
511 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
512 // LLVM's -default-gcov-version flag is set to something invalid.
514 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
515 Options.EmitData = CodeGenOpts.EmitGcovArcs;
516 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
517 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
518 Options.NoRedZone = CodeGenOpts.DisableRedZone;
519 Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
520 Options.Filter = CodeGenOpts.ProfileFilterFiles;
521 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
522 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
526 static Optional<InstrProfOptions>
527 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
528 const LangOptions &LangOpts) {
529 if (!CodeGenOpts.hasProfileClangInstr())
531 InstrProfOptions Options;
532 Options.NoRedZone = CodeGenOpts.DisableRedZone;
533 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
535 // TODO: Surface the option to emit atomic profile counter increments at
537 Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
541 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
542 legacy::FunctionPassManager &FPM) {
543 // Handle disabling of all LLVM passes, where we want to preserve the
544 // internal module before any optimization.
545 if (CodeGenOpts.DisableLLVMPasses)
548 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
549 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
550 // are inserted before PMBuilder ones - they'd get the default-constructed
551 // TLI with an unknown target otherwise.
552 Triple TargetTriple(TheModule->getTargetTriple());
553 std::unique_ptr<TargetLibraryInfoImpl> TLII(
554 createTLII(TargetTriple, CodeGenOpts));
556 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
558 // At O0 and O1 we only run the always inliner which is more efficient. At
559 // higher optimization levels we run the normal inliner.
560 if (CodeGenOpts.OptimizationLevel <= 1) {
561 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
562 !CodeGenOpts.DisableLifetimeMarkers);
563 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
565 // We do not want to inline hot callsites for SamplePGO module-summary build
566 // because profile annotation will happen again in ThinLTO backend, and we
567 // want the IR of the hot path to match the profile.
568 PMBuilder.Inliner = createFunctionInliningPass(
569 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
570 (!CodeGenOpts.SampleProfileFile.empty() &&
571 CodeGenOpts.PrepareForThinLTO));
574 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
575 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
576 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
577 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
579 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
580 // Loop interleaving in the loop vectorizer has historically been set to be
581 // enabled when loop unrolling is enabled.
582 PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
583 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
584 PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
585 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
586 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
588 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
591 TM->adjustPassManager(PMBuilder);
593 if (CodeGenOpts.DebugInfoForProfiling ||
594 !CodeGenOpts.SampleProfileFile.empty())
595 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
596 addAddDiscriminatorsPass);
598 // In ObjC ARC mode, add the main ARC optimization passes.
599 if (LangOpts.ObjCAutoRefCount) {
600 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
601 addObjCARCExpandPass);
602 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
603 addObjCARCAPElimPass);
604 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
608 if (LangOpts.Coroutines)
609 addCoroutinePassesToExtensionPoints(PMBuilder);
611 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
612 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
613 addBoundsCheckingPass);
614 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
615 addBoundsCheckingPass);
618 if (CodeGenOpts.SanitizeCoverageType ||
619 CodeGenOpts.SanitizeCoverageIndirectCalls ||
620 CodeGenOpts.SanitizeCoverageTraceCmp) {
621 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
622 addSanitizerCoveragePass);
623 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
624 addSanitizerCoveragePass);
627 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
628 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
629 addAddressSanitizerPasses);
630 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
631 addAddressSanitizerPasses);
634 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
635 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
636 addKernelAddressSanitizerPasses);
637 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
638 addKernelAddressSanitizerPasses);
641 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
642 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
643 addHWAddressSanitizerPasses);
644 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
645 addHWAddressSanitizerPasses);
648 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
649 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
650 addKernelHWAddressSanitizerPasses);
651 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
652 addKernelHWAddressSanitizerPasses);
655 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
656 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
657 addMemorySanitizerPass);
658 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
659 addMemorySanitizerPass);
662 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
663 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
664 addKernelMemorySanitizerPass);
665 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
666 addKernelMemorySanitizerPass);
669 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
670 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
671 addThreadSanitizerPass);
672 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
673 addThreadSanitizerPass);
676 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
677 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
678 addDataFlowSanitizerPass);
679 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
680 addDataFlowSanitizerPass);
683 // Set up the per-function pass manager.
684 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
685 if (CodeGenOpts.VerifyModule)
686 FPM.add(createVerifierPass());
688 // Set up the per-module pass manager.
689 if (!CodeGenOpts.RewriteMapFiles.empty())
690 addSymbolRewriterPass(CodeGenOpts, &MPM);
692 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
693 MPM.add(createGCOVProfilerPass(*Options));
694 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
695 MPM.add(createStripSymbolsPass(true));
698 if (Optional<InstrProfOptions> Options =
699 getInstrProfOptions(CodeGenOpts, LangOpts))
700 MPM.add(createInstrProfilingLegacyPass(*Options, false));
702 bool hasIRInstr = false;
703 if (CodeGenOpts.hasProfileIRInstr()) {
704 PMBuilder.EnablePGOInstrGen = true;
707 if (CodeGenOpts.hasProfileCSIRInstr()) {
708 assert(!CodeGenOpts.hasProfileCSIRUse() &&
709 "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
711 assert(!hasIRInstr &&
712 "Cannot have both ProfileGen pass and CSProfileGen pass at the "
714 PMBuilder.EnablePGOCSInstrGen = true;
718 if (!CodeGenOpts.InstrProfileOutput.empty())
719 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
721 PMBuilder.PGOInstrGen = DefaultProfileGenName;
723 if (CodeGenOpts.hasProfileIRUse()) {
724 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
725 PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
728 if (!CodeGenOpts.SampleProfileFile.empty())
729 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
731 PMBuilder.populateFunctionPassManager(FPM);
732 PMBuilder.populateModulePassManager(MPM);
735 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
736 SmallVector<const char *, 16> BackendArgs;
737 BackendArgs.push_back("clang"); // Fake program name.
738 if (!CodeGenOpts.DebugPass.empty()) {
739 BackendArgs.push_back("-debug-pass");
740 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
742 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
743 BackendArgs.push_back("-limit-float-precision");
744 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
746 BackendArgs.push_back(nullptr);
747 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
751 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
752 // Create the TargetMachine for generating code.
754 std::string Triple = TheModule->getTargetTriple();
755 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
758 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
762 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
763 std::string FeaturesStr =
764 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
765 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
766 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
768 llvm::TargetOptions Options;
769 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
770 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
771 Options, RM, CM, OptLevel));
774 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
775 BackendAction Action,
776 raw_pwrite_stream &OS,
777 raw_pwrite_stream *DwoOS) {
779 llvm::Triple TargetTriple(TheModule->getTargetTriple());
780 std::unique_ptr<TargetLibraryInfoImpl> TLII(
781 createTLII(TargetTriple, CodeGenOpts));
782 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
784 // Normal mode, emit a .s or .o file by running the code generator. Note,
785 // this also adds codegenerator level optimization passes.
786 CodeGenFileType CGFT = getCodeGenFileType(Action);
788 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
789 // "codegen" passes so that it isn't run multiple times when there is
790 // inlining happening.
791 if (CodeGenOpts.OptimizationLevel > 0)
792 CodeGenPasses.add(createObjCARCContractPass());
794 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
795 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
796 Diags.Report(diag::err_fe_unable_to_interface_with_target);
803 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
804 std::unique_ptr<raw_pwrite_stream> OS) {
805 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
807 setCommandLineOpts(CodeGenOpts);
809 bool UsesCodeGen = (Action != Backend_EmitNothing &&
810 Action != Backend_EmitBC &&
811 Action != Backend_EmitLL);
812 CreateTargetMachine(UsesCodeGen);
814 if (UsesCodeGen && !TM)
817 TheModule->setDataLayout(TM->createDataLayout());
819 legacy::PassManager PerModulePasses;
821 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
823 legacy::FunctionPassManager PerFunctionPasses(TheModule);
824 PerFunctionPasses.add(
825 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
827 CreatePasses(PerModulePasses, PerFunctionPasses);
829 legacy::PassManager CodeGenPasses;
831 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
833 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
836 case Backend_EmitNothing:
840 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
841 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
842 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
846 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
847 CodeGenOpts.EnableSplitLTOUnit);
848 PerModulePasses.add(createWriteThinLTOBitcodePass(
849 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
851 // Emit a module summary by default for Regular LTO except for ld64
853 bool EmitLTOSummary =
854 (CodeGenOpts.PrepareForLTO &&
855 !CodeGenOpts.DisableLLVMPasses &&
856 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
857 llvm::Triple::Apple);
858 if (EmitLTOSummary) {
859 if (!TheModule->getModuleFlag("ThinLTO"))
860 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
861 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
865 PerModulePasses.add(createBitcodeWriterPass(
866 *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
872 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
876 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
877 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
881 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
882 DwoOS ? &DwoOS->os() : nullptr))
886 // Before executing passes, print the final values of the LLVM options.
887 cl::PrintOptionValues();
889 // Run passes. For now we do all passes at once, but eventually we
890 // would like to have the option of streaming code generation.
893 PrettyStackTraceString CrashInfo("Per-function optimization");
894 llvm::TimeTraceScope TimeScope("PerFunctionPasses");
896 PerFunctionPasses.doInitialization();
897 for (Function &F : *TheModule)
898 if (!F.isDeclaration())
899 PerFunctionPasses.run(F);
900 PerFunctionPasses.doFinalization();
904 PrettyStackTraceString CrashInfo("Per-module optimization passes");
905 llvm::TimeTraceScope TimeScope("PerModulePasses");
906 PerModulePasses.run(*TheModule);
910 PrettyStackTraceString CrashInfo("Code generation");
911 llvm::TimeTraceScope TimeScope("CodeGenPasses");
912 CodeGenPasses.run(*TheModule);
921 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
922 switch (Opts.OptimizationLevel) {
924 llvm_unreachable("Invalid optimization level!");
927 return PassBuilder::O1;
930 switch (Opts.OptimizeSize) {
932 llvm_unreachable("Invalid optimization level for size!");
935 return PassBuilder::O2;
938 return PassBuilder::Os;
941 return PassBuilder::Oz;
945 return PassBuilder::O3;
949 static void addSanitizersAtO0(ModulePassManager &MPM,
950 const Triple &TargetTriple,
951 const LangOptions &LangOpts,
952 const CodeGenOptions &CodeGenOpts) {
953 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
954 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
955 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
956 MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
957 CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
958 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
960 ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
961 CodeGenOpts.SanitizeAddressUseOdrIndicator));
964 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
965 ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
968 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
969 ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
972 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
973 MPM.addPass(MemorySanitizerPass({}));
974 MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({})));
977 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
978 MPM.addPass(createModuleToFunctionPassAdaptor(
979 MemorySanitizerPass({0, false, /*Kernel=*/true})));
982 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
983 MPM.addPass(ThreadSanitizerPass());
984 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
988 /// A clean version of `EmitAssembly` that uses the new pass manager.
990 /// Not all features are currently supported in this system, but where
991 /// necessary it falls back to the legacy pass manager to at least provide
992 /// basic functionality.
994 /// This API is planned to have its functionality finished and then to replace
995 /// `EmitAssembly` at some point in the future when the default switches.
996 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
997 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
998 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
999 setCommandLineOpts(CodeGenOpts);
1001 bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1002 Action != Backend_EmitBC &&
1003 Action != Backend_EmitLL);
1004 CreateTargetMachine(RequiresCodeGen);
1006 if (RequiresCodeGen && !TM)
1009 TheModule->setDataLayout(TM->createDataLayout());
1011 Optional<PGOOptions> PGOOpt;
1013 if (CodeGenOpts.hasProfileIRInstr())
1014 // -fprofile-generate.
1015 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1016 ? DefaultProfileGenName
1017 : CodeGenOpts.InstrProfileOutput,
1018 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1019 CodeGenOpts.DebugInfoForProfiling);
1020 else if (CodeGenOpts.hasProfileIRUse()) {
1022 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1023 : PGOOptions::NoCSAction;
1024 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1025 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1026 CSAction, CodeGenOpts.DebugInfoForProfiling);
1027 } else if (!CodeGenOpts.SampleProfileFile.empty())
1028 // -fprofile-sample-use
1030 PGOOptions(CodeGenOpts.SampleProfileFile, "",
1031 CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1032 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
1033 else if (CodeGenOpts.DebugInfoForProfiling)
1034 // -fdebug-info-for-profiling
1035 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1036 PGOOptions::NoCSAction, true);
1038 // Check to see if we want to generate a CS profile.
1039 if (CodeGenOpts.hasProfileCSIRInstr()) {
1040 assert(!CodeGenOpts.hasProfileCSIRUse() &&
1041 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1043 if (PGOOpt.hasValue()) {
1044 assert(PGOOpt->Action != PGOOptions::IRInstr &&
1045 PGOOpt->Action != PGOOptions::SampleUse &&
1046 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1048 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1049 ? DefaultProfileGenName
1050 : CodeGenOpts.InstrProfileOutput;
1051 PGOOpt->CSAction = PGOOptions::CSIRInstr;
1053 PGOOpt = PGOOptions("",
1054 CodeGenOpts.InstrProfileOutput.empty()
1055 ? DefaultProfileGenName
1056 : CodeGenOpts.InstrProfileOutput,
1057 "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1058 CodeGenOpts.DebugInfoForProfiling);
1061 PipelineTuningOptions PTO;
1062 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1063 // For historical reasons, loop interleaving is set to mirror setting for loop
1065 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1066 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1067 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1069 PassInstrumentationCallbacks PIC;
1070 StandardInstrumentations SI;
1071 SI.registerCallbacks(PIC);
1072 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1074 // Attempt to load pass plugins and register their callbacks with PB.
1075 for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1076 auto PassPlugin = PassPlugin::Load(PluginFN);
1078 PassPlugin->registerPassBuilderCallbacks(PB);
1080 Diags.Report(diag::err_fe_unable_to_load_plugin)
1081 << PluginFN << toString(PassPlugin.takeError());
1084 #define HANDLE_EXTENSION(Ext) \
1085 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1086 #include "llvm/Support/Extension.def"
1088 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1089 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1090 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1091 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1093 // Register the AA manager first so that our version is the one used.
1094 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1096 // Register the target library analysis directly and give it a customized
1098 Triple TargetTriple(TheModule->getTargetTriple());
1099 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1100 createTLII(TargetTriple, CodeGenOpts));
1101 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1103 // Register all the basic analyses with the managers.
1104 PB.registerModuleAnalyses(MAM);
1105 PB.registerCGSCCAnalyses(CGAM);
1106 PB.registerFunctionAnalyses(FAM);
1107 PB.registerLoopAnalyses(LAM);
1108 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1110 ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1112 if (!CodeGenOpts.DisableLLVMPasses) {
1113 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1114 bool IsLTO = CodeGenOpts.PrepareForLTO;
1116 if (CodeGenOpts.OptimizationLevel == 0) {
1117 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1118 MPM.addPass(GCOVProfilerPass(*Options));
1119 if (Optional<InstrProfOptions> Options =
1120 getInstrProfOptions(CodeGenOpts, LangOpts))
1121 MPM.addPass(InstrProfiling(*Options, false));
1123 // Build a minimal pipeline based on the semantics required by Clang,
1124 // which is just that always inlining occurs. Further, disable generating
1125 // lifetime intrinsics to avoid enabling further optimizations during
1127 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/false));
1129 // At -O0, we can still do PGO. Add all the requested passes for
1130 // instrumentation PGO, if requested.
1131 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1132 PGOOpt->Action == PGOOptions::IRUse))
1133 PB.addPGOInstrPassesForO0(
1134 MPM, CodeGenOpts.DebugPassManager,
1135 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1136 /* IsCS */ false, PGOOpt->ProfileFile,
1137 PGOOpt->ProfileRemappingFile);
1139 // At -O0 we directly run necessary sanitizer passes.
1140 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1141 MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1143 // Lastly, add semantically necessary passes for LTO.
1144 if (IsLTO || IsThinLTO) {
1145 MPM.addPass(CanonicalizeAliasesPass());
1146 MPM.addPass(NameAnonGlobalPass());
1149 // Map our optimization levels into one of the distinct levels used to
1150 // configure the pipeline.
1151 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1153 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1154 MPM.addPass(createModuleToFunctionPassAdaptor(
1155 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1158 // Register callbacks to schedule sanitizer passes at the appropriate part of
1160 // FIXME: either handle asan/the remaining sanitizers or error out
1161 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1162 PB.registerScalarOptimizerLateEPCallback(
1163 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1164 FPM.addPass(BoundsCheckingPass());
1166 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1167 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1168 MPM.addPass(MemorySanitizerPass({}));
1170 PB.registerOptimizerLastEPCallback(
1171 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1172 FPM.addPass(MemorySanitizerPass({}));
1175 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1176 PB.registerPipelineStartEPCallback(
1177 [](ModulePassManager &MPM) { MPM.addPass(ThreadSanitizerPass()); });
1178 PB.registerOptimizerLastEPCallback(
1179 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1180 FPM.addPass(ThreadSanitizerPass());
1183 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1184 PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
1186 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1188 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1189 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1190 PB.registerOptimizerLastEPCallback(
1191 [Recover, UseAfterScope](FunctionPassManager &FPM,
1192 PassBuilder::OptimizationLevel Level) {
1193 FPM.addPass(AddressSanitizerPass(
1194 /*CompileKernel=*/false, Recover, UseAfterScope));
1196 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1197 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1198 PB.registerPipelineStartEPCallback(
1199 [Recover, ModuleUseAfterScope,
1200 UseOdrIndicator](ModulePassManager &MPM) {
1201 MPM.addPass(ModuleAddressSanitizerPass(
1202 /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1206 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1207 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1208 MPM.addPass(GCOVProfilerPass(*Options));
1210 if (Optional<InstrProfOptions> Options =
1211 getInstrProfOptions(CodeGenOpts, LangOpts))
1212 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1213 MPM.addPass(InstrProfiling(*Options, false));
1217 MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1218 Level, CodeGenOpts.DebugPassManager);
1219 MPM.addPass(CanonicalizeAliasesPass());
1220 MPM.addPass(NameAnonGlobalPass());
1222 MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1223 CodeGenOpts.DebugPassManager);
1224 MPM.addPass(CanonicalizeAliasesPass());
1225 MPM.addPass(NameAnonGlobalPass());
1227 MPM = PB.buildPerModuleDefaultPipeline(Level,
1228 CodeGenOpts.DebugPassManager);
1232 if (CodeGenOpts.SanitizeCoverageType ||
1233 CodeGenOpts.SanitizeCoverageIndirectCalls ||
1234 CodeGenOpts.SanitizeCoverageTraceCmp) {
1235 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1236 MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
1239 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1240 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1241 MPM.addPass(HWAddressSanitizerPass(
1242 /*CompileKernel=*/false, Recover));
1244 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1245 MPM.addPass(HWAddressSanitizerPass(
1246 /*CompileKernel=*/true, /*Recover=*/true));
1249 if (CodeGenOpts.OptimizationLevel == 0) {
1250 addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1254 // FIXME: We still use the legacy pass manager to do code generation. We
1255 // create that pass manager here and use it as needed below.
1256 legacy::PassManager CodeGenPasses;
1257 bool NeedCodeGen = false;
1258 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1260 // Append any output we need to the pass manager.
1262 case Backend_EmitNothing:
1265 case Backend_EmitBC:
1266 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1267 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1268 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1272 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1273 CodeGenOpts.EnableSplitLTOUnit);
1274 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1277 // Emit a module summary by default for Regular LTO except for ld64
1279 bool EmitLTOSummary =
1280 (CodeGenOpts.PrepareForLTO &&
1281 !CodeGenOpts.DisableLLVMPasses &&
1282 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1283 llvm::Triple::Apple);
1284 if (EmitLTOSummary) {
1285 if (!TheModule->getModuleFlag("ThinLTO"))
1286 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1287 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1291 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1295 case Backend_EmitLL:
1296 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1299 case Backend_EmitAssembly:
1300 case Backend_EmitMCNull:
1301 case Backend_EmitObj:
1304 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1305 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1306 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1310 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1311 DwoOS ? &DwoOS->os() : nullptr))
1312 // FIXME: Should we handle this error differently?
1317 // Before executing passes, print the final values of the LLVM options.
1318 cl::PrintOptionValues();
1320 // Now that we have all of the passes ready, run them.
1322 PrettyStackTraceString CrashInfo("Optimizer");
1323 MPM.run(*TheModule, MAM);
1326 // Now if needed, run the legacy PM for codegen.
1328 PrettyStackTraceString CrashInfo("Code generation");
1329 CodeGenPasses.run(*TheModule);
1338 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1339 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1341 return BMsOrErr.takeError();
1343 // The bitcode file may contain multiple modules, we want the one that is
1344 // marked as being the ThinLTO module.
1345 if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1348 return make_error<StringError>("Could not find module summary",
1349 inconvertibleErrorCode());
1352 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1353 for (BitcodeModule &BM : BMs) {
1354 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1355 if (LTOInfo && LTOInfo->IsThinLTO)
1361 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1362 const HeaderSearchOptions &HeaderOpts,
1363 const CodeGenOptions &CGOpts,
1364 const clang::TargetOptions &TOpts,
1365 const LangOptions &LOpts,
1366 std::unique_ptr<raw_pwrite_stream> OS,
1367 std::string SampleProfile,
1368 std::string ProfileRemapping,
1369 BackendAction Action) {
1370 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1371 ModuleToDefinedGVSummaries;
1372 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1374 setCommandLineOpts(CGOpts);
1376 // We can simply import the values mentioned in the combined index, since
1377 // we should only invoke this using the individual indexes written out
1378 // via a WriteIndexesThinBackend.
1379 FunctionImporter::ImportMapTy ImportList;
1380 for (auto &GlobalList : *CombinedIndex) {
1381 // Ignore entries for undefined references.
1382 if (GlobalList.second.SummaryList.empty())
1385 auto GUID = GlobalList.first;
1386 for (auto &Summary : GlobalList.second.SummaryList) {
1387 // Skip the summaries for the importing module. These are included to
1388 // e.g. record required linkage changes.
1389 if (Summary->modulePath() == M->getModuleIdentifier())
1391 // Add an entry to provoke importing by thinBackend.
1392 ImportList[Summary->modulePath()].insert(GUID);
1396 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1397 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1399 for (auto &I : ImportList) {
1400 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1401 llvm::MemoryBuffer::getFile(I.first());
1403 errs() << "Error loading imported file '" << I.first()
1404 << "': " << MBOrErr.getError().message() << "\n";
1408 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1410 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1411 errs() << "Error loading imported file '" << I.first()
1412 << "': " << EIB.message() << '\n';
1416 ModuleMap.insert({I.first(), *BMOrErr});
1418 OwnedImports.push_back(std::move(*MBOrErr));
1420 auto AddStream = [&](size_t Task) {
1421 return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1424 if (CGOpts.SaveTempsFilePrefix != "") {
1425 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1426 /* UseInputModulePath */ false)) {
1427 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1428 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1433 Conf.CPU = TOpts.CPU;
1434 Conf.CodeModel = getCodeModel(CGOpts);
1435 Conf.MAttrs = TOpts.Features;
1436 Conf.RelocModel = CGOpts.RelocationModel;
1437 Conf.CGOptLevel = getCGOptLevel(CGOpts);
1438 Conf.OptLevel = CGOpts.OptimizationLevel;
1439 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1440 Conf.SampleProfile = std::move(SampleProfile);
1441 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1442 // For historical reasons, loop interleaving is set to mirror setting for loop
1444 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1445 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1446 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1448 // Context sensitive profile.
1449 if (CGOpts.hasProfileCSIRInstr()) {
1450 Conf.RunCSIRInstr = true;
1451 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1452 } else if (CGOpts.hasProfileCSIRUse()) {
1453 Conf.RunCSIRInstr = false;
1454 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1457 Conf.ProfileRemapping = std::move(ProfileRemapping);
1458 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1459 Conf.DebugPassManager = CGOpts.DebugPassManager;
1460 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1461 Conf.RemarksFilename = CGOpts.OptRecordFile;
1462 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1463 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1464 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1465 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1467 case Backend_EmitNothing:
1468 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1472 case Backend_EmitLL:
1473 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1474 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1478 case Backend_EmitBC:
1479 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1480 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1485 Conf.CGFileType = getCodeGenFileType(Action);
1488 if (Error E = thinBackend(
1489 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1490 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1491 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1492 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1497 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1498 const HeaderSearchOptions &HeaderOpts,
1499 const CodeGenOptions &CGOpts,
1500 const clang::TargetOptions &TOpts,
1501 const LangOptions &LOpts,
1502 const llvm::DataLayout &TDesc, Module *M,
1503 BackendAction Action,
1504 std::unique_ptr<raw_pwrite_stream> OS) {
1506 llvm::TimeTraceScope TimeScope("Backend");
1508 std::unique_ptr<llvm::Module> EmptyModule;
1509 if (!CGOpts.ThinLTOIndexFile.empty()) {
1510 // If we are performing a ThinLTO importing compile, load the function index
1511 // into memory and pass it into runThinLTOBackend, which will run the
1512 // function importer and invoke LTO passes.
1513 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1514 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1515 /*IgnoreEmptyThinLTOIndexFile*/true);
1517 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1518 "Error loading index file '" +
1519 CGOpts.ThinLTOIndexFile + "': ");
1522 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1523 // A null CombinedIndex means we should skip ThinLTO compilation
1524 // (LLVM will optionally ignore empty index files, returning null instead
1526 if (CombinedIndex) {
1527 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1528 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1529 LOpts, std::move(OS), CGOpts.SampleProfileFile,
1530 CGOpts.ProfileRemappingFile, Action);
1533 // Distributed indexing detected that nothing from the module is needed
1534 // for the final linking. So we can skip the compilation. We sill need to
1535 // output an empty object file to make sure that a linker does not fail
1536 // trying to read it. Also for some features, like CFI, we must skip
1537 // the compilation as CombinedIndex does not contain all required
1539 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1540 EmptyModule->setTargetTriple(M->getTargetTriple());
1541 M = EmptyModule.get();
1545 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1547 if (CGOpts.ExperimentalNewPassManager)
1548 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1550 AsmHelper.EmitAssembly(Action, std::move(OS));
1552 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1555 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1556 if (DLDesc != TDesc.getStringRepresentation()) {
1557 unsigned DiagID = Diags.getCustomDiagID(
1558 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1559 "expected target description '%1'");
1560 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1565 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1566 // __LLVM,__bitcode section.
1567 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1568 llvm::MemoryBufferRef Buf) {
1569 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1571 llvm::EmbedBitcodeInModule(
1572 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1573 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,