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.SanitizeCoverageBlocklistFiles));
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.getSanitizeAddressDtorKind();
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 
602   return true;
603 }
604 
605 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
606                                             const LangOptions &LangOpts) {
607   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
608     return None;
609   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
610   // LLVM's -default-gcov-version flag is set to something invalid.
611   GCOVOptions Options;
612   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
613   Options.EmitData = CodeGenOpts.EmitGcovArcs;
614   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
615   Options.NoRedZone = CodeGenOpts.DisableRedZone;
616   Options.Filter = CodeGenOpts.ProfileFilterFiles;
617   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
618   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
619   return Options;
620 }
621 
622 static Optional<InstrProfOptions>
623 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
624                     const LangOptions &LangOpts) {
625   if (!CodeGenOpts.hasProfileClangInstr())
626     return None;
627   InstrProfOptions Options;
628   Options.NoRedZone = CodeGenOpts.DisableRedZone;
629   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
630   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
631   return Options;
632 }
633 
634 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
635                                       legacy::FunctionPassManager &FPM) {
636   // Handle disabling of all LLVM passes, where we want to preserve the
637   // internal module before any optimization.
638   if (CodeGenOpts.DisableLLVMPasses)
639     return;
640 
641   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
642   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
643   // are inserted before PMBuilder ones - they'd get the default-constructed
644   // TLI with an unknown target otherwise.
645   Triple TargetTriple(TheModule->getTargetTriple());
646   std::unique_ptr<TargetLibraryInfoImpl> TLII(
647       createTLII(TargetTriple, CodeGenOpts));
648 
649   // If we reached here with a non-empty index file name, then the index file
650   // was empty and we are not performing ThinLTO backend compilation (used in
651   // testing in a distributed build environment). Drop any the type test
652   // assume sequences inserted for whole program vtables so that codegen doesn't
653   // complain.
654   if (!CodeGenOpts.ThinLTOIndexFile.empty())
655     MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
656                                      /*ImportSummary=*/nullptr,
657                                      /*DropTypeTests=*/true));
658 
659   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
660 
661   // At O0 and O1 we only run the always inliner which is more efficient. At
662   // higher optimization levels we run the normal inliner.
663   if (CodeGenOpts.OptimizationLevel <= 1) {
664     bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
665                                       !CodeGenOpts.DisableLifetimeMarkers) ||
666                                      LangOpts.Coroutines);
667     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
668   } else {
669     // We do not want to inline hot callsites for SamplePGO module-summary build
670     // because profile annotation will happen again in ThinLTO backend, and we
671     // want the IR of the hot path to match the profile.
672     PMBuilder.Inliner = createFunctionInliningPass(
673         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
674         (!CodeGenOpts.SampleProfileFile.empty() &&
675          CodeGenOpts.PrepareForThinLTO));
676   }
677 
678   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
679   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
680   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
681   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
682   // Only enable CGProfilePass when using integrated assembler, since
683   // non-integrated assemblers don't recognize .cgprofile section.
684   PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
685 
686   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
687   // Loop interleaving in the loop vectorizer has historically been set to be
688   // enabled when loop unrolling is enabled.
689   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
690   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
691   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
692   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
693   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
694 
695   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
696 
697   if (TM)
698     TM->adjustPassManager(PMBuilder);
699 
700   if (CodeGenOpts.DebugInfoForProfiling ||
701       !CodeGenOpts.SampleProfileFile.empty())
702     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
703                            addAddDiscriminatorsPass);
704 
705   // In ObjC ARC mode, add the main ARC optimization passes.
706   if (LangOpts.ObjCAutoRefCount) {
707     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
708                            addObjCARCExpandPass);
709     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
710                            addObjCARCAPElimPass);
711     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
712                            addObjCARCOptPass);
713   }
714 
715   if (LangOpts.Coroutines)
716     addCoroutinePassesToExtensionPoints(PMBuilder);
717 
718   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
719     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
720                            addMemProfilerPasses);
721     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
722                            addMemProfilerPasses);
723   }
724 
725   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
726     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
727                            addBoundsCheckingPass);
728     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
729                            addBoundsCheckingPass);
730   }
731 
732   if (CodeGenOpts.SanitizeCoverageType ||
733       CodeGenOpts.SanitizeCoverageIndirectCalls ||
734       CodeGenOpts.SanitizeCoverageTraceCmp) {
735     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
736                            addSanitizerCoveragePass);
737     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
738                            addSanitizerCoveragePass);
739   }
740 
741   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
742     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
743                            addAddressSanitizerPasses);
744     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
745                            addAddressSanitizerPasses);
746   }
747 
748   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
749     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
750                            addKernelAddressSanitizerPasses);
751     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
752                            addKernelAddressSanitizerPasses);
753   }
754 
755   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
756     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
757                            addHWAddressSanitizerPasses);
758     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
759                            addHWAddressSanitizerPasses);
760   }
761 
762   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
763     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
764                            addKernelHWAddressSanitizerPasses);
765     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
766                            addKernelHWAddressSanitizerPasses);
767   }
768 
769   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
770     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
771                            addMemorySanitizerPass);
772     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
773                            addMemorySanitizerPass);
774   }
775 
776   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
777     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
778                            addKernelMemorySanitizerPass);
779     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
780                            addKernelMemorySanitizerPass);
781   }
782 
783   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
784     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
785                            addThreadSanitizerPass);
786     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
787                            addThreadSanitizerPass);
788   }
789 
790   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
791     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
792                            addDataFlowSanitizerPass);
793     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
794                            addDataFlowSanitizerPass);
795   }
796 
797   if (CodeGenOpts.InstrumentFunctions ||
798       CodeGenOpts.InstrumentFunctionEntryBare ||
799       CodeGenOpts.InstrumentFunctionsAfterInlining ||
800       CodeGenOpts.InstrumentForProfiling) {
801     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
802                            addEntryExitInstrumentationPass);
803     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
804                            addEntryExitInstrumentationPass);
805     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
806                            addPostInlineEntryExitInstrumentationPass);
807     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
808                            addPostInlineEntryExitInstrumentationPass);
809   }
810 
811   // Set up the per-function pass manager.
812   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
813   if (CodeGenOpts.VerifyModule)
814     FPM.add(createVerifierPass());
815 
816   // Set up the per-module pass manager.
817   if (!CodeGenOpts.RewriteMapFiles.empty())
818     addSymbolRewriterPass(CodeGenOpts, &MPM);
819 
820   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) {
821     MPM.add(createGCOVProfilerPass(*Options));
822     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
823       MPM.add(createStripSymbolsPass(true));
824   }
825 
826   if (Optional<InstrProfOptions> Options =
827           getInstrProfOptions(CodeGenOpts, LangOpts))
828     MPM.add(createInstrProfilingLegacyPass(*Options, false));
829 
830   bool hasIRInstr = false;
831   if (CodeGenOpts.hasProfileIRInstr()) {
832     PMBuilder.EnablePGOInstrGen = true;
833     hasIRInstr = true;
834   }
835   if (CodeGenOpts.hasProfileCSIRInstr()) {
836     assert(!CodeGenOpts.hasProfileCSIRUse() &&
837            "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
838            "same time");
839     assert(!hasIRInstr &&
840            "Cannot have both ProfileGen pass and CSProfileGen pass at the "
841            "same time");
842     PMBuilder.EnablePGOCSInstrGen = true;
843     hasIRInstr = true;
844   }
845   if (hasIRInstr) {
846     if (!CodeGenOpts.InstrProfileOutput.empty())
847       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
848     else
849       PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
850   }
851   if (CodeGenOpts.hasProfileIRUse()) {
852     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
853     PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
854   }
855 
856   if (!CodeGenOpts.SampleProfileFile.empty())
857     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
858 
859   PMBuilder.populateFunctionPassManager(FPM);
860   PMBuilder.populateModulePassManager(MPM);
861 }
862 
863 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
864   SmallVector<const char *, 16> BackendArgs;
865   BackendArgs.push_back("clang"); // Fake program name.
866   if (!CodeGenOpts.DebugPass.empty()) {
867     BackendArgs.push_back("-debug-pass");
868     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
869   }
870   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
871     BackendArgs.push_back("-limit-float-precision");
872     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
873   }
874   // Check for the default "clang" invocation that won't set any cl::opt values.
875   // Skip trying to parse the command line invocation to avoid the issues
876   // described below.
877   if (BackendArgs.size() == 1)
878     return;
879   BackendArgs.push_back(nullptr);
880   // FIXME: The command line parser below is not thread-safe and shares a global
881   // state, so this call might crash or overwrite the options of another Clang
882   // instance in the same process.
883   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
884                                     BackendArgs.data());
885 }
886 
887 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
888   // Create the TargetMachine for generating code.
889   std::string Error;
890   std::string Triple = TheModule->getTargetTriple();
891   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
892   if (!TheTarget) {
893     if (MustCreateTM)
894       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
895     return;
896   }
897 
898   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
899   std::string FeaturesStr =
900       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
901   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
902   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
903 
904   llvm::TargetOptions Options;
905   if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
906                          HSOpts))
907     return;
908   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
909                                           Options, RM, CM, OptLevel));
910 }
911 
912 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
913                                        BackendAction Action,
914                                        raw_pwrite_stream &OS,
915                                        raw_pwrite_stream *DwoOS) {
916   // Add LibraryInfo.
917   llvm::Triple TargetTriple(TheModule->getTargetTriple());
918   std::unique_ptr<TargetLibraryInfoImpl> TLII(
919       createTLII(TargetTriple, CodeGenOpts));
920   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
921 
922   // Normal mode, emit a .s or .o file by running the code generator. Note,
923   // this also adds codegenerator level optimization passes.
924   CodeGenFileType CGFT = getCodeGenFileType(Action);
925 
926   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
927   // "codegen" passes so that it isn't run multiple times when there is
928   // inlining happening.
929   if (CodeGenOpts.OptimizationLevel > 0)
930     CodeGenPasses.add(createObjCARCContractPass());
931 
932   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
933                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
934     Diags.Report(diag::err_fe_unable_to_interface_with_target);
935     return false;
936   }
937 
938   return true;
939 }
940 
941 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
942                                       std::unique_ptr<raw_pwrite_stream> OS) {
943   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
944 
945   setCommandLineOpts(CodeGenOpts);
946 
947   bool UsesCodeGen = (Action != Backend_EmitNothing &&
948                       Action != Backend_EmitBC &&
949                       Action != Backend_EmitLL);
950   CreateTargetMachine(UsesCodeGen);
951 
952   if (UsesCodeGen && !TM)
953     return;
954   if (TM)
955     TheModule->setDataLayout(TM->createDataLayout());
956 
957   DebugifyCustomPassManager PerModulePasses;
958   DebugInfoPerPassMap DIPreservationMap;
959   if (CodeGenOpts.EnableDIPreservationVerify) {
960     PerModulePasses.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
961     PerModulePasses.setDIPreservationMap(DIPreservationMap);
962 
963     if (!CodeGenOpts.DIBugsReportFilePath.empty())
964       PerModulePasses.setOrigDIVerifyBugsReportFilePath(
965           CodeGenOpts.DIBugsReportFilePath);
966   }
967   PerModulePasses.add(
968       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
969 
970   legacy::FunctionPassManager PerFunctionPasses(TheModule);
971   PerFunctionPasses.add(
972       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
973 
974   CreatePasses(PerModulePasses, PerFunctionPasses);
975 
976   legacy::PassManager CodeGenPasses;
977   CodeGenPasses.add(
978       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
979 
980   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
981 
982   switch (Action) {
983   case Backend_EmitNothing:
984     break;
985 
986   case Backend_EmitBC:
987     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
988       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
989         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
990         if (!ThinLinkOS)
991           return;
992       }
993       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
994                                CodeGenOpts.EnableSplitLTOUnit);
995       PerModulePasses.add(createWriteThinLTOBitcodePass(
996           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
997     } else {
998       // Emit a module summary by default for Regular LTO except for ld64
999       // targets
1000       bool EmitLTOSummary =
1001           (CodeGenOpts.PrepareForLTO &&
1002            !CodeGenOpts.DisableLLVMPasses &&
1003            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1004                llvm::Triple::Apple);
1005       if (EmitLTOSummary) {
1006         if (!TheModule->getModuleFlag("ThinLTO"))
1007           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1008         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1009                                  uint32_t(1));
1010       }
1011 
1012       PerModulePasses.add(createBitcodeWriterPass(
1013           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1014     }
1015     break;
1016 
1017   case Backend_EmitLL:
1018     PerModulePasses.add(
1019         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1020     break;
1021 
1022   default:
1023     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1024       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1025       if (!DwoOS)
1026         return;
1027     }
1028     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1029                        DwoOS ? &DwoOS->os() : nullptr))
1030       return;
1031   }
1032 
1033   // Before executing passes, print the final values of the LLVM options.
1034   cl::PrintOptionValues();
1035 
1036   // Run passes. For now we do all passes at once, but eventually we
1037   // would like to have the option of streaming code generation.
1038 
1039   {
1040     PrettyStackTraceString CrashInfo("Per-function optimization");
1041     llvm::TimeTraceScope TimeScope("PerFunctionPasses");
1042 
1043     PerFunctionPasses.doInitialization();
1044     for (Function &F : *TheModule)
1045       if (!F.isDeclaration())
1046         PerFunctionPasses.run(F);
1047     PerFunctionPasses.doFinalization();
1048   }
1049 
1050   {
1051     PrettyStackTraceString CrashInfo("Per-module optimization passes");
1052     llvm::TimeTraceScope TimeScope("PerModulePasses");
1053     PerModulePasses.run(*TheModule);
1054   }
1055 
1056   {
1057     PrettyStackTraceString CrashInfo("Code generation");
1058     llvm::TimeTraceScope TimeScope("CodeGenPasses");
1059     CodeGenPasses.run(*TheModule);
1060   }
1061 
1062   if (ThinLinkOS)
1063     ThinLinkOS->keep();
1064   if (DwoOS)
1065     DwoOS->keep();
1066 }
1067 
1068 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
1069   switch (Opts.OptimizationLevel) {
1070   default:
1071     llvm_unreachable("Invalid optimization level!");
1072 
1073   case 0:
1074     return PassBuilder::OptimizationLevel::O0;
1075 
1076   case 1:
1077     return PassBuilder::OptimizationLevel::O1;
1078 
1079   case 2:
1080     switch (Opts.OptimizeSize) {
1081     default:
1082       llvm_unreachable("Invalid optimization level for size!");
1083 
1084     case 0:
1085       return PassBuilder::OptimizationLevel::O2;
1086 
1087     case 1:
1088       return PassBuilder::OptimizationLevel::Os;
1089 
1090     case 2:
1091       return PassBuilder::OptimizationLevel::Oz;
1092     }
1093 
1094   case 3:
1095     return PassBuilder::OptimizationLevel::O3;
1096   }
1097 }
1098 
1099 static void addSanitizers(const Triple &TargetTriple,
1100                           const CodeGenOptions &CodeGenOpts,
1101                           const LangOptions &LangOpts, PassBuilder &PB) {
1102   PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
1103                                          PassBuilder::OptimizationLevel Level) {
1104     if (CodeGenOpts.SanitizeCoverageType ||
1105         CodeGenOpts.SanitizeCoverageIndirectCalls ||
1106         CodeGenOpts.SanitizeCoverageTraceCmp) {
1107       auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1108       MPM.addPass(ModuleSanitizerCoveragePass(
1109           SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1110           CodeGenOpts.SanitizeCoverageBlocklistFiles));
1111     }
1112 
1113     auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1114       if (LangOpts.Sanitize.has(Mask)) {
1115         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1116         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1117 
1118         MPM.addPass(
1119             MemorySanitizerPass({TrackOrigins, Recover, CompileKernel}));
1120         FunctionPassManager FPM(CodeGenOpts.DebugPassManager);
1121         FPM.addPass(
1122             MemorySanitizerPass({TrackOrigins, Recover, CompileKernel}));
1123         if (Level != PassBuilder::OptimizationLevel::O0) {
1124           // MemorySanitizer inserts complex instrumentation that mostly
1125           // follows the logic of the original code, but operates on
1126           // "shadow" values. It can benefit from re-running some
1127           // general purpose optimization passes.
1128           FPM.addPass(EarlyCSEPass());
1129           // TODO: Consider add more passes like in
1130           // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible
1131           // difference on size. It's not clear if the rest is still
1132           // usefull. InstCombinePass breakes
1133           // compiler-rt/test/msan/select_origin.cpp.
1134         }
1135         MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1136       }
1137     };
1138     MSanPass(SanitizerKind::Memory, false);
1139     MSanPass(SanitizerKind::KernelMemory, true);
1140 
1141     if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1142       MPM.addPass(ThreadSanitizerPass());
1143       MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1144     }
1145 
1146     auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1147       if (LangOpts.Sanitize.has(Mask)) {
1148         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1149         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1150         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1151         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1152         llvm::AsanDtorKind DestructorKind =
1153             CodeGenOpts.getSanitizeAddressDtorKind();
1154         MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1155         MPM.addPass(ModuleAddressSanitizerPass(
1156             CompileKernel, Recover, ModuleUseAfterScope, UseOdrIndicator,
1157             DestructorKind));
1158         MPM.addPass(createModuleToFunctionPassAdaptor(
1159             AddressSanitizerPass(CompileKernel, Recover, UseAfterScope)));
1160       }
1161     };
1162     ASanPass(SanitizerKind::Address, false);
1163     ASanPass(SanitizerKind::KernelAddress, true);
1164 
1165     auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1166       if (LangOpts.Sanitize.has(Mask)) {
1167         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1168         MPM.addPass(HWAddressSanitizerPass(CompileKernel, Recover));
1169       }
1170     };
1171     HWASanPass(SanitizerKind::HWAddress, false);
1172     HWASanPass(SanitizerKind::KernelHWAddress, true);
1173 
1174     if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
1175       MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
1176     }
1177   });
1178 }
1179 
1180 /// A clean version of `EmitAssembly` that uses the new pass manager.
1181 ///
1182 /// Not all features are currently supported in this system, but where
1183 /// necessary it falls back to the legacy pass manager to at least provide
1184 /// basic functionality.
1185 ///
1186 /// This API is planned to have its functionality finished and then to replace
1187 /// `EmitAssembly` at some point in the future when the default switches.
1188 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1189     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1190   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1191   setCommandLineOpts(CodeGenOpts);
1192 
1193   bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1194                           Action != Backend_EmitBC &&
1195                           Action != Backend_EmitLL);
1196   CreateTargetMachine(RequiresCodeGen);
1197 
1198   if (RequiresCodeGen && !TM)
1199     return;
1200   if (TM)
1201     TheModule->setDataLayout(TM->createDataLayout());
1202 
1203   Optional<PGOOptions> PGOOpt;
1204 
1205   if (CodeGenOpts.hasProfileIRInstr())
1206     // -fprofile-generate.
1207     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1208                             ? std::string(DefaultProfileGenName)
1209                             : CodeGenOpts.InstrProfileOutput,
1210                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1211                         CodeGenOpts.DebugInfoForProfiling);
1212   else if (CodeGenOpts.hasProfileIRUse()) {
1213     // -fprofile-use.
1214     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1215                                                     : PGOOptions::NoCSAction;
1216     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1217                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1218                         CSAction, CodeGenOpts.DebugInfoForProfiling);
1219   } else if (!CodeGenOpts.SampleProfileFile.empty())
1220     // -fprofile-sample-use
1221     PGOOpt = PGOOptions(
1222         CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
1223         PGOOptions::SampleUse, PGOOptions::NoCSAction,
1224         CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
1225   else if (CodeGenOpts.PseudoProbeForProfiling)
1226     // -fpseudo-probe-for-profiling
1227     PGOOpt =
1228         PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
1229                    CodeGenOpts.DebugInfoForProfiling, true);
1230   else if (CodeGenOpts.DebugInfoForProfiling)
1231     // -fdebug-info-for-profiling
1232     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1233                         PGOOptions::NoCSAction, true);
1234 
1235   // Check to see if we want to generate a CS profile.
1236   if (CodeGenOpts.hasProfileCSIRInstr()) {
1237     assert(!CodeGenOpts.hasProfileCSIRUse() &&
1238            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1239            "the same time");
1240     if (PGOOpt.hasValue()) {
1241       assert(PGOOpt->Action != PGOOptions::IRInstr &&
1242              PGOOpt->Action != PGOOptions::SampleUse &&
1243              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1244              " pass");
1245       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1246                                      ? std::string(DefaultProfileGenName)
1247                                      : CodeGenOpts.InstrProfileOutput;
1248       PGOOpt->CSAction = PGOOptions::CSIRInstr;
1249     } else
1250       PGOOpt = PGOOptions("",
1251                           CodeGenOpts.InstrProfileOutput.empty()
1252                               ? std::string(DefaultProfileGenName)
1253                               : CodeGenOpts.InstrProfileOutput,
1254                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1255                           CodeGenOpts.DebugInfoForProfiling);
1256   }
1257 
1258   PipelineTuningOptions PTO;
1259   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1260   // For historical reasons, loop interleaving is set to mirror setting for loop
1261   // unrolling.
1262   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1263   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1264   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1265   PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
1266   // Only enable CGProfilePass when using integrated assembler, since
1267   // non-integrated assemblers don't recognize .cgprofile section.
1268   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
1269   PTO.Coroutines = LangOpts.Coroutines;
1270 
1271   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1272   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1273   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1274   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1275 
1276   PassInstrumentationCallbacks PIC;
1277   StandardInstrumentations SI(CodeGenOpts.DebugPassManager);
1278   SI.registerCallbacks(PIC, &FAM);
1279   PassBuilder PB(CodeGenOpts.DebugPassManager, TM.get(), PTO, PGOOpt, &PIC);
1280 
1281   // Attempt to load pass plugins and register their callbacks with PB.
1282   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1283     auto PassPlugin = PassPlugin::Load(PluginFN);
1284     if (PassPlugin) {
1285       PassPlugin->registerPassBuilderCallbacks(PB);
1286     } else {
1287       Diags.Report(diag::err_fe_unable_to_load_plugin)
1288           << PluginFN << toString(PassPlugin.takeError());
1289     }
1290   }
1291 #define HANDLE_EXTENSION(Ext)                                                  \
1292   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1293 #include "llvm/Support/Extension.def"
1294 
1295   // Register the AA manager first so that our version is the one used.
1296   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1297 
1298   // Register the target library analysis directly and give it a customized
1299   // preset TLI.
1300   Triple TargetTriple(TheModule->getTargetTriple());
1301   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1302       createTLII(TargetTriple, CodeGenOpts));
1303   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1304 
1305   // Register all the basic analyses with the managers.
1306   PB.registerModuleAnalyses(MAM);
1307   PB.registerCGSCCAnalyses(CGAM);
1308   PB.registerFunctionAnalyses(FAM);
1309   PB.registerLoopAnalyses(LAM);
1310   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1311 
1312   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1313 
1314   if (!CodeGenOpts.DisableLLVMPasses) {
1315     // Map our optimization levels into one of the distinct levels used to
1316     // configure the pipeline.
1317     PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1318 
1319     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1320     bool IsLTO = CodeGenOpts.PrepareForLTO;
1321 
1322     if (LangOpts.ObjCAutoRefCount) {
1323       PB.registerPipelineStartEPCallback(
1324           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1325             if (Level != PassBuilder::OptimizationLevel::O0)
1326               MPM.addPass(
1327                   createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1328           });
1329       PB.registerPipelineEarlySimplificationEPCallback(
1330           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1331             if (Level != PassBuilder::OptimizationLevel::O0)
1332               MPM.addPass(ObjCARCAPElimPass());
1333           });
1334       PB.registerScalarOptimizerLateEPCallback(
1335           [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1336             if (Level != PassBuilder::OptimizationLevel::O0)
1337               FPM.addPass(ObjCARCOptPass());
1338           });
1339     }
1340 
1341     // If we reached here with a non-empty index file name, then the index
1342     // file was empty and we are not performing ThinLTO backend compilation
1343     // (used in testing in a distributed build environment).
1344     bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
1345     // If so drop any the type test assume sequences inserted for whole program
1346     // vtables so that codegen doesn't complain.
1347     if (IsThinLTOPostLink)
1348       PB.registerPipelineStartEPCallback(
1349           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1350             MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1351                                            /*ImportSummary=*/nullptr,
1352                                            /*DropTypeTests=*/true));
1353           });
1354 
1355     if (CodeGenOpts.InstrumentFunctions ||
1356         CodeGenOpts.InstrumentFunctionEntryBare ||
1357         CodeGenOpts.InstrumentFunctionsAfterInlining ||
1358         CodeGenOpts.InstrumentForProfiling) {
1359       PB.registerPipelineStartEPCallback(
1360           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1361             MPM.addPass(createModuleToFunctionPassAdaptor(
1362                 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1363           });
1364       PB.registerOptimizerLastEPCallback(
1365           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1366             MPM.addPass(createModuleToFunctionPassAdaptor(
1367                 EntryExitInstrumenterPass(/*PostInlining=*/true)));
1368           });
1369     }
1370 
1371     // Register callbacks to schedule sanitizer passes at the appropriate part
1372     // of the pipeline.
1373     if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1374       PB.registerScalarOptimizerLateEPCallback(
1375           [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1376             FPM.addPass(BoundsCheckingPass());
1377           });
1378 
1379     // Don't add sanitizers if we are here from ThinLTO PostLink. That already
1380     // done on PreLink stage.
1381     if (!IsThinLTOPostLink)
1382       addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
1383 
1384     if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1385       PB.registerPipelineStartEPCallback(
1386           [Options](ModulePassManager &MPM,
1387                     PassBuilder::OptimizationLevel Level) {
1388             MPM.addPass(GCOVProfilerPass(*Options));
1389           });
1390     if (Optional<InstrProfOptions> Options =
1391             getInstrProfOptions(CodeGenOpts, LangOpts))
1392       PB.registerPipelineStartEPCallback(
1393           [Options](ModulePassManager &MPM,
1394                     PassBuilder::OptimizationLevel Level) {
1395             MPM.addPass(InstrProfiling(*Options, false));
1396           });
1397 
1398     if (CodeGenOpts.OptimizationLevel == 0) {
1399       MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO);
1400     } else if (IsThinLTO) {
1401       MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
1402     } else if (IsLTO) {
1403       MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
1404     } else {
1405       MPM = PB.buildPerModuleDefaultPipeline(Level);
1406     }
1407 
1408     if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1409       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1410       MPM.addPass(ModuleMemProfilerPass());
1411     }
1412   }
1413 
1414   // FIXME: We still use the legacy pass manager to do code generation. We
1415   // create that pass manager here and use it as needed below.
1416   legacy::PassManager CodeGenPasses;
1417   bool NeedCodeGen = false;
1418   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1419 
1420   // Append any output we need to the pass manager.
1421   switch (Action) {
1422   case Backend_EmitNothing:
1423     break;
1424 
1425   case Backend_EmitBC:
1426     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1427       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1428         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1429         if (!ThinLinkOS)
1430           return;
1431       }
1432       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1433                                CodeGenOpts.EnableSplitLTOUnit);
1434       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1435                                                            : nullptr));
1436     } else {
1437       // Emit a module summary by default for Regular LTO except for ld64
1438       // targets
1439       bool EmitLTOSummary =
1440           (CodeGenOpts.PrepareForLTO &&
1441            !CodeGenOpts.DisableLLVMPasses &&
1442            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1443                llvm::Triple::Apple);
1444       if (EmitLTOSummary) {
1445         if (!TheModule->getModuleFlag("ThinLTO"))
1446           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1447         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1448                                  uint32_t(1));
1449       }
1450       MPM.addPass(
1451           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1452     }
1453     break;
1454 
1455   case Backend_EmitLL:
1456     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1457     break;
1458 
1459   case Backend_EmitAssembly:
1460   case Backend_EmitMCNull:
1461   case Backend_EmitObj:
1462     NeedCodeGen = true;
1463     CodeGenPasses.add(
1464         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1465     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1466       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1467       if (!DwoOS)
1468         return;
1469     }
1470     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1471                        DwoOS ? &DwoOS->os() : nullptr))
1472       // FIXME: Should we handle this error differently?
1473       return;
1474     break;
1475   }
1476 
1477   // Before executing passes, print the final values of the LLVM options.
1478   cl::PrintOptionValues();
1479 
1480   // Now that we have all of the passes ready, run them.
1481   {
1482     PrettyStackTraceString CrashInfo("Optimizer");
1483     MPM.run(*TheModule, MAM);
1484   }
1485 
1486   // Now if needed, run the legacy PM for codegen.
1487   if (NeedCodeGen) {
1488     PrettyStackTraceString CrashInfo("Code generation");
1489     CodeGenPasses.run(*TheModule);
1490   }
1491 
1492   if (ThinLinkOS)
1493     ThinLinkOS->keep();
1494   if (DwoOS)
1495     DwoOS->keep();
1496 }
1497 
1498 static void runThinLTOBackend(
1499     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1500     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1501     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1502     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1503     std::string ProfileRemapping, BackendAction Action) {
1504   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1505       ModuleToDefinedGVSummaries;
1506   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1507 
1508   setCommandLineOpts(CGOpts);
1509 
1510   // We can simply import the values mentioned in the combined index, since
1511   // we should only invoke this using the individual indexes written out
1512   // via a WriteIndexesThinBackend.
1513   FunctionImporter::ImportMapTy ImportList;
1514   if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1515     return;
1516 
1517   auto AddStream = [&](size_t Task) {
1518     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1519   };
1520   lto::Config Conf;
1521   if (CGOpts.SaveTempsFilePrefix != "") {
1522     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1523                                     /* UseInputModulePath */ false)) {
1524       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1525         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1526                << '\n';
1527       });
1528     }
1529   }
1530   Conf.CPU = TOpts.CPU;
1531   Conf.CodeModel = getCodeModel(CGOpts);
1532   Conf.MAttrs = TOpts.Features;
1533   Conf.RelocModel = CGOpts.RelocationModel;
1534   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1535   Conf.OptLevel = CGOpts.OptimizationLevel;
1536   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1537   Conf.SampleProfile = std::move(SampleProfile);
1538   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1539   // For historical reasons, loop interleaving is set to mirror setting for loop
1540   // unrolling.
1541   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1542   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1543   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1544   // Only enable CGProfilePass when using integrated assembler, since
1545   // non-integrated assemblers don't recognize .cgprofile section.
1546   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1547 
1548   // Context sensitive profile.
1549   if (CGOpts.hasProfileCSIRInstr()) {
1550     Conf.RunCSIRInstr = true;
1551     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1552   } else if (CGOpts.hasProfileCSIRUse()) {
1553     Conf.RunCSIRInstr = false;
1554     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1555   }
1556 
1557   Conf.ProfileRemapping = std::move(ProfileRemapping);
1558   Conf.UseNewPM = !CGOpts.LegacyPassManager;
1559   Conf.DebugPassManager = CGOpts.DebugPassManager;
1560   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1561   Conf.RemarksFilename = CGOpts.OptRecordFile;
1562   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1563   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1564   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1565   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1566   switch (Action) {
1567   case Backend_EmitNothing:
1568     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1569       return false;
1570     };
1571     break;
1572   case Backend_EmitLL:
1573     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1574       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1575       return false;
1576     };
1577     break;
1578   case Backend_EmitBC:
1579     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1580       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1581       return false;
1582     };
1583     break;
1584   default:
1585     Conf.CGFileType = getCodeGenFileType(Action);
1586     break;
1587   }
1588   if (Error E =
1589           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1590                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1591                       /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1592     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1593       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1594     });
1595   }
1596 }
1597 
1598 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1599                               const HeaderSearchOptions &HeaderOpts,
1600                               const CodeGenOptions &CGOpts,
1601                               const clang::TargetOptions &TOpts,
1602                               const LangOptions &LOpts,
1603                               const llvm::DataLayout &TDesc, Module *M,
1604                               BackendAction Action,
1605                               std::unique_ptr<raw_pwrite_stream> OS) {
1606 
1607   llvm::TimeTraceScope TimeScope("Backend");
1608 
1609   std::unique_ptr<llvm::Module> EmptyModule;
1610   if (!CGOpts.ThinLTOIndexFile.empty()) {
1611     // If we are performing a ThinLTO importing compile, load the function index
1612     // into memory and pass it into runThinLTOBackend, which will run the
1613     // function importer and invoke LTO passes.
1614     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1615         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1616                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1617     if (!IndexOrErr) {
1618       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1619                             "Error loading index file '" +
1620                             CGOpts.ThinLTOIndexFile + "': ");
1621       return;
1622     }
1623     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1624     // A null CombinedIndex means we should skip ThinLTO compilation
1625     // (LLVM will optionally ignore empty index files, returning null instead
1626     // of an error).
1627     if (CombinedIndex) {
1628       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1629         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1630                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1631                           CGOpts.ProfileRemappingFile, Action);
1632         return;
1633       }
1634       // Distributed indexing detected that nothing from the module is needed
1635       // for the final linking. So we can skip the compilation. We sill need to
1636       // output an empty object file to make sure that a linker does not fail
1637       // trying to read it. Also for some features, like CFI, we must skip
1638       // the compilation as CombinedIndex does not contain all required
1639       // information.
1640       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1641       EmptyModule->setTargetTriple(M->getTargetTriple());
1642       M = EmptyModule.get();
1643     }
1644   }
1645 
1646   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1647 
1648   if (!CGOpts.LegacyPassManager)
1649     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1650   else
1651     AsmHelper.EmitAssembly(Action, std::move(OS));
1652 
1653   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1654   // DataLayout.
1655   if (AsmHelper.TM) {
1656     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1657     if (DLDesc != TDesc.getStringRepresentation()) {
1658       unsigned DiagID = Diags.getCustomDiagID(
1659           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1660                                     "expected target description '%1'");
1661       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1662     }
1663   }
1664 }
1665 
1666 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1667 // __LLVM,__bitcode section.
1668 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1669                          llvm::MemoryBufferRef Buf) {
1670   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1671     return;
1672   llvm::EmbedBitcodeInModule(
1673       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1674       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1675       CGOpts.CmdArgs);
1676 }
1677