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/Passes/PassBuilder.h"
42 #include "llvm/Passes/PassPlugin.h"
43 #include "llvm/Passes/StandardInstrumentations.h"
44 #include "llvm/Support/BuryPointer.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/PrettyStackTrace.h"
48 #include "llvm/Support/TargetRegistry.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/PassManagerBuilder.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/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/NameAnonGlobals.h"
87 #include "llvm/Transforms/Utils/SymbolRewriter.h"
88 #include <memory>
89 using namespace clang;
90 using namespace llvm;
91 
92 #define HANDLE_EXTENSION(Ext)                                                  \
93   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
94 #include "llvm/Support/Extension.def"
95 
96 namespace {
97 
98 // Default filename used for profile generation.
99 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
100 
101 class EmitAssemblyHelper {
102   DiagnosticsEngine &Diags;
103   const HeaderSearchOptions &HSOpts;
104   const CodeGenOptions &CodeGenOpts;
105   const clang::TargetOptions &TargetOpts;
106   const LangOptions &LangOpts;
107   Module *TheModule;
108 
109   Timer CodeGenerationTime;
110 
111   std::unique_ptr<raw_pwrite_stream> OS;
112 
113   TargetIRAnalysis getTargetIRAnalysis() const {
114     if (TM)
115       return TM->getTargetIRAnalysis();
116 
117     return TargetIRAnalysis();
118   }
119 
120   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
121 
122   /// Generates the TargetMachine.
123   /// Leaves TM unchanged if it is unable to create the target machine.
124   /// Some of our clang tests specify triples which are not built
125   /// into clang. This is okay because these tests check the generated
126   /// IR, and they require DataLayout which depends on the triple.
127   /// In this case, we allow this method to fail and not report an error.
128   /// When MustCreateTM is used, we print an error if we are unable to load
129   /// the requested target.
130   void CreateTargetMachine(bool MustCreateTM);
131 
132   /// Add passes necessary to emit assembly or LLVM IR.
133   ///
134   /// \return True on success.
135   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
136                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
137 
138   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
139     std::error_code EC;
140     auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
141                                                      llvm::sys::fs::OF_None);
142     if (EC) {
143       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
144       F.reset();
145     }
146     return F;
147   }
148 
149 public:
150   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
151                      const HeaderSearchOptions &HeaderSearchOpts,
152                      const CodeGenOptions &CGOpts,
153                      const clang::TargetOptions &TOpts,
154                      const LangOptions &LOpts, Module *M)
155       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
156         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
157         CodeGenerationTime("codegen", "Code Generation Time") {}
158 
159   ~EmitAssemblyHelper() {
160     if (CodeGenOpts.DisableFree)
161       BuryPointer(std::move(TM));
162   }
163 
164   std::unique_ptr<TargetMachine> TM;
165 
166   void EmitAssembly(BackendAction Action,
167                     std::unique_ptr<raw_pwrite_stream> OS);
168 
169   void EmitAssemblyWithNewPassManager(BackendAction Action,
170                                       std::unique_ptr<raw_pwrite_stream> OS);
171 };
172 
173 // We need this wrapper to access LangOpts and CGOpts from extension functions
174 // that we add to the PassManagerBuilder.
175 class PassManagerBuilderWrapper : public PassManagerBuilder {
176 public:
177   PassManagerBuilderWrapper(const Triple &TargetTriple,
178                             const CodeGenOptions &CGOpts,
179                             const LangOptions &LangOpts)
180       : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
181         LangOpts(LangOpts) {}
182   const Triple &getTargetTriple() const { return TargetTriple; }
183   const CodeGenOptions &getCGOpts() const { return CGOpts; }
184   const LangOptions &getLangOpts() const { return LangOpts; }
185 
186 private:
187   const Triple &TargetTriple;
188   const CodeGenOptions &CGOpts;
189   const LangOptions &LangOpts;
190 };
191 }
192 
193 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
194   if (Builder.OptLevel > 0)
195     PM.add(createObjCARCAPElimPass());
196 }
197 
198 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
199   if (Builder.OptLevel > 0)
200     PM.add(createObjCARCExpandPass());
201 }
202 
203 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
204   if (Builder.OptLevel > 0)
205     PM.add(createObjCARCOptPass());
206 }
207 
208 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
209                                      legacy::PassManagerBase &PM) {
210   PM.add(createAddDiscriminatorsPass());
211 }
212 
213 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
214                                   legacy::PassManagerBase &PM) {
215   PM.add(createBoundsCheckingLegacyPass());
216 }
217 
218 static SanitizerCoverageOptions
219 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
220   SanitizerCoverageOptions Opts;
221   Opts.CoverageType =
222       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
223   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
224   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
225   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
226   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
227   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
228   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
229   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
230   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
231   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
232   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
233   Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
234   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
235   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
236   return Opts;
237 }
238 
239 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
240                                      legacy::PassManagerBase &PM) {
241   const PassManagerBuilderWrapper &BuilderWrapper =
242       static_cast<const PassManagerBuilderWrapper &>(Builder);
243   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
244   auto Opts = getSancovOptsFromCGOpts(CGOpts);
245   PM.add(createModuleSanitizerCoverageLegacyPassPass(
246       Opts, CGOpts.SanitizeCoverageAllowlistFiles,
247       CGOpts.SanitizeCoverageIgnorelistFiles));
248 }
249 
250 // Check if ASan should use GC-friendly instrumentation for globals.
251 // First of all, there is no point if -fdata-sections is off (expect for MachO,
252 // where this is not a factor). Also, on ELF this feature requires an assembler
253 // extension that only works with -integrated-as at the moment.
254 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
255   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
256     return false;
257   switch (T.getObjectFormat()) {
258   case Triple::MachO:
259   case Triple::COFF:
260     return true;
261   case Triple::ELF:
262     return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
263   case Triple::GOFF:
264     llvm::report_fatal_error("ASan not implemented for GOFF");
265   case Triple::XCOFF:
266     llvm::report_fatal_error("ASan not implemented for XCOFF.");
267   case Triple::Wasm:
268   case Triple::UnknownObjectFormat:
269     break;
270   }
271   return false;
272 }
273 
274 static void addMemProfilerPasses(const PassManagerBuilder &Builder,
275                                  legacy::PassManagerBase &PM) {
276   PM.add(createMemProfilerFunctionPass());
277   PM.add(createModuleMemProfilerLegacyPassPass());
278 }
279 
280 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
281                                       legacy::PassManagerBase &PM) {
282   const PassManagerBuilderWrapper &BuilderWrapper =
283       static_cast<const PassManagerBuilderWrapper&>(Builder);
284   const Triple &T = BuilderWrapper.getTargetTriple();
285   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
286   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
287   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
288   bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
289   bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
290   llvm::AsanDtorKind DestructorKind = CGOpts.getSanitizeAddressDtor();
291   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
292                                             UseAfterScope));
293   PM.add(createModuleAddressSanitizerLegacyPassPass(
294       /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator,
295       DestructorKind));
296 }
297 
298 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
299                                             legacy::PassManagerBase &PM) {
300   PM.add(createAddressSanitizerFunctionPass(
301       /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
302   PM.add(createModuleAddressSanitizerLegacyPassPass(
303       /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
304       /*UseOdrIndicator*/ false));
305 }
306 
307 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
308                                             legacy::PassManagerBase &PM) {
309   const PassManagerBuilderWrapper &BuilderWrapper =
310       static_cast<const PassManagerBuilderWrapper &>(Builder);
311   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
312   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
313   PM.add(
314       createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
315 }
316 
317 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
318                                             legacy::PassManagerBase &PM) {
319   PM.add(createHWAddressSanitizerLegacyPassPass(
320       /*CompileKernel*/ true, /*Recover*/ true));
321 }
322 
323 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
324                                              legacy::PassManagerBase &PM,
325                                              bool CompileKernel) {
326   const PassManagerBuilderWrapper &BuilderWrapper =
327       static_cast<const PassManagerBuilderWrapper&>(Builder);
328   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
329   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
330   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
331   PM.add(createMemorySanitizerLegacyPassPass(
332       MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
333 
334   // MemorySanitizer inserts complex instrumentation that mostly follows
335   // the logic of the original code, but operates on "shadow" values.
336   // It can benefit from re-running some general purpose optimization passes.
337   if (Builder.OptLevel > 0) {
338     PM.add(createEarlyCSEPass());
339     PM.add(createReassociatePass());
340     PM.add(createLICMPass());
341     PM.add(createGVNPass());
342     PM.add(createInstructionCombiningPass());
343     PM.add(createDeadStoreEliminationPass());
344   }
345 }
346 
347 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
348                                    legacy::PassManagerBase &PM) {
349   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
350 }
351 
352 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
353                                          legacy::PassManagerBase &PM) {
354   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
355 }
356 
357 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
358                                    legacy::PassManagerBase &PM) {
359   PM.add(createThreadSanitizerLegacyPassPass());
360 }
361 
362 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
363                                      legacy::PassManagerBase &PM) {
364   const PassManagerBuilderWrapper &BuilderWrapper =
365       static_cast<const PassManagerBuilderWrapper&>(Builder);
366   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
367   PM.add(createDataFlowSanitizerLegacyPassPass(LangOpts.NoSanitizeFiles));
368 }
369 
370 static void addEntryExitInstrumentationPass(const PassManagerBuilder &Builder,
371                                             legacy::PassManagerBase &PM) {
372   PM.add(createEntryExitInstrumenterPass());
373 }
374 
375 static void
376 addPostInlineEntryExitInstrumentationPass(const PassManagerBuilder &Builder,
377                                           legacy::PassManagerBase &PM) {
378   PM.add(createPostInlineEntryExitInstrumenterPass());
379 }
380 
381 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
382                                          const CodeGenOptions &CodeGenOpts) {
383   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
384 
385   switch (CodeGenOpts.getVecLib()) {
386   case CodeGenOptions::Accelerate:
387     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
388     break;
389   case CodeGenOptions::LIBMVEC:
390     switch(TargetTriple.getArch()) {
391       default:
392         break;
393       case llvm::Triple::x86_64:
394         TLII->addVectorizableFunctionsFromVecLib
395                 (TargetLibraryInfoImpl::LIBMVEC_X86);
396         break;
397     }
398     break;
399   case CodeGenOptions::MASSV:
400     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
401     break;
402   case CodeGenOptions::SVML:
403     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
404     break;
405   default:
406     break;
407   }
408   return TLII;
409 }
410 
411 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
412                                   legacy::PassManager *MPM) {
413   llvm::SymbolRewriter::RewriteDescriptorList DL;
414 
415   llvm::SymbolRewriter::RewriteMapParser MapParser;
416   for (const auto &MapFile : Opts.RewriteMapFiles)
417     MapParser.parse(MapFile, &DL);
418 
419   MPM->add(createRewriteSymbolsPass(DL));
420 }
421 
422 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
423   switch (CodeGenOpts.OptimizationLevel) {
424   default:
425     llvm_unreachable("Invalid optimization level!");
426   case 0:
427     return CodeGenOpt::None;
428   case 1:
429     return CodeGenOpt::Less;
430   case 2:
431     return CodeGenOpt::Default; // O2/Os/Oz
432   case 3:
433     return CodeGenOpt::Aggressive;
434   }
435 }
436 
437 static Optional<llvm::CodeModel::Model>
438 getCodeModel(const CodeGenOptions &CodeGenOpts) {
439   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
440                            .Case("tiny", llvm::CodeModel::Tiny)
441                            .Case("small", llvm::CodeModel::Small)
442                            .Case("kernel", llvm::CodeModel::Kernel)
443                            .Case("medium", llvm::CodeModel::Medium)
444                            .Case("large", llvm::CodeModel::Large)
445                            .Case("default", ~1u)
446                            .Default(~0u);
447   assert(CodeModel != ~0u && "invalid code model!");
448   if (CodeModel == ~1u)
449     return None;
450   return static_cast<llvm::CodeModel::Model>(CodeModel);
451 }
452 
453 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
454   if (Action == Backend_EmitObj)
455     return CGFT_ObjectFile;
456   else if (Action == Backend_EmitMCNull)
457     return CGFT_Null;
458   else {
459     assert(Action == Backend_EmitAssembly && "Invalid action!");
460     return CGFT_AssemblyFile;
461   }
462 }
463 
464 static bool initTargetOptions(DiagnosticsEngine &Diags,
465                               llvm::TargetOptions &Options,
466                               const CodeGenOptions &CodeGenOpts,
467                               const clang::TargetOptions &TargetOpts,
468                               const LangOptions &LangOpts,
469                               const HeaderSearchOptions &HSOpts) {
470   switch (LangOpts.getThreadModel()) {
471   case LangOptions::ThreadModelKind::POSIX:
472     Options.ThreadModel = llvm::ThreadModel::POSIX;
473     break;
474   case LangOptions::ThreadModelKind::Single:
475     Options.ThreadModel = llvm::ThreadModel::Single;
476     break;
477   }
478 
479   // Set float ABI type.
480   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
481           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
482          "Invalid Floating Point ABI!");
483   Options.FloatABIType =
484       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
485           .Case("soft", llvm::FloatABI::Soft)
486           .Case("softfp", llvm::FloatABI::Soft)
487           .Case("hard", llvm::FloatABI::Hard)
488           .Default(llvm::FloatABI::Default);
489 
490   // Set FP fusion mode.
491   switch (LangOpts.getDefaultFPContractMode()) {
492   case LangOptions::FPM_Off:
493     // Preserve any contraction performed by the front-end.  (Strict performs
494     // splitting of the muladd intrinsic in the backend.)
495     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
496     break;
497   case LangOptions::FPM_On:
498   case LangOptions::FPM_FastHonorPragmas:
499     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
500     break;
501   case LangOptions::FPM_Fast:
502     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
503     break;
504   }
505 
506   Options.BinutilsVersion =
507       llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
508   Options.UseInitArray = CodeGenOpts.UseInitArray;
509   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
510   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
511   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
512 
513   // Set EABI version.
514   Options.EABIVersion = TargetOpts.EABIVersion;
515 
516   if (LangOpts.hasSjLjExceptions())
517     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
518   if (LangOpts.hasSEHExceptions())
519     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
520   if (LangOpts.hasDWARFExceptions())
521     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
522   if (LangOpts.hasWasmExceptions())
523     Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
524 
525   Options.NoInfsFPMath = LangOpts.NoHonorInfs;
526   Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
527   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
528   Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
529   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
530 
531   Options.BBSections =
532       llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
533           .Case("all", llvm::BasicBlockSection::All)
534           .Case("labels", llvm::BasicBlockSection::Labels)
535           .StartsWith("list=", llvm::BasicBlockSection::List)
536           .Case("none", llvm::BasicBlockSection::None)
537           .Default(llvm::BasicBlockSection::None);
538 
539   if (Options.BBSections == llvm::BasicBlockSection::List) {
540     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
541         MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
542     if (!MBOrErr) {
543       Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
544           << MBOrErr.getError().message();
545       return false;
546     }
547     Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
548   }
549 
550   Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
551   Options.FunctionSections = CodeGenOpts.FunctionSections;
552   Options.DataSections = CodeGenOpts.DataSections;
553   Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
554   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
555   Options.UniqueBasicBlockSectionNames =
556       CodeGenOpts.UniqueBasicBlockSectionNames;
557   Options.StackProtectorGuard =
558       llvm::StringSwitch<llvm::StackProtectorGuards>(CodeGenOpts
559           .StackProtectorGuard)
560           .Case("tls", llvm::StackProtectorGuards::TLS)
561           .Case("global", llvm::StackProtectorGuards::Global)
562           .Default(llvm::StackProtectorGuards::None);
563   Options.StackProtectorGuardOffset = CodeGenOpts.StackProtectorGuardOffset;
564   Options.StackProtectorGuardReg = CodeGenOpts.StackProtectorGuardReg;
565   Options.TLSSize = CodeGenOpts.TLSSize;
566   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
567   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
568   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
569   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
570   Options.EmitAddrsig = CodeGenOpts.Addrsig;
571   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
572   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
573   Options.EnableAIXExtendedAltivecABI = CodeGenOpts.EnableAIXExtendedAltivecABI;
574   Options.PseudoProbeForProfiling = CodeGenOpts.PseudoProbeForProfiling;
575   Options.ValueTrackingVariableLocations =
576       CodeGenOpts.ValueTrackingVariableLocations;
577   Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
578 
579   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
580   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
581   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
582   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
583   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
584   Options.MCOptions.MCIncrementalLinkerCompatible =
585       CodeGenOpts.IncrementalLinkerCompatible;
586   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
587   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
588   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
589   Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
590   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
591   Options.MCOptions.ABIName = TargetOpts.ABI;
592   for (const auto &Entry : HSOpts.UserEntries)
593     if (!Entry.IsFramework &&
594         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
595          Entry.Group == frontend::IncludeDirGroup::Angled ||
596          Entry.Group == frontend::IncludeDirGroup::System))
597       Options.MCOptions.IASSearchPaths.push_back(
598           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
599   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
600   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
601   Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
602 
603   return true;
604 }
605 
606 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
607                                             const LangOptions &LangOpts) {
608   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
609     return None;
610   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
611   // LLVM's -default-gcov-version flag is set to something invalid.
612   GCOVOptions Options;
613   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
614   Options.EmitData = CodeGenOpts.EmitGcovArcs;
615   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
616   Options.NoRedZone = CodeGenOpts.DisableRedZone;
617   Options.Filter = CodeGenOpts.ProfileFilterFiles;
618   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
619   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
620   return Options;
621 }
622 
623 static Optional<InstrProfOptions>
624 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
625                     const LangOptions &LangOpts) {
626   if (!CodeGenOpts.hasProfileClangInstr())
627     return None;
628   InstrProfOptions Options;
629   Options.NoRedZone = CodeGenOpts.DisableRedZone;
630   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
631   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
632   return Options;
633 }
634 
635 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
636                                       legacy::FunctionPassManager &FPM) {
637   // Handle disabling of all LLVM passes, where we want to preserve the
638   // internal module before any optimization.
639   if (CodeGenOpts.DisableLLVMPasses)
640     return;
641 
642   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
643   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
644   // are inserted before PMBuilder ones - they'd get the default-constructed
645   // TLI with an unknown target otherwise.
646   Triple TargetTriple(TheModule->getTargetTriple());
647   std::unique_ptr<TargetLibraryInfoImpl> TLII(
648       createTLII(TargetTriple, CodeGenOpts));
649 
650   // If we reached here with a non-empty index file name, then the index file
651   // was empty and we are not performing ThinLTO backend compilation (used in
652   // testing in a distributed build environment). Drop any the type test
653   // assume sequences inserted for whole program vtables so that codegen doesn't
654   // complain.
655   if (!CodeGenOpts.ThinLTOIndexFile.empty())
656     MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
657                                      /*ImportSummary=*/nullptr,
658                                      /*DropTypeTests=*/true));
659 
660   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
661 
662   // At O0 and O1 we only run the always inliner which is more efficient. At
663   // higher optimization levels we run the normal inliner.
664   if (CodeGenOpts.OptimizationLevel <= 1) {
665     bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
666                                       !CodeGenOpts.DisableLifetimeMarkers) ||
667                                      LangOpts.Coroutines);
668     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
669   } else {
670     // We do not want to inline hot callsites for SamplePGO module-summary build
671     // because profile annotation will happen again in ThinLTO backend, and we
672     // want the IR of the hot path to match the profile.
673     PMBuilder.Inliner = createFunctionInliningPass(
674         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
675         (!CodeGenOpts.SampleProfileFile.empty() &&
676          CodeGenOpts.PrepareForThinLTO));
677   }
678 
679   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
680   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
681   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
682   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
683   // Only enable CGProfilePass when using integrated assembler, since
684   // non-integrated assemblers don't recognize .cgprofile section.
685   PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
686 
687   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
688   // Loop interleaving in the loop vectorizer has historically been set to be
689   // enabled when loop unrolling is enabled.
690   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
691   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
692   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
693   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
694   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
695 
696   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
697 
698   if (TM)
699     TM->adjustPassManager(PMBuilder);
700 
701   if (CodeGenOpts.DebugInfoForProfiling ||
702       !CodeGenOpts.SampleProfileFile.empty())
703     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
704                            addAddDiscriminatorsPass);
705 
706   // In ObjC ARC mode, add the main ARC optimization passes.
707   if (LangOpts.ObjCAutoRefCount) {
708     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
709                            addObjCARCExpandPass);
710     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
711                            addObjCARCAPElimPass);
712     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
713                            addObjCARCOptPass);
714   }
715 
716   if (LangOpts.Coroutines)
717     addCoroutinePassesToExtensionPoints(PMBuilder);
718 
719   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
720     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
721                            addMemProfilerPasses);
722     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
723                            addMemProfilerPasses);
724   }
725 
726   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
727     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
728                            addBoundsCheckingPass);
729     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
730                            addBoundsCheckingPass);
731   }
732 
733   if (CodeGenOpts.SanitizeCoverageType ||
734       CodeGenOpts.SanitizeCoverageIndirectCalls ||
735       CodeGenOpts.SanitizeCoverageTraceCmp) {
736     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
737                            addSanitizerCoveragePass);
738     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
739                            addSanitizerCoveragePass);
740   }
741 
742   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
743     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
744                            addAddressSanitizerPasses);
745     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
746                            addAddressSanitizerPasses);
747   }
748 
749   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
750     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
751                            addKernelAddressSanitizerPasses);
752     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
753                            addKernelAddressSanitizerPasses);
754   }
755 
756   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
757     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
758                            addHWAddressSanitizerPasses);
759     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
760                            addHWAddressSanitizerPasses);
761   }
762 
763   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
764     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
765                            addKernelHWAddressSanitizerPasses);
766     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
767                            addKernelHWAddressSanitizerPasses);
768   }
769 
770   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
771     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
772                            addMemorySanitizerPass);
773     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
774                            addMemorySanitizerPass);
775   }
776 
777   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
778     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
779                            addKernelMemorySanitizerPass);
780     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
781                            addKernelMemorySanitizerPass);
782   }
783 
784   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
785     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
786                            addThreadSanitizerPass);
787     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
788                            addThreadSanitizerPass);
789   }
790 
791   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
792     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
793                            addDataFlowSanitizerPass);
794     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
795                            addDataFlowSanitizerPass);
796   }
797 
798   if (CodeGenOpts.InstrumentFunctions ||
799       CodeGenOpts.InstrumentFunctionEntryBare ||
800       CodeGenOpts.InstrumentFunctionsAfterInlining ||
801       CodeGenOpts.InstrumentForProfiling) {
802     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
803                            addEntryExitInstrumentationPass);
804     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
805                            addEntryExitInstrumentationPass);
806     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
807                            addPostInlineEntryExitInstrumentationPass);
808     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
809                            addPostInlineEntryExitInstrumentationPass);
810   }
811 
812   // Set up the per-function pass manager.
813   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
814   if (CodeGenOpts.VerifyModule)
815     FPM.add(createVerifierPass());
816 
817   // Set up the per-module pass manager.
818   if (!CodeGenOpts.RewriteMapFiles.empty())
819     addSymbolRewriterPass(CodeGenOpts, &MPM);
820 
821   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) {
822     MPM.add(createGCOVProfilerPass(*Options));
823     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
824       MPM.add(createStripSymbolsPass(true));
825   }
826 
827   if (Optional<InstrProfOptions> Options =
828           getInstrProfOptions(CodeGenOpts, LangOpts))
829     MPM.add(createInstrProfilingLegacyPass(*Options, false));
830 
831   bool hasIRInstr = false;
832   if (CodeGenOpts.hasProfileIRInstr()) {
833     PMBuilder.EnablePGOInstrGen = true;
834     hasIRInstr = true;
835   }
836   if (CodeGenOpts.hasProfileCSIRInstr()) {
837     assert(!CodeGenOpts.hasProfileCSIRUse() &&
838            "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
839            "same time");
840     assert(!hasIRInstr &&
841            "Cannot have both ProfileGen pass and CSProfileGen pass at the "
842            "same time");
843     PMBuilder.EnablePGOCSInstrGen = true;
844     hasIRInstr = true;
845   }
846   if (hasIRInstr) {
847     if (!CodeGenOpts.InstrProfileOutput.empty())
848       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
849     else
850       PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
851   }
852   if (CodeGenOpts.hasProfileIRUse()) {
853     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
854     PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
855   }
856 
857   if (!CodeGenOpts.SampleProfileFile.empty())
858     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
859 
860   PMBuilder.populateFunctionPassManager(FPM);
861   PMBuilder.populateModulePassManager(MPM);
862 }
863 
864 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
865   SmallVector<const char *, 16> BackendArgs;
866   BackendArgs.push_back("clang"); // Fake program name.
867   if (!CodeGenOpts.DebugPass.empty()) {
868     BackendArgs.push_back("-debug-pass");
869     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
870     // New PM supports structure dumping. Old PM is still used for codegen,
871     // so we need to pass both options.
872     if (!CodeGenOpts.LegacyPassManager && CodeGenOpts.DebugPass == "Structure")
873       BackendArgs.push_back("-debug-pass-structure");
874   }
875   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
876     BackendArgs.push_back("-limit-float-precision");
877     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
878   }
879   // Check for the default "clang" invocation that won't set any cl::opt values.
880   // Skip trying to parse the command line invocation to avoid the issues
881   // described below.
882   if (BackendArgs.size() == 1)
883     return;
884   BackendArgs.push_back(nullptr);
885   // FIXME: The command line parser below is not thread-safe and shares a global
886   // state, so this call might crash or overwrite the options of another Clang
887   // instance in the same process.
888   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
889                                     BackendArgs.data());
890 }
891 
892 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
893   // Create the TargetMachine for generating code.
894   std::string Error;
895   std::string Triple = TheModule->getTargetTriple();
896   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
897   if (!TheTarget) {
898     if (MustCreateTM)
899       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
900     return;
901   }
902 
903   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
904   std::string FeaturesStr =
905       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
906   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
907   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
908 
909   llvm::TargetOptions Options;
910   if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
911                          HSOpts))
912     return;
913   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
914                                           Options, RM, CM, OptLevel));
915 }
916 
917 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
918                                        BackendAction Action,
919                                        raw_pwrite_stream &OS,
920                                        raw_pwrite_stream *DwoOS) {
921   // Add LibraryInfo.
922   llvm::Triple TargetTriple(TheModule->getTargetTriple());
923   std::unique_ptr<TargetLibraryInfoImpl> TLII(
924       createTLII(TargetTriple, CodeGenOpts));
925   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
926 
927   // Normal mode, emit a .s or .o file by running the code generator. Note,
928   // this also adds codegenerator level optimization passes.
929   CodeGenFileType CGFT = getCodeGenFileType(Action);
930 
931   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
932   // "codegen" passes so that it isn't run multiple times when there is
933   // inlining happening.
934   if (CodeGenOpts.OptimizationLevel > 0)
935     CodeGenPasses.add(createObjCARCContractPass());
936 
937   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
938                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
939     Diags.Report(diag::err_fe_unable_to_interface_with_target);
940     return false;
941   }
942 
943   return true;
944 }
945 
946 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
947                                       std::unique_ptr<raw_pwrite_stream> OS) {
948   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
949 
950   setCommandLineOpts(CodeGenOpts);
951 
952   bool UsesCodeGen = (Action != Backend_EmitNothing &&
953                       Action != Backend_EmitBC &&
954                       Action != Backend_EmitLL);
955   CreateTargetMachine(UsesCodeGen);
956 
957   if (UsesCodeGen && !TM)
958     return;
959   if (TM)
960     TheModule->setDataLayout(TM->createDataLayout());
961 
962   DebugifyCustomPassManager PerModulePasses;
963   DebugInfoPerPassMap DIPreservationMap;
964   if (CodeGenOpts.EnableDIPreservationVerify) {
965     PerModulePasses.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
966     PerModulePasses.setDIPreservationMap(DIPreservationMap);
967 
968     if (!CodeGenOpts.DIBugsReportFilePath.empty())
969       PerModulePasses.setOrigDIVerifyBugsReportFilePath(
970           CodeGenOpts.DIBugsReportFilePath);
971   }
972   PerModulePasses.add(
973       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
974 
975   legacy::FunctionPassManager PerFunctionPasses(TheModule);
976   PerFunctionPasses.add(
977       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
978 
979   CreatePasses(PerModulePasses, PerFunctionPasses);
980 
981   legacy::PassManager CodeGenPasses;
982   CodeGenPasses.add(
983       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
984 
985   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
986 
987   switch (Action) {
988   case Backend_EmitNothing:
989     break;
990 
991   case Backend_EmitBC:
992     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
993       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
994         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
995         if (!ThinLinkOS)
996           return;
997       }
998       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
999                                CodeGenOpts.EnableSplitLTOUnit);
1000       PerModulePasses.add(createWriteThinLTOBitcodePass(
1001           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
1002     } else {
1003       // Emit a module summary by default for Regular LTO except for ld64
1004       // targets
1005       bool EmitLTOSummary =
1006           (CodeGenOpts.PrepareForLTO &&
1007            !CodeGenOpts.DisableLLVMPasses &&
1008            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1009                llvm::Triple::Apple);
1010       if (EmitLTOSummary) {
1011         if (!TheModule->getModuleFlag("ThinLTO"))
1012           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1013         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1014                                  uint32_t(1));
1015       }
1016 
1017       PerModulePasses.add(createBitcodeWriterPass(
1018           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1019     }
1020     break;
1021 
1022   case Backend_EmitLL:
1023     PerModulePasses.add(
1024         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1025     break;
1026 
1027   default:
1028     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1029       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1030       if (!DwoOS)
1031         return;
1032     }
1033     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1034                        DwoOS ? &DwoOS->os() : nullptr))
1035       return;
1036   }
1037 
1038   // Before executing passes, print the final values of the LLVM options.
1039   cl::PrintOptionValues();
1040 
1041   // Run passes. For now we do all passes at once, but eventually we
1042   // would like to have the option of streaming code generation.
1043 
1044   {
1045     PrettyStackTraceString CrashInfo("Per-function optimization");
1046     llvm::TimeTraceScope TimeScope("PerFunctionPasses");
1047 
1048     PerFunctionPasses.doInitialization();
1049     for (Function &F : *TheModule)
1050       if (!F.isDeclaration())
1051         PerFunctionPasses.run(F);
1052     PerFunctionPasses.doFinalization();
1053   }
1054 
1055   {
1056     PrettyStackTraceString CrashInfo("Per-module optimization passes");
1057     llvm::TimeTraceScope TimeScope("PerModulePasses");
1058     PerModulePasses.run(*TheModule);
1059   }
1060 
1061   {
1062     PrettyStackTraceString CrashInfo("Code generation");
1063     llvm::TimeTraceScope TimeScope("CodeGenPasses");
1064     CodeGenPasses.run(*TheModule);
1065   }
1066 
1067   if (ThinLinkOS)
1068     ThinLinkOS->keep();
1069   if (DwoOS)
1070     DwoOS->keep();
1071 }
1072 
1073 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
1074   switch (Opts.OptimizationLevel) {
1075   default:
1076     llvm_unreachable("Invalid optimization level!");
1077 
1078   case 0:
1079     return PassBuilder::OptimizationLevel::O0;
1080 
1081   case 1:
1082     return PassBuilder::OptimizationLevel::O1;
1083 
1084   case 2:
1085     switch (Opts.OptimizeSize) {
1086     default:
1087       llvm_unreachable("Invalid optimization level for size!");
1088 
1089     case 0:
1090       return PassBuilder::OptimizationLevel::O2;
1091 
1092     case 1:
1093       return PassBuilder::OptimizationLevel::Os;
1094 
1095     case 2:
1096       return PassBuilder::OptimizationLevel::Oz;
1097     }
1098 
1099   case 3:
1100     return PassBuilder::OptimizationLevel::O3;
1101   }
1102 }
1103 
1104 static void addSanitizers(const Triple &TargetTriple,
1105                           const CodeGenOptions &CodeGenOpts,
1106                           const LangOptions &LangOpts, PassBuilder &PB) {
1107   PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
1108                                          PassBuilder::OptimizationLevel Level) {
1109     if (CodeGenOpts.SanitizeCoverageType ||
1110         CodeGenOpts.SanitizeCoverageIndirectCalls ||
1111         CodeGenOpts.SanitizeCoverageTraceCmp) {
1112       auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1113       MPM.addPass(ModuleSanitizerCoveragePass(
1114           SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1115           CodeGenOpts.SanitizeCoverageIgnorelistFiles));
1116     }
1117 
1118     auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1119       if (LangOpts.Sanitize.has(Mask)) {
1120         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1121         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1122 
1123         MPM.addPass(
1124             MemorySanitizerPass({TrackOrigins, Recover, CompileKernel}));
1125         FunctionPassManager FPM;
1126         FPM.addPass(
1127             MemorySanitizerPass({TrackOrigins, Recover, CompileKernel}));
1128         if (Level != PassBuilder::OptimizationLevel::O0) {
1129           // MemorySanitizer inserts complex instrumentation that mostly
1130           // follows the logic of the original code, but operates on
1131           // "shadow" values. It can benefit from re-running some
1132           // general purpose optimization passes.
1133           FPM.addPass(EarlyCSEPass());
1134           // TODO: Consider add more passes like in
1135           // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible
1136           // difference on size. It's not clear if the rest is still
1137           // usefull. InstCombinePass breakes
1138           // compiler-rt/test/msan/select_origin.cpp.
1139         }
1140         MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1141       }
1142     };
1143     MSanPass(SanitizerKind::Memory, false);
1144     MSanPass(SanitizerKind::KernelMemory, true);
1145 
1146     if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1147       MPM.addPass(ThreadSanitizerPass());
1148       MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1149     }
1150 
1151     auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1152       if (LangOpts.Sanitize.has(Mask)) {
1153         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1154         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1155         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1156         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1157         llvm::AsanDtorKind DestructorKind =
1158             CodeGenOpts.getSanitizeAddressDtor();
1159         MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1160         MPM.addPass(ModuleAddressSanitizerPass(
1161             CompileKernel, Recover, ModuleUseAfterScope, UseOdrIndicator,
1162             DestructorKind));
1163         MPM.addPass(createModuleToFunctionPassAdaptor(
1164             AddressSanitizerPass(CompileKernel, Recover, UseAfterScope)));
1165       }
1166     };
1167     ASanPass(SanitizerKind::Address, false);
1168     ASanPass(SanitizerKind::KernelAddress, true);
1169 
1170     auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1171       if (LangOpts.Sanitize.has(Mask)) {
1172         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1173         MPM.addPass(HWAddressSanitizerPass(CompileKernel, Recover));
1174       }
1175     };
1176     HWASanPass(SanitizerKind::HWAddress, false);
1177     HWASanPass(SanitizerKind::KernelHWAddress, true);
1178 
1179     if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
1180       MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
1181     }
1182   });
1183 }
1184 
1185 /// A clean version of `EmitAssembly` that uses the new pass manager.
1186 ///
1187 /// Not all features are currently supported in this system, but where
1188 /// necessary it falls back to the legacy pass manager to at least provide
1189 /// basic functionality.
1190 ///
1191 /// This API is planned to have its functionality finished and then to replace
1192 /// `EmitAssembly` at some point in the future when the default switches.
1193 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1194     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1195   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1196   setCommandLineOpts(CodeGenOpts);
1197 
1198   bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1199                           Action != Backend_EmitBC &&
1200                           Action != Backend_EmitLL);
1201   CreateTargetMachine(RequiresCodeGen);
1202 
1203   if (RequiresCodeGen && !TM)
1204     return;
1205   if (TM)
1206     TheModule->setDataLayout(TM->createDataLayout());
1207 
1208   Optional<PGOOptions> PGOOpt;
1209 
1210   if (CodeGenOpts.hasProfileIRInstr())
1211     // -fprofile-generate.
1212     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1213                             ? std::string(DefaultProfileGenName)
1214                             : CodeGenOpts.InstrProfileOutput,
1215                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1216                         CodeGenOpts.DebugInfoForProfiling);
1217   else if (CodeGenOpts.hasProfileIRUse()) {
1218     // -fprofile-use.
1219     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1220                                                     : PGOOptions::NoCSAction;
1221     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1222                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1223                         CSAction, CodeGenOpts.DebugInfoForProfiling);
1224   } else if (!CodeGenOpts.SampleProfileFile.empty())
1225     // -fprofile-sample-use
1226     PGOOpt = PGOOptions(
1227         CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
1228         PGOOptions::SampleUse, PGOOptions::NoCSAction,
1229         CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
1230   else if (CodeGenOpts.PseudoProbeForProfiling)
1231     // -fpseudo-probe-for-profiling
1232     PGOOpt =
1233         PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
1234                    CodeGenOpts.DebugInfoForProfiling, true);
1235   else if (CodeGenOpts.DebugInfoForProfiling)
1236     // -fdebug-info-for-profiling
1237     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1238                         PGOOptions::NoCSAction, true);
1239 
1240   // Check to see if we want to generate a CS profile.
1241   if (CodeGenOpts.hasProfileCSIRInstr()) {
1242     assert(!CodeGenOpts.hasProfileCSIRUse() &&
1243            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1244            "the same time");
1245     if (PGOOpt.hasValue()) {
1246       assert(PGOOpt->Action != PGOOptions::IRInstr &&
1247              PGOOpt->Action != PGOOptions::SampleUse &&
1248              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1249              " pass");
1250       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1251                                      ? std::string(DefaultProfileGenName)
1252                                      : CodeGenOpts.InstrProfileOutput;
1253       PGOOpt->CSAction = PGOOptions::CSIRInstr;
1254     } else
1255       PGOOpt = PGOOptions("",
1256                           CodeGenOpts.InstrProfileOutput.empty()
1257                               ? std::string(DefaultProfileGenName)
1258                               : CodeGenOpts.InstrProfileOutput,
1259                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1260                           CodeGenOpts.DebugInfoForProfiling);
1261   }
1262 
1263   PipelineTuningOptions PTO;
1264   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1265   // For historical reasons, loop interleaving is set to mirror setting for loop
1266   // unrolling.
1267   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1268   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1269   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1270   PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
1271   // Only enable CGProfilePass when using integrated assembler, since
1272   // non-integrated assemblers don't recognize .cgprofile section.
1273   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
1274   PTO.Coroutines = LangOpts.Coroutines;
1275 
1276   LoopAnalysisManager LAM;
1277   FunctionAnalysisManager FAM;
1278   CGSCCAnalysisManager CGAM;
1279   ModuleAnalysisManager MAM;
1280 
1281   PassInstrumentationCallbacks PIC;
1282   StandardInstrumentations SI(CodeGenOpts.DebugPassManager);
1283   SI.registerCallbacks(PIC, &FAM);
1284   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1285 
1286   // Attempt to load pass plugins and register their callbacks with PB.
1287   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1288     auto PassPlugin = PassPlugin::Load(PluginFN);
1289     if (PassPlugin) {
1290       PassPlugin->registerPassBuilderCallbacks(PB);
1291     } else {
1292       Diags.Report(diag::err_fe_unable_to_load_plugin)
1293           << PluginFN << toString(PassPlugin.takeError());
1294     }
1295   }
1296 #define HANDLE_EXTENSION(Ext)                                                  \
1297   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1298 #include "llvm/Support/Extension.def"
1299 
1300   // Register the AA manager first so that our version is the one used.
1301   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1302 
1303   // Register the target library analysis directly and give it a customized
1304   // preset TLI.
1305   Triple TargetTriple(TheModule->getTargetTriple());
1306   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1307       createTLII(TargetTriple, CodeGenOpts));
1308   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1309 
1310   // Register all the basic analyses with the managers.
1311   PB.registerModuleAnalyses(MAM);
1312   PB.registerCGSCCAnalyses(CGAM);
1313   PB.registerFunctionAnalyses(FAM);
1314   PB.registerLoopAnalyses(LAM);
1315   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1316 
1317   ModulePassManager MPM;
1318 
1319   if (!CodeGenOpts.DisableLLVMPasses) {
1320     // Map our optimization levels into one of the distinct levels used to
1321     // configure the pipeline.
1322     PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1323 
1324     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1325     bool IsLTO = CodeGenOpts.PrepareForLTO;
1326 
1327     if (LangOpts.ObjCAutoRefCount) {
1328       PB.registerPipelineStartEPCallback(
1329           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1330             if (Level != PassBuilder::OptimizationLevel::O0)
1331               MPM.addPass(
1332                   createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1333           });
1334       PB.registerPipelineEarlySimplificationEPCallback(
1335           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1336             if (Level != PassBuilder::OptimizationLevel::O0)
1337               MPM.addPass(ObjCARCAPElimPass());
1338           });
1339       PB.registerScalarOptimizerLateEPCallback(
1340           [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1341             if (Level != PassBuilder::OptimizationLevel::O0)
1342               FPM.addPass(ObjCARCOptPass());
1343           });
1344     }
1345 
1346     // If we reached here with a non-empty index file name, then the index
1347     // file was empty and we are not performing ThinLTO backend compilation
1348     // (used in testing in a distributed build environment).
1349     bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
1350     // If so drop any the type test assume sequences inserted for whole program
1351     // vtables so that codegen doesn't complain.
1352     if (IsThinLTOPostLink)
1353       PB.registerPipelineStartEPCallback(
1354           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1355             MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1356                                            /*ImportSummary=*/nullptr,
1357                                            /*DropTypeTests=*/true));
1358           });
1359 
1360     if (CodeGenOpts.InstrumentFunctions ||
1361         CodeGenOpts.InstrumentFunctionEntryBare ||
1362         CodeGenOpts.InstrumentFunctionsAfterInlining ||
1363         CodeGenOpts.InstrumentForProfiling) {
1364       PB.registerPipelineStartEPCallback(
1365           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1366             MPM.addPass(createModuleToFunctionPassAdaptor(
1367                 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1368           });
1369       PB.registerOptimizerLastEPCallback(
1370           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1371             MPM.addPass(createModuleToFunctionPassAdaptor(
1372                 EntryExitInstrumenterPass(/*PostInlining=*/true)));
1373           });
1374     }
1375 
1376     // Register callbacks to schedule sanitizer passes at the appropriate part
1377     // of the pipeline.
1378     if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1379       PB.registerScalarOptimizerLateEPCallback(
1380           [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1381             FPM.addPass(BoundsCheckingPass());
1382           });
1383 
1384     // Don't add sanitizers if we are here from ThinLTO PostLink. That already
1385     // done on PreLink stage.
1386     if (!IsThinLTOPostLink)
1387       addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
1388 
1389     if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1390       PB.registerPipelineStartEPCallback(
1391           [Options](ModulePassManager &MPM,
1392                     PassBuilder::OptimizationLevel Level) {
1393             MPM.addPass(GCOVProfilerPass(*Options));
1394           });
1395     if (Optional<InstrProfOptions> Options =
1396             getInstrProfOptions(CodeGenOpts, LangOpts))
1397       PB.registerPipelineStartEPCallback(
1398           [Options](ModulePassManager &MPM,
1399                     PassBuilder::OptimizationLevel Level) {
1400             MPM.addPass(InstrProfiling(*Options, false));
1401           });
1402 
1403     if (CodeGenOpts.OptimizationLevel == 0) {
1404       MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO);
1405     } else if (IsThinLTO) {
1406       MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
1407     } else if (IsLTO) {
1408       MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
1409     } else {
1410       MPM = PB.buildPerModuleDefaultPipeline(Level);
1411     }
1412 
1413     if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1414       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1415       MPM.addPass(ModuleMemProfilerPass());
1416     }
1417   }
1418 
1419   // FIXME: We still use the legacy pass manager to do code generation. We
1420   // create that pass manager here and use it as needed below.
1421   legacy::PassManager CodeGenPasses;
1422   bool NeedCodeGen = false;
1423   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1424 
1425   // Append any output we need to the pass manager.
1426   switch (Action) {
1427   case Backend_EmitNothing:
1428     break;
1429 
1430   case Backend_EmitBC:
1431     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1432       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1433         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1434         if (!ThinLinkOS)
1435           return;
1436       }
1437       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1438                                CodeGenOpts.EnableSplitLTOUnit);
1439       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1440                                                            : nullptr));
1441     } else {
1442       // Emit a module summary by default for Regular LTO except for ld64
1443       // targets
1444       bool EmitLTOSummary =
1445           (CodeGenOpts.PrepareForLTO &&
1446            !CodeGenOpts.DisableLLVMPasses &&
1447            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1448                llvm::Triple::Apple);
1449       if (EmitLTOSummary) {
1450         if (!TheModule->getModuleFlag("ThinLTO"))
1451           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1452         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1453                                  uint32_t(1));
1454       }
1455       MPM.addPass(
1456           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1457     }
1458     break;
1459 
1460   case Backend_EmitLL:
1461     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1462     break;
1463 
1464   case Backend_EmitAssembly:
1465   case Backend_EmitMCNull:
1466   case Backend_EmitObj:
1467     NeedCodeGen = true;
1468     CodeGenPasses.add(
1469         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1470     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1471       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1472       if (!DwoOS)
1473         return;
1474     }
1475     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1476                        DwoOS ? &DwoOS->os() : nullptr))
1477       // FIXME: Should we handle this error differently?
1478       return;
1479     break;
1480   }
1481 
1482   // Before executing passes, print the final values of the LLVM options.
1483   cl::PrintOptionValues();
1484 
1485   // Now that we have all of the passes ready, run them.
1486   {
1487     PrettyStackTraceString CrashInfo("Optimizer");
1488     MPM.run(*TheModule, MAM);
1489   }
1490 
1491   // Now if needed, run the legacy PM for codegen.
1492   if (NeedCodeGen) {
1493     PrettyStackTraceString CrashInfo("Code generation");
1494     CodeGenPasses.run(*TheModule);
1495   }
1496 
1497   if (ThinLinkOS)
1498     ThinLinkOS->keep();
1499   if (DwoOS)
1500     DwoOS->keep();
1501 }
1502 
1503 static void runThinLTOBackend(
1504     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1505     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1506     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1507     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1508     std::string ProfileRemapping, BackendAction Action) {
1509   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1510       ModuleToDefinedGVSummaries;
1511   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1512 
1513   setCommandLineOpts(CGOpts);
1514 
1515   // We can simply import the values mentioned in the combined index, since
1516   // we should only invoke this using the individual indexes written out
1517   // via a WriteIndexesThinBackend.
1518   FunctionImporter::ImportMapTy ImportList;
1519   if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1520     return;
1521 
1522   auto AddStream = [&](size_t Task) {
1523     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1524   };
1525   lto::Config Conf;
1526   if (CGOpts.SaveTempsFilePrefix != "") {
1527     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1528                                     /* UseInputModulePath */ false)) {
1529       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1530         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1531                << '\n';
1532       });
1533     }
1534   }
1535   Conf.CPU = TOpts.CPU;
1536   Conf.CodeModel = getCodeModel(CGOpts);
1537   Conf.MAttrs = TOpts.Features;
1538   Conf.RelocModel = CGOpts.RelocationModel;
1539   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1540   Conf.OptLevel = CGOpts.OptimizationLevel;
1541   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1542   Conf.SampleProfile = std::move(SampleProfile);
1543   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1544   // For historical reasons, loop interleaving is set to mirror setting for loop
1545   // unrolling.
1546   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1547   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1548   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1549   // Only enable CGProfilePass when using integrated assembler, since
1550   // non-integrated assemblers don't recognize .cgprofile section.
1551   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1552 
1553   // Context sensitive profile.
1554   if (CGOpts.hasProfileCSIRInstr()) {
1555     Conf.RunCSIRInstr = true;
1556     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1557   } else if (CGOpts.hasProfileCSIRUse()) {
1558     Conf.RunCSIRInstr = false;
1559     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1560   }
1561 
1562   Conf.ProfileRemapping = std::move(ProfileRemapping);
1563   Conf.UseNewPM = !CGOpts.LegacyPassManager;
1564   Conf.DebugPassManager = CGOpts.DebugPassManager;
1565   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1566   Conf.RemarksFilename = CGOpts.OptRecordFile;
1567   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1568   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1569   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1570   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1571   switch (Action) {
1572   case Backend_EmitNothing:
1573     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1574       return false;
1575     };
1576     break;
1577   case Backend_EmitLL:
1578     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1579       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1580       return false;
1581     };
1582     break;
1583   case Backend_EmitBC:
1584     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1585       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1586       return false;
1587     };
1588     break;
1589   default:
1590     Conf.CGFileType = getCodeGenFileType(Action);
1591     break;
1592   }
1593   if (Error E =
1594           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1595                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1596                       /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1597     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1598       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1599     });
1600   }
1601 }
1602 
1603 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1604                               const HeaderSearchOptions &HeaderOpts,
1605                               const CodeGenOptions &CGOpts,
1606                               const clang::TargetOptions &TOpts,
1607                               const LangOptions &LOpts,
1608                               StringRef TDesc, Module *M,
1609                               BackendAction Action,
1610                               std::unique_ptr<raw_pwrite_stream> OS) {
1611 
1612   llvm::TimeTraceScope TimeScope("Backend");
1613 
1614   std::unique_ptr<llvm::Module> EmptyModule;
1615   if (!CGOpts.ThinLTOIndexFile.empty()) {
1616     // If we are performing a ThinLTO importing compile, load the function index
1617     // into memory and pass it into runThinLTOBackend, which will run the
1618     // function importer and invoke LTO passes.
1619     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1620         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1621                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1622     if (!IndexOrErr) {
1623       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1624                             "Error loading index file '" +
1625                             CGOpts.ThinLTOIndexFile + "': ");
1626       return;
1627     }
1628     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1629     // A null CombinedIndex means we should skip ThinLTO compilation
1630     // (LLVM will optionally ignore empty index files, returning null instead
1631     // of an error).
1632     if (CombinedIndex) {
1633       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1634         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1635                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1636                           CGOpts.ProfileRemappingFile, Action);
1637         return;
1638       }
1639       // Distributed indexing detected that nothing from the module is needed
1640       // for the final linking. So we can skip the compilation. We sill need to
1641       // output an empty object file to make sure that a linker does not fail
1642       // trying to read it. Also for some features, like CFI, we must skip
1643       // the compilation as CombinedIndex does not contain all required
1644       // information.
1645       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1646       EmptyModule->setTargetTriple(M->getTargetTriple());
1647       M = EmptyModule.get();
1648     }
1649   }
1650 
1651   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1652 
1653   if (!CGOpts.LegacyPassManager)
1654     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1655   else
1656     AsmHelper.EmitAssembly(Action, std::move(OS));
1657 
1658   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1659   // DataLayout.
1660   if (AsmHelper.TM) {
1661     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1662     if (DLDesc != TDesc) {
1663       unsigned DiagID = Diags.getCustomDiagID(
1664           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1665                                     "expected target description '%1'");
1666       Diags.Report(DiagID) << DLDesc << TDesc;
1667     }
1668   }
1669 }
1670 
1671 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1672 // __LLVM,__bitcode section.
1673 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1674                          llvm::MemoryBufferRef Buf) {
1675   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1676     return;
1677   llvm::EmbedBitcodeInModule(
1678       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1679       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1680       CGOpts.CmdArgs);
1681 }
1682