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