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