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 "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/AliasAnalysis.h"
22 #include "llvm/Analysis/StackSafetyAnalysis.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Bitcode/BitcodeReader.h"
26 #include "llvm/Bitcode/BitcodeWriter.h"
27 #include "llvm/Bitcode/BitcodeWriterPass.h"
28 #include "llvm/CodeGen/RegAllocRegistry.h"
29 #include "llvm/CodeGen/SchedulerRegistry.h"
30 #include "llvm/CodeGen/TargetSubtargetInfo.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/IRPrintingPasses.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/ModuleSummaryIndex.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/LTO/LTOBackend.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/MC/TargetRegistry.h"
42 #include "llvm/Passes/PassBuilder.h"
43 #include "llvm/Passes/PassPlugin.h"
44 #include "llvm/Passes/StandardInstrumentations.h"
45 #include "llvm/Support/BuryPointer.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 #include "llvm/Support/PrettyStackTrace.h"
49 #include "llvm/Support/TimeProfiler.h"
50 #include "llvm/Support/Timer.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "llvm/Transforms/Coroutines.h"
56 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
57 #include "llvm/Transforms/Coroutines/CoroEarly.h"
58 #include "llvm/Transforms/Coroutines/CoroElide.h"
59 #include "llvm/Transforms/Coroutines/CoroSplit.h"
60 #include "llvm/Transforms/IPO.h"
61 #include "llvm/Transforms/IPO/AlwaysInliner.h"
62 #include "llvm/Transforms/IPO/LowerTypeTests.h"
63 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
64 #include "llvm/Transforms/InstCombine/InstCombine.h"
65 #include "llvm/Transforms/Instrumentation.h"
66 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
67 #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
68 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
69 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
70 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
71 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
72 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
73 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
74 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
75 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
76 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
77 #include "llvm/Transforms/ObjCARC.h"
78 #include "llvm/Transforms/Scalar.h"
79 #include "llvm/Transforms/Scalar/EarlyCSE.h"
80 #include "llvm/Transforms/Scalar/GVN.h"
81 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
82 #include "llvm/Transforms/Utils.h"
83 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
84 #include "llvm/Transforms/Utils/Debugify.h"
85 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
86 #include "llvm/Transforms/Utils/ModuleUtils.h"
87 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
88 #include "llvm/Transforms/Utils/SymbolRewriter.h"
89 #include <memory>
90 using namespace clang;
91 using namespace llvm;
92 
93 #define HANDLE_EXTENSION(Ext)                                                  \
94   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
95 #include "llvm/Support/Extension.def"
96 
97 namespace llvm {
98 extern cl::opt<bool> DebugInfoCorrelate;
99 }
100 
101 namespace {
102 
103 // Default filename used for profile generation.
104 std::string getDefaultProfileGenName() {
105   return DebugInfoCorrelate ? "default_%p.proflite" : "default_%m.profraw";
106 }
107 
108 class EmitAssemblyHelper {
109   DiagnosticsEngine &Diags;
110   const HeaderSearchOptions &HSOpts;
111   const CodeGenOptions &CodeGenOpts;
112   const clang::TargetOptions &TargetOpts;
113   const LangOptions &LangOpts;
114   Module *TheModule;
115 
116   Timer CodeGenerationTime;
117 
118   std::unique_ptr<raw_pwrite_stream> OS;
119 
120   Triple TargetTriple;
121 
122   TargetIRAnalysis getTargetIRAnalysis() const {
123     if (TM)
124       return TM->getTargetIRAnalysis();
125 
126     return TargetIRAnalysis();
127   }
128 
129   /// Generates the TargetMachine.
130   /// Leaves TM unchanged if it is unable to create the target machine.
131   /// Some of our clang tests specify triples which are not built
132   /// into clang. This is okay because these tests check the generated
133   /// IR, and they require DataLayout which depends on the triple.
134   /// In this case, we allow this method to fail and not report an error.
135   /// When MustCreateTM is used, we print an error if we are unable to load
136   /// the requested target.
137   void CreateTargetMachine(bool MustCreateTM);
138 
139   /// Add passes necessary to emit assembly or LLVM IR.
140   ///
141   /// \return True on success.
142   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
143                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
144 
145   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
146     std::error_code EC;
147     auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
148                                                      llvm::sys::fs::OF_None);
149     if (EC) {
150       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
151       F.reset();
152     }
153     return F;
154   }
155 
156   void
157   RunOptimizationPipeline(BackendAction Action,
158                           std::unique_ptr<raw_pwrite_stream> &OS,
159                           std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS);
160   void RunCodegenPipeline(BackendAction Action,
161                           std::unique_ptr<raw_pwrite_stream> &OS,
162                           std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
163 
164   /// Check whether we should emit a module summary for regular LTO.
165   /// The module summary should be emitted by default for regular LTO
166   /// except for ld64 targets.
167   ///
168   /// \return True if the module summary should be emitted.
169   bool shouldEmitRegularLTOSummary() const {
170     return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
171            TargetTriple.getVendor() != llvm::Triple::Apple;
172   }
173 
174 public:
175   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
176                      const HeaderSearchOptions &HeaderSearchOpts,
177                      const CodeGenOptions &CGOpts,
178                      const clang::TargetOptions &TOpts,
179                      const LangOptions &LOpts, Module *M)
180       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
181         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
182         CodeGenerationTime("codegen", "Code Generation Time"),
183         TargetTriple(TheModule->getTargetTriple()) {}
184 
185   ~EmitAssemblyHelper() {
186     if (CodeGenOpts.DisableFree)
187       BuryPointer(std::move(TM));
188   }
189 
190   std::unique_ptr<TargetMachine> TM;
191 
192   // Emit output using the new pass manager for the optimization pipeline.
193   void EmitAssembly(BackendAction Action,
194                     std::unique_ptr<raw_pwrite_stream> OS);
195 };
196 }
197 
198 static SanitizerCoverageOptions
199 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
200   SanitizerCoverageOptions Opts;
201   Opts.CoverageType =
202       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
203   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
204   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
205   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
206   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
207   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
208   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
209   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
210   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
211   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
212   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
213   Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
214   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
215   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
216   Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
217   Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
218   return Opts;
219 }
220 
221 // Check if ASan should use GC-friendly instrumentation for globals.
222 // First of all, there is no point if -fdata-sections is off (expect for MachO,
223 // where this is not a factor). Also, on ELF this feature requires an assembler
224 // extension that only works with -integrated-as at the moment.
225 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
226   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
227     return false;
228   switch (T.getObjectFormat()) {
229   case Triple::MachO:
230   case Triple::COFF:
231     return true;
232   case Triple::ELF:
233     return !CGOpts.DisableIntegratedAS;
234   case Triple::GOFF:
235     llvm::report_fatal_error("ASan not implemented for GOFF");
236   case Triple::XCOFF:
237     llvm::report_fatal_error("ASan not implemented for XCOFF.");
238   case Triple::Wasm:
239   case Triple::DXContainer:
240   case Triple::UnknownObjectFormat:
241     break;
242   }
243   return false;
244 }
245 
246 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
247                                          const CodeGenOptions &CodeGenOpts) {
248   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
249 
250   switch (CodeGenOpts.getVecLib()) {
251   case CodeGenOptions::Accelerate:
252     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
253     break;
254   case CodeGenOptions::LIBMVEC:
255     switch(TargetTriple.getArch()) {
256       default:
257         break;
258       case llvm::Triple::x86_64:
259         TLII->addVectorizableFunctionsFromVecLib
260                 (TargetLibraryInfoImpl::LIBMVEC_X86);
261         break;
262     }
263     break;
264   case CodeGenOptions::MASSV:
265     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
266     break;
267   case CodeGenOptions::SVML:
268     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
269     break;
270   case CodeGenOptions::Darwin_libsystem_m:
271     TLII->addVectorizableFunctionsFromVecLib(
272         TargetLibraryInfoImpl::DarwinLibSystemM);
273     break;
274   default:
275     break;
276   }
277   return TLII;
278 }
279 
280 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
281   switch (CodeGenOpts.OptimizationLevel) {
282   default:
283     llvm_unreachable("Invalid optimization level!");
284   case 0:
285     return CodeGenOpt::None;
286   case 1:
287     return CodeGenOpt::Less;
288   case 2:
289     return CodeGenOpt::Default; // O2/Os/Oz
290   case 3:
291     return CodeGenOpt::Aggressive;
292   }
293 }
294 
295 static Optional<llvm::CodeModel::Model>
296 getCodeModel(const CodeGenOptions &CodeGenOpts) {
297   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
298                            .Case("tiny", llvm::CodeModel::Tiny)
299                            .Case("small", llvm::CodeModel::Small)
300                            .Case("kernel", llvm::CodeModel::Kernel)
301                            .Case("medium", llvm::CodeModel::Medium)
302                            .Case("large", llvm::CodeModel::Large)
303                            .Case("default", ~1u)
304                            .Default(~0u);
305   assert(CodeModel != ~0u && "invalid code model!");
306   if (CodeModel == ~1u)
307     return None;
308   return static_cast<llvm::CodeModel::Model>(CodeModel);
309 }
310 
311 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
312   if (Action == Backend_EmitObj)
313     return CGFT_ObjectFile;
314   else if (Action == Backend_EmitMCNull)
315     return CGFT_Null;
316   else {
317     assert(Action == Backend_EmitAssembly && "Invalid action!");
318     return CGFT_AssemblyFile;
319   }
320 }
321 
322 static bool actionRequiresCodeGen(BackendAction Action) {
323   return Action != Backend_EmitNothing && Action != Backend_EmitBC &&
324          Action != Backend_EmitLL;
325 }
326 
327 static bool initTargetOptions(DiagnosticsEngine &Diags,
328                               llvm::TargetOptions &Options,
329                               const CodeGenOptions &CodeGenOpts,
330                               const clang::TargetOptions &TargetOpts,
331                               const LangOptions &LangOpts,
332                               const HeaderSearchOptions &HSOpts) {
333   switch (LangOpts.getThreadModel()) {
334   case LangOptions::ThreadModelKind::POSIX:
335     Options.ThreadModel = llvm::ThreadModel::POSIX;
336     break;
337   case LangOptions::ThreadModelKind::Single:
338     Options.ThreadModel = llvm::ThreadModel::Single;
339     break;
340   }
341 
342   // Set float ABI type.
343   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
344           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
345          "Invalid Floating Point ABI!");
346   Options.FloatABIType =
347       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
348           .Case("soft", llvm::FloatABI::Soft)
349           .Case("softfp", llvm::FloatABI::Soft)
350           .Case("hard", llvm::FloatABI::Hard)
351           .Default(llvm::FloatABI::Default);
352 
353   // Set FP fusion mode.
354   switch (LangOpts.getDefaultFPContractMode()) {
355   case LangOptions::FPM_Off:
356     // Preserve any contraction performed by the front-end.  (Strict performs
357     // splitting of the muladd intrinsic in the backend.)
358     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
359     break;
360   case LangOptions::FPM_On:
361   case LangOptions::FPM_FastHonorPragmas:
362     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
363     break;
364   case LangOptions::FPM_Fast:
365     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
366     break;
367   }
368 
369   Options.BinutilsVersion =
370       llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
371   Options.UseInitArray = CodeGenOpts.UseInitArray;
372   Options.LowerGlobalDtorsViaCxaAtExit =
373       CodeGenOpts.RegisterGlobalDtorsWithAtExit;
374   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
375   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
376   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
377 
378   // Set EABI version.
379   Options.EABIVersion = TargetOpts.EABIVersion;
380 
381   if (LangOpts.hasSjLjExceptions())
382     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
383   if (LangOpts.hasSEHExceptions())
384     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
385   if (LangOpts.hasDWARFExceptions())
386     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
387   if (LangOpts.hasWasmExceptions())
388     Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
389 
390   Options.NoInfsFPMath = LangOpts.NoHonorInfs;
391   Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
392   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
393   Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
394   Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
395 
396   Options.BBSections =
397       llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
398           .Case("all", llvm::BasicBlockSection::All)
399           .Case("labels", llvm::BasicBlockSection::Labels)
400           .StartsWith("list=", llvm::BasicBlockSection::List)
401           .Case("none", llvm::BasicBlockSection::None)
402           .Default(llvm::BasicBlockSection::None);
403 
404   if (Options.BBSections == llvm::BasicBlockSection::List) {
405     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
406         MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
407     if (!MBOrErr) {
408       Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
409           << MBOrErr.getError().message();
410       return false;
411     }
412     Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
413   }
414 
415   Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
416   Options.FunctionSections = CodeGenOpts.FunctionSections;
417   Options.DataSections = CodeGenOpts.DataSections;
418   Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
419   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
420   Options.UniqueBasicBlockSectionNames =
421       CodeGenOpts.UniqueBasicBlockSectionNames;
422   Options.TLSSize = CodeGenOpts.TLSSize;
423   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
424   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
425   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
426   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
427   Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
428   Options.EmitAddrsig = CodeGenOpts.Addrsig;
429   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
430   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
431   Options.EnableAIXExtendedAltivecABI = CodeGenOpts.EnableAIXExtendedAltivecABI;
432   Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
433   Options.LoopAlignment = CodeGenOpts.LoopAlignment;
434   Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
435   Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
436   Options.Hotpatch = CodeGenOpts.HotPatch;
437   Options.JMCInstrument = CodeGenOpts.JMCInstrument;
438 
439   switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
440   case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
441     Options.SwiftAsyncFramePointer =
442         SwiftAsyncFramePointerMode::DeploymentBased;
443     break;
444 
445   case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
446     Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
447     break;
448 
449   case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
450     Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
451     break;
452   }
453 
454   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
455   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
456   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
457   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
458   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
459   Options.MCOptions.MCIncrementalLinkerCompatible =
460       CodeGenOpts.IncrementalLinkerCompatible;
461   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
462   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
463   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
464   Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
465   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
466   Options.MCOptions.ABIName = TargetOpts.ABI;
467   for (const auto &Entry : HSOpts.UserEntries)
468     if (!Entry.IsFramework &&
469         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
470          Entry.Group == frontend::IncludeDirGroup::Angled ||
471          Entry.Group == frontend::IncludeDirGroup::System))
472       Options.MCOptions.IASSearchPaths.push_back(
473           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
474   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
475   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
476 
477   return true;
478 }
479 
480 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
481                                             const LangOptions &LangOpts) {
482   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
483     return None;
484   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
485   // LLVM's -default-gcov-version flag is set to something invalid.
486   GCOVOptions Options;
487   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
488   Options.EmitData = CodeGenOpts.EmitGcovArcs;
489   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
490   Options.NoRedZone = CodeGenOpts.DisableRedZone;
491   Options.Filter = CodeGenOpts.ProfileFilterFiles;
492   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
493   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
494   return Options;
495 }
496 
497 static Optional<InstrProfOptions>
498 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
499                     const LangOptions &LangOpts) {
500   if (!CodeGenOpts.hasProfileClangInstr())
501     return None;
502   InstrProfOptions Options;
503   Options.NoRedZone = CodeGenOpts.DisableRedZone;
504   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
505   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
506   return Options;
507 }
508 
509 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
510   SmallVector<const char *, 16> BackendArgs;
511   BackendArgs.push_back("clang"); // Fake program name.
512   if (!CodeGenOpts.DebugPass.empty()) {
513     BackendArgs.push_back("-debug-pass");
514     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
515   }
516   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
517     BackendArgs.push_back("-limit-float-precision");
518     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
519   }
520   // Check for the default "clang" invocation that won't set any cl::opt values.
521   // Skip trying to parse the command line invocation to avoid the issues
522   // described below.
523   if (BackendArgs.size() == 1)
524     return;
525   BackendArgs.push_back(nullptr);
526   // FIXME: The command line parser below is not thread-safe and shares a global
527   // state, so this call might crash or overwrite the options of another Clang
528   // instance in the same process.
529   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
530                                     BackendArgs.data());
531 }
532 
533 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
534   // Create the TargetMachine for generating code.
535   std::string Error;
536   std::string Triple = TheModule->getTargetTriple();
537   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
538   if (!TheTarget) {
539     if (MustCreateTM)
540       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
541     return;
542   }
543 
544   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
545   std::string FeaturesStr =
546       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
547   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
548   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
549 
550   llvm::TargetOptions Options;
551   if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
552                          HSOpts))
553     return;
554   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
555                                           Options, RM, CM, OptLevel));
556 }
557 
558 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
559                                        BackendAction Action,
560                                        raw_pwrite_stream &OS,
561                                        raw_pwrite_stream *DwoOS) {
562   // Add LibraryInfo.
563   std::unique_ptr<TargetLibraryInfoImpl> TLII(
564       createTLII(TargetTriple, CodeGenOpts));
565   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
566 
567   // Normal mode, emit a .s or .o file by running the code generator. Note,
568   // this also adds codegenerator level optimization passes.
569   CodeGenFileType CGFT = getCodeGenFileType(Action);
570 
571   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
572   // "codegen" passes so that it isn't run multiple times when there is
573   // inlining happening.
574   if (CodeGenOpts.OptimizationLevel > 0)
575     CodeGenPasses.add(createObjCARCContractPass());
576 
577   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
578                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
579     Diags.Report(diag::err_fe_unable_to_interface_with_target);
580     return false;
581   }
582 
583   return true;
584 }
585 
586 static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
587   switch (Opts.OptimizationLevel) {
588   default:
589     llvm_unreachable("Invalid optimization level!");
590 
591   case 0:
592     return OptimizationLevel::O0;
593 
594   case 1:
595     return OptimizationLevel::O1;
596 
597   case 2:
598     switch (Opts.OptimizeSize) {
599     default:
600       llvm_unreachable("Invalid optimization level for size!");
601 
602     case 0:
603       return OptimizationLevel::O2;
604 
605     case 1:
606       return OptimizationLevel::Os;
607 
608     case 2:
609       return OptimizationLevel::Oz;
610     }
611 
612   case 3:
613     return OptimizationLevel::O3;
614   }
615 }
616 
617 static void addSanitizers(const Triple &TargetTriple,
618                           const CodeGenOptions &CodeGenOpts,
619                           const LangOptions &LangOpts, PassBuilder &PB) {
620   PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
621                                          OptimizationLevel Level) {
622     if (CodeGenOpts.hasSanitizeCoverage()) {
623       auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
624       MPM.addPass(ModuleSanitizerCoveragePass(
625           SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
626           CodeGenOpts.SanitizeCoverageIgnorelistFiles));
627     }
628 
629     auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
630       if (LangOpts.Sanitize.has(Mask)) {
631         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
632         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
633 
634         MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
635                                        CodeGenOpts.SanitizeMemoryParamRetval);
636         MPM.addPass(ModuleMemorySanitizerPass(options));
637         FunctionPassManager FPM;
638         FPM.addPass(MemorySanitizerPass(options));
639         if (Level != OptimizationLevel::O0) {
640           // MemorySanitizer inserts complex instrumentation that mostly
641           // follows the logic of the original code, but operates on
642           // "shadow" values. It can benefit from re-running some
643           // general purpose optimization passes.
644           FPM.addPass(EarlyCSEPass());
645           // TODO: Consider add more passes like in
646           // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible
647           // difference on size. It's not clear if the rest is still
648           // usefull. InstCombinePass breakes
649           // compiler-rt/test/msan/select_origin.cpp.
650         }
651         MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
652       }
653     };
654     MSanPass(SanitizerKind::Memory, false);
655     MSanPass(SanitizerKind::KernelMemory, true);
656 
657     if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
658       MPM.addPass(ModuleThreadSanitizerPass());
659       MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
660     }
661 
662     auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
663       if (LangOpts.Sanitize.has(Mask)) {
664         bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
665         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
666         llvm::AsanDtorKind DestructorKind =
667             CodeGenOpts.getSanitizeAddressDtor();
668         AddressSanitizerOptions Opts;
669         Opts.CompileKernel = CompileKernel;
670         Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
671         Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
672         Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
673         MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
674         MPM.addPass(ModuleAddressSanitizerPass(
675             Opts, UseGlobalGC, UseOdrIndicator, DestructorKind));
676       }
677     };
678     ASanPass(SanitizerKind::Address, false);
679     ASanPass(SanitizerKind::KernelAddress, true);
680 
681     auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
682       if (LangOpts.Sanitize.has(Mask)) {
683         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
684         MPM.addPass(HWAddressSanitizerPass(
685             {CompileKernel, Recover,
686              /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
687       }
688     };
689     HWASanPass(SanitizerKind::HWAddress, false);
690     HWASanPass(SanitizerKind::KernelHWAddress, true);
691 
692     if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
693       MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
694     }
695   });
696 }
697 
698 void EmitAssemblyHelper::RunOptimizationPipeline(
699     BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
700     std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS) {
701   Optional<PGOOptions> PGOOpt;
702 
703   if (CodeGenOpts.hasProfileIRInstr())
704     // -fprofile-generate.
705     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
706                             ? getDefaultProfileGenName()
707                             : CodeGenOpts.InstrProfileOutput,
708                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
709                         CodeGenOpts.DebugInfoForProfiling);
710   else if (CodeGenOpts.hasProfileIRUse()) {
711     // -fprofile-use.
712     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
713                                                     : PGOOptions::NoCSAction;
714     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
715                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
716                         CSAction, CodeGenOpts.DebugInfoForProfiling);
717   } else if (!CodeGenOpts.SampleProfileFile.empty())
718     // -fprofile-sample-use
719     PGOOpt = PGOOptions(
720         CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
721         PGOOptions::SampleUse, PGOOptions::NoCSAction,
722         CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
723   else if (CodeGenOpts.PseudoProbeForProfiling)
724     // -fpseudo-probe-for-profiling
725     PGOOpt =
726         PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
727                    CodeGenOpts.DebugInfoForProfiling, true);
728   else if (CodeGenOpts.DebugInfoForProfiling)
729     // -fdebug-info-for-profiling
730     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
731                         PGOOptions::NoCSAction, true);
732 
733   // Check to see if we want to generate a CS profile.
734   if (CodeGenOpts.hasProfileCSIRInstr()) {
735     assert(!CodeGenOpts.hasProfileCSIRUse() &&
736            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
737            "the same time");
738     if (PGOOpt.hasValue()) {
739       assert(PGOOpt->Action != PGOOptions::IRInstr &&
740              PGOOpt->Action != PGOOptions::SampleUse &&
741              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
742              " pass");
743       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
744                                      ? getDefaultProfileGenName()
745                                      : CodeGenOpts.InstrProfileOutput;
746       PGOOpt->CSAction = PGOOptions::CSIRInstr;
747     } else
748       PGOOpt = PGOOptions("",
749                           CodeGenOpts.InstrProfileOutput.empty()
750                               ? getDefaultProfileGenName()
751                               : CodeGenOpts.InstrProfileOutput,
752                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
753                           CodeGenOpts.DebugInfoForProfiling);
754   }
755   if (TM)
756     TM->setPGOOption(PGOOpt);
757 
758   PipelineTuningOptions PTO;
759   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
760   // For historical reasons, loop interleaving is set to mirror setting for loop
761   // unrolling.
762   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
763   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
764   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
765   PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
766   // Only enable CGProfilePass when using integrated assembler, since
767   // non-integrated assemblers don't recognize .cgprofile section.
768   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
769 
770   LoopAnalysisManager LAM;
771   FunctionAnalysisManager FAM;
772   CGSCCAnalysisManager CGAM;
773   ModuleAnalysisManager MAM;
774 
775   bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
776   PassInstrumentationCallbacks PIC;
777   PrintPassOptions PrintPassOpts;
778   PrintPassOpts.Indent = DebugPassStructure;
779   PrintPassOpts.SkipAnalyses = DebugPassStructure;
780   StandardInstrumentations SI(CodeGenOpts.DebugPassManager ||
781                                   DebugPassStructure,
782                               /*VerifyEach*/ false, PrintPassOpts);
783   SI.registerCallbacks(PIC, &FAM);
784   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
785 
786   // Attempt to load pass plugins and register their callbacks with PB.
787   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
788     auto PassPlugin = PassPlugin::Load(PluginFN);
789     if (PassPlugin) {
790       PassPlugin->registerPassBuilderCallbacks(PB);
791     } else {
792       Diags.Report(diag::err_fe_unable_to_load_plugin)
793           << PluginFN << toString(PassPlugin.takeError());
794     }
795   }
796 #define HANDLE_EXTENSION(Ext)                                                  \
797   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
798 #include "llvm/Support/Extension.def"
799 
800   // Register the target library analysis directly and give it a customized
801   // preset TLI.
802   std::unique_ptr<TargetLibraryInfoImpl> TLII(
803       createTLII(TargetTriple, CodeGenOpts));
804   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
805 
806   // Register all the basic analyses with the managers.
807   PB.registerModuleAnalyses(MAM);
808   PB.registerCGSCCAnalyses(CGAM);
809   PB.registerFunctionAnalyses(FAM);
810   PB.registerLoopAnalyses(LAM);
811   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
812 
813   ModulePassManager MPM;
814 
815   if (!CodeGenOpts.DisableLLVMPasses) {
816     // Map our optimization levels into one of the distinct levels used to
817     // configure the pipeline.
818     OptimizationLevel Level = mapToLevel(CodeGenOpts);
819 
820     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
821     bool IsLTO = CodeGenOpts.PrepareForLTO;
822 
823     if (LangOpts.ObjCAutoRefCount) {
824       PB.registerPipelineStartEPCallback(
825           [](ModulePassManager &MPM, OptimizationLevel Level) {
826             if (Level != OptimizationLevel::O0)
827               MPM.addPass(
828                   createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
829           });
830       PB.registerPipelineEarlySimplificationEPCallback(
831           [](ModulePassManager &MPM, OptimizationLevel Level) {
832             if (Level != OptimizationLevel::O0)
833               MPM.addPass(ObjCARCAPElimPass());
834           });
835       PB.registerScalarOptimizerLateEPCallback(
836           [](FunctionPassManager &FPM, OptimizationLevel Level) {
837             if (Level != OptimizationLevel::O0)
838               FPM.addPass(ObjCARCOptPass());
839           });
840     }
841 
842     // If we reached here with a non-empty index file name, then the index
843     // file was empty and we are not performing ThinLTO backend compilation
844     // (used in testing in a distributed build environment).
845     bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
846     // If so drop any the type test assume sequences inserted for whole program
847     // vtables so that codegen doesn't complain.
848     if (IsThinLTOPostLink)
849       PB.registerPipelineStartEPCallback(
850           [](ModulePassManager &MPM, OptimizationLevel Level) {
851             MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
852                                            /*ImportSummary=*/nullptr,
853                                            /*DropTypeTests=*/true));
854           });
855 
856     if (CodeGenOpts.InstrumentFunctions ||
857         CodeGenOpts.InstrumentFunctionEntryBare ||
858         CodeGenOpts.InstrumentFunctionsAfterInlining ||
859         CodeGenOpts.InstrumentForProfiling) {
860       PB.registerPipelineStartEPCallback(
861           [](ModulePassManager &MPM, OptimizationLevel Level) {
862             MPM.addPass(createModuleToFunctionPassAdaptor(
863                 EntryExitInstrumenterPass(/*PostInlining=*/false)));
864           });
865       PB.registerOptimizerLastEPCallback(
866           [](ModulePassManager &MPM, OptimizationLevel Level) {
867             MPM.addPass(createModuleToFunctionPassAdaptor(
868                 EntryExitInstrumenterPass(/*PostInlining=*/true)));
869           });
870     }
871 
872     // Register callbacks to schedule sanitizer passes at the appropriate part
873     // of the pipeline.
874     if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
875       PB.registerScalarOptimizerLateEPCallback(
876           [](FunctionPassManager &FPM, OptimizationLevel Level) {
877             FPM.addPass(BoundsCheckingPass());
878           });
879 
880     // Don't add sanitizers if we are here from ThinLTO PostLink. That already
881     // done on PreLink stage.
882     if (!IsThinLTOPostLink)
883       addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
884 
885     if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
886       PB.registerPipelineStartEPCallback(
887           [Options](ModulePassManager &MPM, OptimizationLevel Level) {
888             MPM.addPass(GCOVProfilerPass(*Options));
889           });
890     if (Optional<InstrProfOptions> Options =
891             getInstrProfOptions(CodeGenOpts, LangOpts))
892       PB.registerPipelineStartEPCallback(
893           [Options](ModulePassManager &MPM, OptimizationLevel Level) {
894             MPM.addPass(InstrProfiling(*Options, false));
895           });
896 
897     if (CodeGenOpts.OptimizationLevel == 0) {
898       MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO);
899     } else if (IsThinLTO) {
900       MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
901     } else if (IsLTO) {
902       MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
903     } else {
904       MPM = PB.buildPerModuleDefaultPipeline(Level);
905     }
906 
907     if (!CodeGenOpts.MemoryProfileOutput.empty()) {
908       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
909       MPM.addPass(ModuleMemProfilerPass());
910     }
911   }
912 
913   // Add a verifier pass if requested. We don't have to do this if the action
914   // requires code generation because there will already be a verifier pass in
915   // the code-generation pipeline.
916   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
917     MPM.addPass(VerifierPass());
918 
919   switch (Action) {
920   case Backend_EmitBC:
921     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
922       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
923         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
924         if (!ThinLinkOS)
925           return;
926       }
927       if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
928         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
929                                  CodeGenOpts.EnableSplitLTOUnit);
930       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
931                                                            : nullptr));
932     } else {
933       // Emit a module summary by default for Regular LTO except for ld64
934       // targets
935       bool EmitLTOSummary = shouldEmitRegularLTOSummary();
936       if (EmitLTOSummary) {
937         if (!TheModule->getModuleFlag("ThinLTO"))
938           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
939         if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
940           TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
941                                    uint32_t(1));
942       }
943       MPM.addPass(
944           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
945     }
946     break;
947 
948   case Backend_EmitLL:
949     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
950     break;
951 
952   default:
953     break;
954   }
955 
956   // Now that we have all of the passes ready, run them.
957   {
958     PrettyStackTraceString CrashInfo("Optimizer");
959     llvm::TimeTraceScope TimeScope("Optimizer");
960     MPM.run(*TheModule, MAM);
961   }
962 }
963 
964 void EmitAssemblyHelper::RunCodegenPipeline(
965     BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
966     std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
967   // We still use the legacy PM to run the codegen pipeline since the new PM
968   // does not work with the codegen pipeline.
969   // FIXME: make the new PM work with the codegen pipeline.
970   legacy::PassManager CodeGenPasses;
971 
972   // Append any output we need to the pass manager.
973   switch (Action) {
974   case Backend_EmitAssembly:
975   case Backend_EmitMCNull:
976   case Backend_EmitObj:
977     CodeGenPasses.add(
978         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
979     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
980       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
981       if (!DwoOS)
982         return;
983     }
984     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
985                        DwoOS ? &DwoOS->os() : nullptr))
986       // FIXME: Should we handle this error differently?
987       return;
988     break;
989   default:
990     return;
991   }
992 
993   {
994     PrettyStackTraceString CrashInfo("Code generation");
995     llvm::TimeTraceScope TimeScope("CodeGenPasses");
996     CodeGenPasses.run(*TheModule);
997   }
998 }
999 
1000 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
1001                                       std::unique_ptr<raw_pwrite_stream> OS) {
1002   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1003   setCommandLineOpts(CodeGenOpts);
1004 
1005   bool RequiresCodeGen = actionRequiresCodeGen(Action);
1006   CreateTargetMachine(RequiresCodeGen);
1007 
1008   if (RequiresCodeGen && !TM)
1009     return;
1010   if (TM)
1011     TheModule->setDataLayout(TM->createDataLayout());
1012 
1013   // Before executing passes, print the final values of the LLVM options.
1014   cl::PrintOptionValues();
1015 
1016   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1017   RunOptimizationPipeline(Action, OS, ThinLinkOS);
1018   RunCodegenPipeline(Action, OS, DwoOS);
1019 
1020   if (ThinLinkOS)
1021     ThinLinkOS->keep();
1022   if (DwoOS)
1023     DwoOS->keep();
1024 }
1025 
1026 static void runThinLTOBackend(
1027     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1028     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1029     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1030     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1031     std::string ProfileRemapping, BackendAction Action) {
1032   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1033       ModuleToDefinedGVSummaries;
1034   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1035 
1036   setCommandLineOpts(CGOpts);
1037 
1038   // We can simply import the values mentioned in the combined index, since
1039   // we should only invoke this using the individual indexes written out
1040   // via a WriteIndexesThinBackend.
1041   FunctionImporter::ImportMapTy ImportList;
1042   if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1043     return;
1044 
1045   auto AddStream = [&](size_t Task) {
1046     return std::make_unique<CachedFileStream>(std::move(OS),
1047                                               CGOpts.ObjectFilenameForDebug);
1048   };
1049   lto::Config Conf;
1050   if (CGOpts.SaveTempsFilePrefix != "") {
1051     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1052                                     /* UseInputModulePath */ false)) {
1053       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1054         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1055                << '\n';
1056       });
1057     }
1058   }
1059   Conf.CPU = TOpts.CPU;
1060   Conf.CodeModel = getCodeModel(CGOpts);
1061   Conf.MAttrs = TOpts.Features;
1062   Conf.RelocModel = CGOpts.RelocationModel;
1063   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1064   Conf.OptLevel = CGOpts.OptimizationLevel;
1065   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1066   Conf.SampleProfile = std::move(SampleProfile);
1067   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1068   // For historical reasons, loop interleaving is set to mirror setting for loop
1069   // unrolling.
1070   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1071   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1072   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1073   // Only enable CGProfilePass when using integrated assembler, since
1074   // non-integrated assemblers don't recognize .cgprofile section.
1075   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1076 
1077   // Context sensitive profile.
1078   if (CGOpts.hasProfileCSIRInstr()) {
1079     Conf.RunCSIRInstr = true;
1080     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1081   } else if (CGOpts.hasProfileCSIRUse()) {
1082     Conf.RunCSIRInstr = false;
1083     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1084   }
1085 
1086   Conf.ProfileRemapping = std::move(ProfileRemapping);
1087   Conf.DebugPassManager = CGOpts.DebugPassManager;
1088   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1089   Conf.RemarksFilename = CGOpts.OptRecordFile;
1090   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1091   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1092   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1093   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1094   switch (Action) {
1095   case Backend_EmitNothing:
1096     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1097       return false;
1098     };
1099     break;
1100   case Backend_EmitLL:
1101     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1102       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1103       return false;
1104     };
1105     break;
1106   case Backend_EmitBC:
1107     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1108       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1109       return false;
1110     };
1111     break;
1112   default:
1113     Conf.CGFileType = getCodeGenFileType(Action);
1114     break;
1115   }
1116   if (Error E =
1117           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1118                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1119                       /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1120     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1121       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1122     });
1123   }
1124 }
1125 
1126 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1127                               const HeaderSearchOptions &HeaderOpts,
1128                               const CodeGenOptions &CGOpts,
1129                               const clang::TargetOptions &TOpts,
1130                               const LangOptions &LOpts,
1131                               StringRef TDesc, Module *M,
1132                               BackendAction Action,
1133                               std::unique_ptr<raw_pwrite_stream> OS) {
1134 
1135   llvm::TimeTraceScope TimeScope("Backend");
1136 
1137   std::unique_ptr<llvm::Module> EmptyModule;
1138   if (!CGOpts.ThinLTOIndexFile.empty()) {
1139     // If we are performing a ThinLTO importing compile, load the function index
1140     // into memory and pass it into runThinLTOBackend, which will run the
1141     // function importer and invoke LTO passes.
1142     std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1143     if (Error E = llvm::getModuleSummaryIndexForFile(
1144                       CGOpts.ThinLTOIndexFile,
1145                       /*IgnoreEmptyThinLTOIndexFile*/ true)
1146                       .moveInto(CombinedIndex)) {
1147       logAllUnhandledErrors(std::move(E), errs(),
1148                             "Error loading index file '" +
1149                             CGOpts.ThinLTOIndexFile + "': ");
1150       return;
1151     }
1152 
1153     // A null CombinedIndex means we should skip ThinLTO compilation
1154     // (LLVM will optionally ignore empty index files, returning null instead
1155     // of an error).
1156     if (CombinedIndex) {
1157       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1158         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1159                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1160                           CGOpts.ProfileRemappingFile, Action);
1161         return;
1162       }
1163       // Distributed indexing detected that nothing from the module is needed
1164       // for the final linking. So we can skip the compilation. We sill need to
1165       // output an empty object file to make sure that a linker does not fail
1166       // trying to read it. Also for some features, like CFI, we must skip
1167       // the compilation as CombinedIndex does not contain all required
1168       // information.
1169       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1170       EmptyModule->setTargetTriple(M->getTargetTriple());
1171       M = EmptyModule.get();
1172     }
1173   }
1174 
1175   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1176   AsmHelper.EmitAssembly(Action, std::move(OS));
1177 
1178   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1179   // DataLayout.
1180   if (AsmHelper.TM) {
1181     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1182     if (DLDesc != TDesc) {
1183       unsigned DiagID = Diags.getCustomDiagID(
1184           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1185                                     "expected target description '%1'");
1186       Diags.Report(DiagID) << DLDesc << TDesc;
1187     }
1188   }
1189 }
1190 
1191 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1192 // __LLVM,__bitcode section.
1193 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1194                          llvm::MemoryBufferRef Buf) {
1195   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1196     return;
1197   llvm::embedBitcodeInModule(
1198       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1199       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1200       CGOpts.CmdArgs);
1201 }
1202 
1203 void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1204                         DiagnosticsEngine &Diags) {
1205   if (CGOpts.OffloadObjects.empty())
1206     return;
1207 
1208   for (StringRef OffloadObject : CGOpts.OffloadObjects) {
1209     if (OffloadObject.count(',') != 1)
1210       Diags.Report(Diags.getCustomDiagID(
1211           DiagnosticsEngine::Error, "Invalid string pair for embedding '%0'"))
1212           << OffloadObject;
1213     auto FilenameAndSection = OffloadObject.split(',');
1214     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1215         llvm::MemoryBuffer::getFileOrSTDIN(FilenameAndSection.first);
1216     if (std::error_code EC = ObjectOrErr.getError()) {
1217       auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1218                                           "could not open '%0' for embedding");
1219       Diags.Report(DiagID) << FilenameAndSection.first;
1220       return;
1221     }
1222 
1223     SmallString<128> SectionName(
1224         {".llvm.offloading.", FilenameAndSection.second});
1225     llvm::embedBufferInModule(*M, **ObjectOrErr, SectionName);
1226   }
1227 }
1228