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