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