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/Object/OffloadBinary.h"
43 #include "llvm/Passes/PassBuilder.h"
44 #include "llvm/Passes/PassPlugin.h"
45 #include "llvm/Passes/StandardInstrumentations.h"
46 #include "llvm/Support/BuryPointer.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/PrettyStackTrace.h"
50 #include "llvm/Support/TimeProfiler.h"
51 #include "llvm/Support/Timer.h"
52 #include "llvm/Support/ToolOutputFile.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include "llvm/Target/TargetOptions.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/ThinLTOBitcodeWriter.h"
64 #include "llvm/Transforms/InstCombine/InstCombine.h"
65 #include "llvm/Transforms/Instrumentation.h"
66 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
67 #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.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/ModuleUtils.h"
87 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
88 #include "llvm/Transforms/Utils/SymbolRewriter.h"
89 #include <memory>
90 using namespace clang;
91 using namespace llvm;
92 
93 #define HANDLE_EXTENSION(Ext)                                                  \
94   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
95 #include "llvm/Support/Extension.def"
96 
97 namespace llvm {
98 extern cl::opt<bool> DebugInfoCorrelate;
99 }
100 
101 namespace {
102 
103 // Default filename used for profile generation.
104 std::string getDefaultProfileGenName() {
105   return DebugInfoCorrelate ? "default_%p.proflite" : "default_%m.profraw";
106 }
107 
108 class EmitAssemblyHelper {
109   DiagnosticsEngine &Diags;
110   const HeaderSearchOptions &HSOpts;
111   const CodeGenOptions &CodeGenOpts;
112   const clang::TargetOptions &TargetOpts;
113   const LangOptions &LangOpts;
114   Module *TheModule;
115 
116   Timer CodeGenerationTime;
117 
118   std::unique_ptr<raw_pwrite_stream> OS;
119 
120   Triple TargetTriple;
121 
122   TargetIRAnalysis getTargetIRAnalysis() const {
123     if (TM)
124       return TM->getTargetIRAnalysis();
125 
126     return TargetIRAnalysis();
127   }
128 
129   /// Generates the TargetMachine.
130   /// Leaves TM unchanged if it is unable to create the target machine.
131   /// Some of our clang tests specify triples which are not built
132   /// into clang. This is okay because these tests check the generated
133   /// IR, and they require DataLayout which depends on the triple.
134   /// In this case, we allow this method to fail and not report an error.
135   /// When MustCreateTM is used, we print an error if we are unable to load
136   /// the requested target.
137   void CreateTargetMachine(bool MustCreateTM);
138 
139   /// Add passes necessary to emit assembly or LLVM IR.
140   ///
141   /// \return True on success.
142   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
143                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
144 
145   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
146     std::error_code EC;
147     auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
148                                                      llvm::sys::fs::OF_None);
149     if (EC) {
150       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
151       F.reset();
152     }
153     return F;
154   }
155 
156   void
157   RunOptimizationPipeline(BackendAction Action,
158                           std::unique_ptr<raw_pwrite_stream> &OS,
159                           std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS);
160   void RunCodegenPipeline(BackendAction Action,
161                           std::unique_ptr<raw_pwrite_stream> &OS,
162                           std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
163 
164   /// Check whether we should emit a module summary for regular LTO.
165   /// The module summary should be emitted by default for regular LTO
166   /// except for ld64 targets.
167   ///
168   /// \return True if the module summary should be emitted.
169   bool shouldEmitRegularLTOSummary() const {
170     return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
171            TargetTriple.getVendor() != llvm::Triple::Apple;
172   }
173 
174 public:
175   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
176                      const HeaderSearchOptions &HeaderSearchOpts,
177                      const CodeGenOptions &CGOpts,
178                      const clang::TargetOptions &TOpts,
179                      const LangOptions &LOpts, Module *M)
180       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
181         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
182         CodeGenerationTime("codegen", "Code Generation Time"),
183         TargetTriple(TheModule->getTargetTriple()) {}
184 
185   ~EmitAssemblyHelper() {
186     if (CodeGenOpts.DisableFree)
187       BuryPointer(std::move(TM));
188   }
189 
190   std::unique_ptr<TargetMachine> TM;
191 
192   // Emit output using the new pass manager for the optimization pipeline.
193   void EmitAssembly(BackendAction Action,
194                     std::unique_ptr<raw_pwrite_stream> OS);
195 };
196 }
197 
198 static SanitizerCoverageOptions
199 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
200   SanitizerCoverageOptions Opts;
201   Opts.CoverageType =
202       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
203   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
204   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
205   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
206   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
207   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
208   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
209   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
210   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
211   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
212   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
213   Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
214   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
215   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
216   Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
217   Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
218   return Opts;
219 }
220 
221 // Check if ASan should use GC-friendly instrumentation for globals.
222 // First of all, there is no point if -fdata-sections is off (expect for MachO,
223 // where this is not a factor). Also, on ELF this feature requires an assembler
224 // extension that only works with -integrated-as at the moment.
225 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
226   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
227     return false;
228   switch (T.getObjectFormat()) {
229   case Triple::MachO:
230   case Triple::COFF:
231     return true;
232   case Triple::ELF:
233     return !CGOpts.DisableIntegratedAS;
234   case Triple::GOFF:
235     llvm::report_fatal_error("ASan not implemented for GOFF");
236   case Triple::XCOFF:
237     llvm::report_fatal_error("ASan not implemented for XCOFF.");
238   case Triple::Wasm:
239   case Triple::DXContainer:
240   case Triple::SPIRV:
241   case Triple::UnknownObjectFormat:
242     break;
243   }
244   return false;
245 }
246 
247 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
248                                          const CodeGenOptions &CodeGenOpts) {
249   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
250 
251   switch (CodeGenOpts.getVecLib()) {
252   case CodeGenOptions::Accelerate:
253     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
254     break;
255   case CodeGenOptions::LIBMVEC:
256     switch(TargetTriple.getArch()) {
257       default:
258         break;
259       case llvm::Triple::x86_64:
260         TLII->addVectorizableFunctionsFromVecLib
261                 (TargetLibraryInfoImpl::LIBMVEC_X86);
262         break;
263     }
264     break;
265   case CodeGenOptions::MASSV:
266     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
267     break;
268   case CodeGenOptions::SVML:
269     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
270     break;
271   case CodeGenOptions::Darwin_libsystem_m:
272     TLII->addVectorizableFunctionsFromVecLib(
273         TargetLibraryInfoImpl::DarwinLibSystemM);
274     break;
275   default:
276     break;
277   }
278   return TLII;
279 }
280 
281 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
282   switch (CodeGenOpts.OptimizationLevel) {
283   default:
284     llvm_unreachable("Invalid optimization level!");
285   case 0:
286     return CodeGenOpt::None;
287   case 1:
288     return CodeGenOpt::Less;
289   case 2:
290     return CodeGenOpt::Default; // O2/Os/Oz
291   case 3:
292     return CodeGenOpt::Aggressive;
293   }
294 }
295 
296 static Optional<llvm::CodeModel::Model>
297 getCodeModel(const CodeGenOptions &CodeGenOpts) {
298   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
299                            .Case("tiny", llvm::CodeModel::Tiny)
300                            .Case("small", llvm::CodeModel::Small)
301                            .Case("kernel", llvm::CodeModel::Kernel)
302                            .Case("medium", llvm::CodeModel::Medium)
303                            .Case("large", llvm::CodeModel::Large)
304                            .Case("default", ~1u)
305                            .Default(~0u);
306   assert(CodeModel != ~0u && "invalid code model!");
307   if (CodeModel == ~1u)
308     return None;
309   return static_cast<llvm::CodeModel::Model>(CodeModel);
310 }
311 
312 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
313   if (Action == Backend_EmitObj)
314     return CGFT_ObjectFile;
315   else if (Action == Backend_EmitMCNull)
316     return CGFT_Null;
317   else {
318     assert(Action == Backend_EmitAssembly && "Invalid action!");
319     return CGFT_AssemblyFile;
320   }
321 }
322 
323 static bool actionRequiresCodeGen(BackendAction Action) {
324   return Action != Backend_EmitNothing && Action != Backend_EmitBC &&
325          Action != Backend_EmitLL;
326 }
327 
328 static bool initTargetOptions(DiagnosticsEngine &Diags,
329                               llvm::TargetOptions &Options,
330                               const CodeGenOptions &CodeGenOpts,
331                               const clang::TargetOptions &TargetOpts,
332                               const LangOptions &LangOpts,
333                               const HeaderSearchOptions &HSOpts) {
334   switch (LangOpts.getThreadModel()) {
335   case LangOptions::ThreadModelKind::POSIX:
336     Options.ThreadModel = llvm::ThreadModel::POSIX;
337     break;
338   case LangOptions::ThreadModelKind::Single:
339     Options.ThreadModel = llvm::ThreadModel::Single;
340     break;
341   }
342 
343   // Set float ABI type.
344   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
345           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
346          "Invalid Floating Point ABI!");
347   Options.FloatABIType =
348       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
349           .Case("soft", llvm::FloatABI::Soft)
350           .Case("softfp", llvm::FloatABI::Soft)
351           .Case("hard", llvm::FloatABI::Hard)
352           .Default(llvm::FloatABI::Default);
353 
354   // Set FP fusion mode.
355   switch (LangOpts.getDefaultFPContractMode()) {
356   case LangOptions::FPM_Off:
357     // Preserve any contraction performed by the front-end.  (Strict performs
358     // splitting of the muladd intrinsic in the backend.)
359     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
360     break;
361   case LangOptions::FPM_On:
362   case LangOptions::FPM_FastHonorPragmas:
363     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
364     break;
365   case LangOptions::FPM_Fast:
366     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
367     break;
368   }
369 
370   Options.BinutilsVersion =
371       llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
372   Options.UseInitArray = CodeGenOpts.UseInitArray;
373   Options.LowerGlobalDtorsViaCxaAtExit =
374       CodeGenOpts.RegisterGlobalDtorsWithAtExit;
375   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
376   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
377   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
378 
379   // Set EABI version.
380   Options.EABIVersion = TargetOpts.EABIVersion;
381 
382   if (LangOpts.hasSjLjExceptions())
383     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
384   if (LangOpts.hasSEHExceptions())
385     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
386   if (LangOpts.hasDWARFExceptions())
387     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
388   if (LangOpts.hasWasmExceptions())
389     Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
390 
391   Options.NoInfsFPMath = LangOpts.NoHonorInfs;
392   Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
393   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
394   Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
395   Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
396 
397   Options.BBSections =
398       llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
399           .Case("all", llvm::BasicBlockSection::All)
400           .Case("labels", llvm::BasicBlockSection::Labels)
401           .StartsWith("list=", llvm::BasicBlockSection::List)
402           .Case("none", llvm::BasicBlockSection::None)
403           .Default(llvm::BasicBlockSection::None);
404 
405   if (Options.BBSections == llvm::BasicBlockSection::List) {
406     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
407         MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
408     if (!MBOrErr) {
409       Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
410           << MBOrErr.getError().message();
411       return false;
412     }
413     Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
414   }
415 
416   Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
417   Options.FunctionSections = CodeGenOpts.FunctionSections;
418   Options.DataSections = CodeGenOpts.DataSections;
419   Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
420   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
421   Options.UniqueBasicBlockSectionNames =
422       CodeGenOpts.UniqueBasicBlockSectionNames;
423   Options.TLSSize = CodeGenOpts.TLSSize;
424   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
425   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
426   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
427   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
428   Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
429   Options.EmitAddrsig = CodeGenOpts.Addrsig;
430   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
431   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
432   Options.EnableAIXExtendedAltivecABI = CodeGenOpts.EnableAIXExtendedAltivecABI;
433   Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
434   Options.LoopAlignment = CodeGenOpts.LoopAlignment;
435   Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
436   Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
437   Options.Hotpatch = CodeGenOpts.HotPatch;
438   Options.JMCInstrument = CodeGenOpts.JMCInstrument;
439 
440   switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
441   case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
442     Options.SwiftAsyncFramePointer =
443         SwiftAsyncFramePointerMode::DeploymentBased;
444     break;
445 
446   case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
447     Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
448     break;
449 
450   case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
451     Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
452     break;
453   }
454 
455   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
456   Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
457   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
458   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
459   Options.MCOptions.MCUseDwarfDirectory =
460       CodeGenOpts.NoDwarfDirectoryAsm
461           ? llvm::MCTargetOptions::DisableDwarfDirectory
462           : llvm::MCTargetOptions::EnableDwarfDirectory;
463   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
464   Options.MCOptions.MCIncrementalLinkerCompatible =
465       CodeGenOpts.IncrementalLinkerCompatible;
466   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
467   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
468   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
469   Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
470   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
471   Options.MCOptions.ABIName = TargetOpts.ABI;
472   for (const auto &Entry : HSOpts.UserEntries)
473     if (!Entry.IsFramework &&
474         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
475          Entry.Group == frontend::IncludeDirGroup::Angled ||
476          Entry.Group == frontend::IncludeDirGroup::System))
477       Options.MCOptions.IASSearchPaths.push_back(
478           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
479   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
480   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
481   Options.MisExpect = CodeGenOpts.MisExpect;
482 
483   return true;
484 }
485 
486 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
487                                             const LangOptions &LangOpts) {
488   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
489     return None;
490   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
491   // LLVM's -default-gcov-version flag is set to something invalid.
492   GCOVOptions Options;
493   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
494   Options.EmitData = CodeGenOpts.EmitGcovArcs;
495   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
496   Options.NoRedZone = CodeGenOpts.DisableRedZone;
497   Options.Filter = CodeGenOpts.ProfileFilterFiles;
498   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
499   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
500   return Options;
501 }
502 
503 static Optional<InstrProfOptions>
504 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
505                     const LangOptions &LangOpts) {
506   if (!CodeGenOpts.hasProfileClangInstr())
507     return None;
508   InstrProfOptions Options;
509   Options.NoRedZone = CodeGenOpts.DisableRedZone;
510   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
511   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
512   return Options;
513 }
514 
515 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
516   SmallVector<const char *, 16> BackendArgs;
517   BackendArgs.push_back("clang"); // Fake program name.
518   if (!CodeGenOpts.DebugPass.empty()) {
519     BackendArgs.push_back("-debug-pass");
520     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
521   }
522   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
523     BackendArgs.push_back("-limit-float-precision");
524     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
525   }
526   // Check for the default "clang" invocation that won't set any cl::opt values.
527   // Skip trying to parse the command line invocation to avoid the issues
528   // described below.
529   if (BackendArgs.size() == 1)
530     return;
531   BackendArgs.push_back(nullptr);
532   // FIXME: The command line parser below is not thread-safe and shares a global
533   // state, so this call might crash or overwrite the options of another Clang
534   // instance in the same process.
535   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
536                                     BackendArgs.data());
537 }
538 
539 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
540   // Create the TargetMachine for generating code.
541   std::string Error;
542   std::string Triple = TheModule->getTargetTriple();
543   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
544   if (!TheTarget) {
545     if (MustCreateTM)
546       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
547     return;
548   }
549 
550   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
551   std::string FeaturesStr =
552       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
553   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
554   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
555 
556   llvm::TargetOptions Options;
557   if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
558                          HSOpts))
559     return;
560   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
561                                           Options, RM, CM, OptLevel));
562 }
563 
564 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
565                                        BackendAction Action,
566                                        raw_pwrite_stream &OS,
567                                        raw_pwrite_stream *DwoOS) {
568   // Add LibraryInfo.
569   std::unique_ptr<TargetLibraryInfoImpl> TLII(
570       createTLII(TargetTriple, CodeGenOpts));
571   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
572 
573   // Normal mode, emit a .s or .o file by running the code generator. Note,
574   // this also adds codegenerator level optimization passes.
575   CodeGenFileType CGFT = getCodeGenFileType(Action);
576 
577   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
578   // "codegen" passes so that it isn't run multiple times when there is
579   // inlining happening.
580   if (CodeGenOpts.OptimizationLevel > 0)
581     CodeGenPasses.add(createObjCARCContractPass());
582 
583   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
584                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
585     Diags.Report(diag::err_fe_unable_to_interface_with_target);
586     return false;
587   }
588 
589   return true;
590 }
591 
592 static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
593   switch (Opts.OptimizationLevel) {
594   default:
595     llvm_unreachable("Invalid optimization level!");
596 
597   case 0:
598     return OptimizationLevel::O0;
599 
600   case 1:
601     return OptimizationLevel::O1;
602 
603   case 2:
604     switch (Opts.OptimizeSize) {
605     default:
606       llvm_unreachable("Invalid optimization level for size!");
607 
608     case 0:
609       return OptimizationLevel::O2;
610 
611     case 1:
612       return OptimizationLevel::Os;
613 
614     case 2:
615       return OptimizationLevel::Oz;
616     }
617 
618   case 3:
619     return OptimizationLevel::O3;
620   }
621 }
622 
623 static void addSanitizers(const Triple &TargetTriple,
624                           const CodeGenOptions &CodeGenOpts,
625                           const LangOptions &LangOpts, PassBuilder &PB) {
626   PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
627                                          OptimizationLevel Level) {
628     if (CodeGenOpts.hasSanitizeCoverage()) {
629       auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
630       MPM.addPass(ModuleSanitizerCoveragePass(
631           SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
632           CodeGenOpts.SanitizeCoverageIgnorelistFiles));
633     }
634 
635     auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
636       if (LangOpts.Sanitize.has(Mask)) {
637         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
638         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
639 
640         MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
641                                        CodeGenOpts.SanitizeMemoryParamRetval);
642         MPM.addPass(ModuleMemorySanitizerPass(options));
643         FunctionPassManager FPM;
644         FPM.addPass(MemorySanitizerPass(options));
645         if (Level != OptimizationLevel::O0) {
646           // MemorySanitizer inserts complex instrumentation that mostly
647           // follows the logic of the original code, but operates on
648           // "shadow" values. It can benefit from re-running some
649           // general purpose optimization passes.
650           FPM.addPass(EarlyCSEPass());
651           // TODO: Consider add more passes like in
652           // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible
653           // difference on size. It's not clear if the rest is still
654           // usefull. InstCombinePass breakes
655           // compiler-rt/test/msan/select_origin.cpp.
656         }
657         MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
658       }
659     };
660     MSanPass(SanitizerKind::Memory, false);
661     MSanPass(SanitizerKind::KernelMemory, true);
662 
663     if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
664       MPM.addPass(ModuleThreadSanitizerPass());
665       MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
666     }
667 
668     auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
669       if (LangOpts.Sanitize.has(Mask)) {
670         bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
671         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
672         llvm::AsanDtorKind DestructorKind =
673             CodeGenOpts.getSanitizeAddressDtor();
674         AddressSanitizerOptions Opts;
675         Opts.CompileKernel = CompileKernel;
676         Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
677         Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
678         Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
679         MPM.addPass(ModuleAddressSanitizerPass(
680             Opts, UseGlobalGC, UseOdrIndicator, DestructorKind));
681       }
682     };
683     ASanPass(SanitizerKind::Address, false);
684     ASanPass(SanitizerKind::KernelAddress, true);
685 
686     auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
687       if (LangOpts.Sanitize.has(Mask)) {
688         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
689         MPM.addPass(HWAddressSanitizerPass(
690             {CompileKernel, Recover,
691              /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
692       }
693     };
694     HWASanPass(SanitizerKind::HWAddress, false);
695     HWASanPass(SanitizerKind::KernelHWAddress, true);
696 
697     if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
698       MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
699     }
700   });
701 }
702 
703 void EmitAssemblyHelper::RunOptimizationPipeline(
704     BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
705     std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS) {
706   Optional<PGOOptions> PGOOpt;
707 
708   if (CodeGenOpts.hasProfileIRInstr())
709     // -fprofile-generate.
710     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
711                             ? getDefaultProfileGenName()
712                             : CodeGenOpts.InstrProfileOutput,
713                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
714                         CodeGenOpts.DebugInfoForProfiling);
715   else if (CodeGenOpts.hasProfileIRUse()) {
716     // -fprofile-use.
717     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
718                                                     : PGOOptions::NoCSAction;
719     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
720                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
721                         CSAction, CodeGenOpts.DebugInfoForProfiling);
722   } else if (!CodeGenOpts.SampleProfileFile.empty())
723     // -fprofile-sample-use
724     PGOOpt = PGOOptions(
725         CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
726         PGOOptions::SampleUse, PGOOptions::NoCSAction,
727         CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
728   else if (CodeGenOpts.PseudoProbeForProfiling)
729     // -fpseudo-probe-for-profiling
730     PGOOpt =
731         PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
732                    CodeGenOpts.DebugInfoForProfiling, true);
733   else if (CodeGenOpts.DebugInfoForProfiling)
734     // -fdebug-info-for-profiling
735     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
736                         PGOOptions::NoCSAction, true);
737 
738   // Check to see if we want to generate a CS profile.
739   if (CodeGenOpts.hasProfileCSIRInstr()) {
740     assert(!CodeGenOpts.hasProfileCSIRUse() &&
741            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
742            "the same time");
743     if (PGOOpt) {
744       assert(PGOOpt->Action != PGOOptions::IRInstr &&
745              PGOOpt->Action != PGOOptions::SampleUse &&
746              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
747              " pass");
748       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
749                                      ? getDefaultProfileGenName()
750                                      : CodeGenOpts.InstrProfileOutput;
751       PGOOpt->CSAction = PGOOptions::CSIRInstr;
752     } else
753       PGOOpt = PGOOptions("",
754                           CodeGenOpts.InstrProfileOutput.empty()
755                               ? getDefaultProfileGenName()
756                               : CodeGenOpts.InstrProfileOutput,
757                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
758                           CodeGenOpts.DebugInfoForProfiling);
759   }
760   if (TM)
761     TM->setPGOOption(PGOOpt);
762 
763   PipelineTuningOptions PTO;
764   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
765   // For historical reasons, loop interleaving is set to mirror setting for loop
766   // unrolling.
767   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
768   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
769   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
770   PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
771   // Only enable CGProfilePass when using integrated assembler, since
772   // non-integrated assemblers don't recognize .cgprofile section.
773   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
774 
775   LoopAnalysisManager LAM;
776   FunctionAnalysisManager FAM;
777   CGSCCAnalysisManager CGAM;
778   ModuleAnalysisManager MAM;
779 
780   bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
781   PassInstrumentationCallbacks PIC;
782   PrintPassOptions PrintPassOpts;
783   PrintPassOpts.Indent = DebugPassStructure;
784   PrintPassOpts.SkipAnalyses = DebugPassStructure;
785   StandardInstrumentations SI(CodeGenOpts.DebugPassManager ||
786                                   DebugPassStructure,
787                               /*VerifyEach*/ false, PrintPassOpts);
788   SI.registerCallbacks(PIC, &FAM);
789   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
790 
791   // Enable verify-debuginfo-preserve-each for new PM.
792   DebugifyEachInstrumentation Debugify;
793   DebugInfoPerPass DebugInfoBeforePass;
794   if (CodeGenOpts.EnableDIPreservationVerify) {
795     Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
796     Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
797 
798     if (!CodeGenOpts.DIBugsReportFilePath.empty())
799       Debugify.setOrigDIVerifyBugsReportFilePath(
800           CodeGenOpts.DIBugsReportFilePath);
801     Debugify.registerCallbacks(PIC);
802   }
803   // Attempt to load pass plugins and register their callbacks with PB.
804   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
805     auto PassPlugin = PassPlugin::Load(PluginFN);
806     if (PassPlugin) {
807       PassPlugin->registerPassBuilderCallbacks(PB);
808     } else {
809       Diags.Report(diag::err_fe_unable_to_load_plugin)
810           << PluginFN << toString(PassPlugin.takeError());
811     }
812   }
813 #define HANDLE_EXTENSION(Ext)                                                  \
814   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
815 #include "llvm/Support/Extension.def"
816 
817   // Register the target library analysis directly and give it a customized
818   // preset TLI.
819   std::unique_ptr<TargetLibraryInfoImpl> TLII(
820       createTLII(TargetTriple, CodeGenOpts));
821   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
822 
823   // Register all the basic analyses with the managers.
824   PB.registerModuleAnalyses(MAM);
825   PB.registerCGSCCAnalyses(CGAM);
826   PB.registerFunctionAnalyses(FAM);
827   PB.registerLoopAnalyses(LAM);
828   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
829 
830   ModulePassManager MPM;
831 
832   if (!CodeGenOpts.DisableLLVMPasses) {
833     // Map our optimization levels into one of the distinct levels used to
834     // configure the pipeline.
835     OptimizationLevel Level = mapToLevel(CodeGenOpts);
836 
837     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
838     bool IsLTO = CodeGenOpts.PrepareForLTO;
839 
840     if (LangOpts.ObjCAutoRefCount) {
841       PB.registerPipelineStartEPCallback(
842           [](ModulePassManager &MPM, OptimizationLevel Level) {
843             if (Level != OptimizationLevel::O0)
844               MPM.addPass(
845                   createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
846           });
847       PB.registerPipelineEarlySimplificationEPCallback(
848           [](ModulePassManager &MPM, OptimizationLevel Level) {
849             if (Level != OptimizationLevel::O0)
850               MPM.addPass(ObjCARCAPElimPass());
851           });
852       PB.registerScalarOptimizerLateEPCallback(
853           [](FunctionPassManager &FPM, OptimizationLevel Level) {
854             if (Level != OptimizationLevel::O0)
855               FPM.addPass(ObjCARCOptPass());
856           });
857     }
858 
859     // If we reached here with a non-empty index file name, then the index
860     // file was empty and we are not performing ThinLTO backend compilation
861     // (used in testing in a distributed build environment).
862     bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
863     // If so drop any the type test assume sequences inserted for whole program
864     // vtables so that codegen doesn't complain.
865     if (IsThinLTOPostLink)
866       PB.registerPipelineStartEPCallback(
867           [](ModulePassManager &MPM, OptimizationLevel Level) {
868             MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
869                                            /*ImportSummary=*/nullptr,
870                                            /*DropTypeTests=*/true));
871           });
872 
873     if (CodeGenOpts.InstrumentFunctions ||
874         CodeGenOpts.InstrumentFunctionEntryBare ||
875         CodeGenOpts.InstrumentFunctionsAfterInlining ||
876         CodeGenOpts.InstrumentForProfiling) {
877       PB.registerPipelineStartEPCallback(
878           [](ModulePassManager &MPM, OptimizationLevel Level) {
879             MPM.addPass(createModuleToFunctionPassAdaptor(
880                 EntryExitInstrumenterPass(/*PostInlining=*/false)));
881           });
882       PB.registerOptimizerLastEPCallback(
883           [](ModulePassManager &MPM, OptimizationLevel Level) {
884             MPM.addPass(createModuleToFunctionPassAdaptor(
885                 EntryExitInstrumenterPass(/*PostInlining=*/true)));
886           });
887     }
888 
889     // Register callbacks to schedule sanitizer passes at the appropriate part
890     // of the pipeline.
891     if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
892       PB.registerScalarOptimizerLateEPCallback(
893           [](FunctionPassManager &FPM, OptimizationLevel Level) {
894             FPM.addPass(BoundsCheckingPass());
895           });
896 
897     // Don't add sanitizers if we are here from ThinLTO PostLink. That already
898     // done on PreLink stage.
899     if (!IsThinLTOPostLink)
900       addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
901 
902     if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
903       PB.registerPipelineStartEPCallback(
904           [Options](ModulePassManager &MPM, OptimizationLevel Level) {
905             MPM.addPass(GCOVProfilerPass(*Options));
906           });
907     if (Optional<InstrProfOptions> Options =
908             getInstrProfOptions(CodeGenOpts, LangOpts))
909       PB.registerPipelineStartEPCallback(
910           [Options](ModulePassManager &MPM, OptimizationLevel Level) {
911             MPM.addPass(InstrProfiling(*Options, false));
912           });
913 
914     if (CodeGenOpts.OptimizationLevel == 0) {
915       MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO);
916     } else if (IsThinLTO) {
917       MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
918     } else if (IsLTO) {
919       MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
920     } else {
921       MPM = PB.buildPerModuleDefaultPipeline(Level);
922     }
923 
924     if (!CodeGenOpts.MemoryProfileOutput.empty()) {
925       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
926       MPM.addPass(ModuleMemProfilerPass());
927     }
928   }
929 
930   // Add a verifier pass if requested. We don't have to do this if the action
931   // requires code generation because there will already be a verifier pass in
932   // the code-generation pipeline.
933   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
934     MPM.addPass(VerifierPass());
935 
936   switch (Action) {
937   case Backend_EmitBC:
938     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
939       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
940         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
941         if (!ThinLinkOS)
942           return;
943       }
944       if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
945         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
946                                  CodeGenOpts.EnableSplitLTOUnit);
947       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
948                                                            : nullptr));
949     } else {
950       // Emit a module summary by default for Regular LTO except for ld64
951       // targets
952       bool EmitLTOSummary = shouldEmitRegularLTOSummary();
953       if (EmitLTOSummary) {
954         if (!TheModule->getModuleFlag("ThinLTO"))
955           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
956         if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
957           TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
958                                    uint32_t(1));
959       }
960       MPM.addPass(
961           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
962     }
963     break;
964 
965   case Backend_EmitLL:
966     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
967     break;
968 
969   default:
970     break;
971   }
972 
973   // Now that we have all of the passes ready, run them.
974   {
975     PrettyStackTraceString CrashInfo("Optimizer");
976     llvm::TimeTraceScope TimeScope("Optimizer");
977     MPM.run(*TheModule, MAM);
978   }
979 }
980 
981 void EmitAssemblyHelper::RunCodegenPipeline(
982     BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
983     std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
984   // We still use the legacy PM to run the codegen pipeline since the new PM
985   // does not work with the codegen pipeline.
986   // FIXME: make the new PM work with the codegen pipeline.
987   legacy::PassManager CodeGenPasses;
988 
989   // Append any output we need to the pass manager.
990   switch (Action) {
991   case Backend_EmitAssembly:
992   case Backend_EmitMCNull:
993   case Backend_EmitObj:
994     CodeGenPasses.add(
995         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
996     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
997       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
998       if (!DwoOS)
999         return;
1000     }
1001     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1002                        DwoOS ? &DwoOS->os() : nullptr))
1003       // FIXME: Should we handle this error differently?
1004       return;
1005     break;
1006   default:
1007     return;
1008   }
1009 
1010   {
1011     PrettyStackTraceString CrashInfo("Code generation");
1012     llvm::TimeTraceScope TimeScope("CodeGenPasses");
1013     CodeGenPasses.run(*TheModule);
1014   }
1015 }
1016 
1017 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
1018                                       std::unique_ptr<raw_pwrite_stream> OS) {
1019   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1020   setCommandLineOpts(CodeGenOpts);
1021 
1022   bool RequiresCodeGen = actionRequiresCodeGen(Action);
1023   CreateTargetMachine(RequiresCodeGen);
1024 
1025   if (RequiresCodeGen && !TM)
1026     return;
1027   if (TM)
1028     TheModule->setDataLayout(TM->createDataLayout());
1029 
1030   // Before executing passes, print the final values of the LLVM options.
1031   cl::PrintOptionValues();
1032 
1033   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1034   RunOptimizationPipeline(Action, OS, ThinLinkOS);
1035   RunCodegenPipeline(Action, OS, DwoOS);
1036 
1037   if (ThinLinkOS)
1038     ThinLinkOS->keep();
1039   if (DwoOS)
1040     DwoOS->keep();
1041 }
1042 
1043 static void runThinLTOBackend(
1044     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1045     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1046     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1047     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1048     std::string ProfileRemapping, BackendAction Action) {
1049   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1050       ModuleToDefinedGVSummaries;
1051   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1052 
1053   setCommandLineOpts(CGOpts);
1054 
1055   // We can simply import the values mentioned in the combined index, since
1056   // we should only invoke this using the individual indexes written out
1057   // via a WriteIndexesThinBackend.
1058   FunctionImporter::ImportMapTy ImportList;
1059   if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1060     return;
1061 
1062   auto AddStream = [&](size_t Task) {
1063     return std::make_unique<CachedFileStream>(std::move(OS),
1064                                               CGOpts.ObjectFilenameForDebug);
1065   };
1066   lto::Config Conf;
1067   if (CGOpts.SaveTempsFilePrefix != "") {
1068     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1069                                     /* UseInputModulePath */ false)) {
1070       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1071         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1072                << '\n';
1073       });
1074     }
1075   }
1076   Conf.CPU = TOpts.CPU;
1077   Conf.CodeModel = getCodeModel(CGOpts);
1078   Conf.MAttrs = TOpts.Features;
1079   Conf.RelocModel = CGOpts.RelocationModel;
1080   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1081   Conf.OptLevel = CGOpts.OptimizationLevel;
1082   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1083   Conf.SampleProfile = std::move(SampleProfile);
1084   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1085   // For historical reasons, loop interleaving is set to mirror setting for loop
1086   // unrolling.
1087   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1088   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1089   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1090   // Only enable CGProfilePass when using integrated assembler, since
1091   // non-integrated assemblers don't recognize .cgprofile section.
1092   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1093 
1094   // Context sensitive profile.
1095   if (CGOpts.hasProfileCSIRInstr()) {
1096     Conf.RunCSIRInstr = true;
1097     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1098   } else if (CGOpts.hasProfileCSIRUse()) {
1099     Conf.RunCSIRInstr = false;
1100     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1101   }
1102 
1103   Conf.ProfileRemapping = std::move(ProfileRemapping);
1104   Conf.DebugPassManager = CGOpts.DebugPassManager;
1105   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1106   Conf.RemarksFilename = CGOpts.OptRecordFile;
1107   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1108   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1109   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1110   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1111   switch (Action) {
1112   case Backend_EmitNothing:
1113     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1114       return false;
1115     };
1116     break;
1117   case Backend_EmitLL:
1118     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1119       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1120       return false;
1121     };
1122     break;
1123   case Backend_EmitBC:
1124     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1125       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1126       return false;
1127     };
1128     break;
1129   default:
1130     Conf.CGFileType = getCodeGenFileType(Action);
1131     break;
1132   }
1133   if (Error E =
1134           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1135                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1136                       /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1137     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1138       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1139     });
1140   }
1141 }
1142 
1143 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1144                               const HeaderSearchOptions &HeaderOpts,
1145                               const CodeGenOptions &CGOpts,
1146                               const clang::TargetOptions &TOpts,
1147                               const LangOptions &LOpts,
1148                               StringRef TDesc, Module *M,
1149                               BackendAction Action,
1150                               std::unique_ptr<raw_pwrite_stream> OS) {
1151 
1152   llvm::TimeTraceScope TimeScope("Backend");
1153 
1154   std::unique_ptr<llvm::Module> EmptyModule;
1155   if (!CGOpts.ThinLTOIndexFile.empty()) {
1156     // If we are performing a ThinLTO importing compile, load the function index
1157     // into memory and pass it into runThinLTOBackend, which will run the
1158     // function importer and invoke LTO passes.
1159     std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1160     if (Error E = llvm::getModuleSummaryIndexForFile(
1161                       CGOpts.ThinLTOIndexFile,
1162                       /*IgnoreEmptyThinLTOIndexFile*/ true)
1163                       .moveInto(CombinedIndex)) {
1164       logAllUnhandledErrors(std::move(E), errs(),
1165                             "Error loading index file '" +
1166                             CGOpts.ThinLTOIndexFile + "': ");
1167       return;
1168     }
1169 
1170     // A null CombinedIndex means we should skip ThinLTO compilation
1171     // (LLVM will optionally ignore empty index files, returning null instead
1172     // of an error).
1173     if (CombinedIndex) {
1174       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1175         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1176                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1177                           CGOpts.ProfileRemappingFile, Action);
1178         return;
1179       }
1180       // Distributed indexing detected that nothing from the module is needed
1181       // for the final linking. So we can skip the compilation. We sill need to
1182       // output an empty object file to make sure that a linker does not fail
1183       // trying to read it. Also for some features, like CFI, we must skip
1184       // the compilation as CombinedIndex does not contain all required
1185       // information.
1186       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1187       EmptyModule->setTargetTriple(M->getTargetTriple());
1188       M = EmptyModule.get();
1189     }
1190   }
1191 
1192   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1193   AsmHelper.EmitAssembly(Action, std::move(OS));
1194 
1195   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1196   // DataLayout.
1197   if (AsmHelper.TM) {
1198     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1199     if (DLDesc != TDesc) {
1200       unsigned DiagID = Diags.getCustomDiagID(
1201           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1202                                     "expected target description '%1'");
1203       Diags.Report(DiagID) << DLDesc << TDesc;
1204     }
1205   }
1206 }
1207 
1208 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1209 // __LLVM,__bitcode section.
1210 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1211                          llvm::MemoryBufferRef Buf) {
1212   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1213     return;
1214   llvm::embedBitcodeInModule(
1215       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1216       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1217       CGOpts.CmdArgs);
1218 }
1219 
1220 void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1221                         DiagnosticsEngine &Diags) {
1222   if (CGOpts.OffloadObjects.empty())
1223     return;
1224 
1225   for (StringRef OffloadObject : CGOpts.OffloadObjects) {
1226     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1227         llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1228     if (std::error_code EC = ObjectOrErr.getError()) {
1229       auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1230                                           "could not open '%0' for embedding");
1231       Diags.Report(DiagID) << OffloadObject;
1232       return;
1233     }
1234 
1235     llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading",
1236                               Align(object::OffloadBinary::getAlignment()));
1237   }
1238 }
1239