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