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