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