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