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