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