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