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