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