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