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