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