LTOCodeGenerator.h 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-LTOCodeGenerator.h - LLVM Link Time Optimizer -----------------------===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file declares the LTOCodeGenerator class.
  15. //
  16. // LTO compilation consists of three phases: Pre-IPO, IPO and Post-IPO.
  17. //
  18. // The Pre-IPO phase compiles source code into bitcode file. The resulting
  19. // bitcode files, along with object files and libraries, will be fed to the
  20. // linker to through the IPO and Post-IPO phases. By using obj-file extension,
  21. // the resulting bitcode file disguises itself as an object file, and therefore
  22. // obviates the need of writing a special set of the make-rules only for LTO
  23. // compilation.
  24. //
  25. // The IPO phase perform inter-procedural analyses and optimizations, and
  26. // the Post-IPO consists two sub-phases: intra-procedural scalar optimizations
  27. // (SOPT), and intra-procedural target-dependent code generator (CG).
  28. //
  29. // As of this writing, we don't separate IPO and the Post-IPO SOPT. They
  30. // are intermingled together, and are driven by a single pass manager (see
  31. // PassManagerBuilder::populateLTOPassManager()).
  32. //
  33. // The "LTOCodeGenerator" is the driver for the IPO and Post-IPO stages.
  34. // The "CodeGenerator" here is bit confusing. Don't confuse the "CodeGenerator"
  35. // with the machine specific code generator.
  36. //
  37. //===----------------------------------------------------------------------===//
  38. #ifndef LLVM_LTO_LEGACY_LTOCODEGENERATOR_H
  39. #define LLVM_LTO_LEGACY_LTOCODEGENERATOR_H
  40. #include "llvm-c/lto.h"
  41. #include "llvm/ADT/ArrayRef.h"
  42. #include "llvm/ADT/SmallPtrSet.h"
  43. #include "llvm/ADT/StringMap.h"
  44. #include "llvm/ADT/StringSet.h"
  45. #include "llvm/IR/GlobalValue.h"
  46. #include "llvm/IR/Module.h"
  47. #include "llvm/LTO/Config.h"
  48. #include "llvm/LTO/LTO.h"
  49. #include "llvm/Support/CommandLine.h"
  50. #include "llvm/Support/Error.h"
  51. #include "llvm/Support/ToolOutputFile.h"
  52. #include "llvm/Target/TargetMachine.h"
  53. #include "llvm/Target/TargetOptions.h"
  54. #include <string>
  55. #include <vector>
  56. /// Enable global value internalization in LTO.
  57. extern llvm::cl::opt<bool> EnableLTOInternalization;
  58. namespace llvm {
  59. template <typename T> class ArrayRef;
  60. class LLVMContext;
  61. class DiagnosticInfo;
  62. class Linker;
  63. class Mangler;
  64. class MemoryBuffer;
  65. class TargetLibraryInfo;
  66. class TargetMachine;
  67. class raw_ostream;
  68. class raw_pwrite_stream;
  69. //===----------------------------------------------------------------------===//
  70. /// C++ class which implements the opaque lto_code_gen_t type.
  71. ///
  72. struct LTOCodeGenerator {
  73. static const char *getVersionString();
  74. LTOCodeGenerator(LLVMContext &Context);
  75. ~LTOCodeGenerator();
  76. /// Merge given module. Return true on success.
  77. ///
  78. /// Resets \a HasVerifiedInput.
  79. bool addModule(struct LTOModule *);
  80. /// Set the destination module.
  81. ///
  82. /// Resets \a HasVerifiedInput.
  83. void setModule(std::unique_ptr<LTOModule> M);
  84. void setAsmUndefinedRefs(struct LTOModule *);
  85. void setTargetOptions(const TargetOptions &Options);
  86. void setDebugInfo(lto_debug_model);
  87. void setCodePICModel(Optional<Reloc::Model> Model) {
  88. Config.RelocModel = Model;
  89. }
  90. /// Set the file type to be emitted (assembly or object code).
  91. /// The default is CGFT_ObjectFile.
  92. void setFileType(CodeGenFileType FT) { Config.CGFileType = FT; }
  93. void setCpu(StringRef MCpu) { Config.CPU = std::string(MCpu); }
  94. void setAttrs(std::vector<std::string> MAttrs) { Config.MAttrs = MAttrs; }
  95. void setOptLevel(unsigned OptLevel);
  96. void setShouldInternalize(bool Value) { ShouldInternalize = Value; }
  97. void setShouldEmbedUselists(bool Value) { ShouldEmbedUselists = Value; }
  98. /// Restore linkage of globals
  99. ///
  100. /// When set, the linkage of globals will be restored prior to code
  101. /// generation. That is, a global symbol that had external linkage prior to
  102. /// LTO will be emitted with external linkage again; and a local will remain
  103. /// local. Note that this option only affects the end result - globals may
  104. /// still be internalized in the process of LTO and may be modified and/or
  105. /// deleted where legal.
  106. ///
  107. /// The default behavior will internalize globals (unless on the preserve
  108. /// list) and, if parallel code generation is enabled, will externalize
  109. /// all locals.
  110. void setShouldRestoreGlobalsLinkage(bool Value) {
  111. ShouldRestoreGlobalsLinkage = Value;
  112. }
  113. void addMustPreserveSymbol(StringRef Sym) { MustPreserveSymbols.insert(Sym); }
  114. /// Pass options to the driver and optimization passes.
  115. ///
  116. /// These options are not necessarily for debugging purpose (the function
  117. /// name is misleading). This function should be called before
  118. /// LTOCodeGenerator::compilexxx(), and
  119. /// LTOCodeGenerator::writeMergedModules().
  120. void setCodeGenDebugOptions(ArrayRef<StringRef> Opts);
  121. /// Parse the options set in setCodeGenDebugOptions.
  122. ///
  123. /// Like \a setCodeGenDebugOptions(), this must be called before
  124. /// LTOCodeGenerator::compilexxx() and
  125. /// LTOCodeGenerator::writeMergedModules().
  126. void parseCodeGenDebugOptions();
  127. /// Write the merged module to the file specified by the given path. Return
  128. /// true on success.
  129. ///
  130. /// Calls \a verifyMergedModuleOnce().
  131. bool writeMergedModules(StringRef Path);
  132. /// Compile the merged module into a *single* output file; the path to output
  133. /// file is returned to the caller via argument "name". Return true on
  134. /// success.
  135. ///
  136. /// \note It is up to the linker to remove the intermediate output file. Do
  137. /// not try to remove the object file in LTOCodeGenerator's destructor as we
  138. /// don't who (LTOCodeGenerator or the output file) will last longer.
  139. bool compile_to_file(const char **Name);
  140. /// As with compile_to_file(), this function compiles the merged module into
  141. /// single output file. Instead of returning the output file path to the
  142. /// caller (linker), it brings the output to a buffer, and returns the buffer
  143. /// to the caller. This function should delete the intermediate file once
  144. /// its content is brought to memory. Return NULL if the compilation was not
  145. /// successful.
  146. std::unique_ptr<MemoryBuffer> compile();
  147. /// Optimizes the merged module. Returns true on success.
  148. ///
  149. /// Calls \a verifyMergedModuleOnce().
  150. bool optimize();
  151. /// Compiles the merged optimized module into a single output file. It brings
  152. /// the output to a buffer, and returns the buffer to the caller. Return NULL
  153. /// if the compilation was not successful.
  154. std::unique_ptr<MemoryBuffer> compileOptimized();
  155. /// Compile the merged optimized module \p ParallelismLevel output files each
  156. /// representing a linkable partition of the module. If out contains more
  157. /// than one element, code generation is done in parallel with \p
  158. /// ParallelismLevel threads. Output files will be written to the streams
  159. /// created using the \p AddStream callback. Returns true on success.
  160. ///
  161. /// Calls \a verifyMergedModuleOnce().
  162. bool compileOptimized(AddStreamFn AddStream, unsigned ParallelismLevel);
  163. /// Enable the Freestanding mode: indicate that the optimizer should not
  164. /// assume builtins are present on the target.
  165. void setFreestanding(bool Enabled) { Config.Freestanding = Enabled; }
  166. void setDisableVerify(bool Value) { Config.DisableVerify = Value; }
  167. void setUseNewPM(bool Value) { Config.UseNewPM = Value; }
  168. void setDiagnosticHandler(lto_diagnostic_handler_t, void *);
  169. LLVMContext &getContext() { return Context; }
  170. void resetMergedModule() { MergedModule.reset(); }
  171. void DiagnosticHandler(const DiagnosticInfo &DI);
  172. private:
  173. /// Verify the merged module on first call.
  174. ///
  175. /// Sets \a HasVerifiedInput on first call and doesn't run again on the same
  176. /// input.
  177. void verifyMergedModuleOnce();
  178. bool compileOptimizedToFile(const char **Name);
  179. void restoreLinkageForExternals();
  180. void applyScopeRestrictions();
  181. void preserveDiscardableGVs(
  182. Module &TheModule,
  183. llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV);
  184. bool determineTarget();
  185. std::unique_ptr<TargetMachine> createTargetMachine();
  186. void emitError(const std::string &ErrMsg);
  187. void emitWarning(const std::string &ErrMsg);
  188. void finishOptimizationRemarks();
  189. LLVMContext &Context;
  190. std::unique_ptr<Module> MergedModule;
  191. std::unique_ptr<Linker> TheLinker;
  192. std::unique_ptr<TargetMachine> TargetMach;
  193. bool EmitDwarfDebugInfo = false;
  194. bool ScopeRestrictionsDone = false;
  195. bool HasVerifiedInput = false;
  196. StringSet<> MustPreserveSymbols;
  197. StringSet<> AsmUndefinedRefs;
  198. StringMap<GlobalValue::LinkageTypes> ExternalSymbols;
  199. std::vector<std::string> CodegenOptions;
  200. std::string FeatureStr;
  201. std::string NativeObjectPath;
  202. const Target *MArch = nullptr;
  203. std::string TripleStr;
  204. lto_diagnostic_handler_t DiagHandler = nullptr;
  205. void *DiagContext = nullptr;
  206. bool ShouldInternalize = EnableLTOInternalization;
  207. bool ShouldEmbedUselists = false;
  208. bool ShouldRestoreGlobalsLinkage = false;
  209. std::unique_ptr<ToolOutputFile> DiagnosticOutputFile;
  210. std::unique_ptr<ToolOutputFile> StatsFile = nullptr;
  211. lto::Config Config;
  212. };
  213. /// A convenience function that calls cl::ParseCommandLineOptions on the given
  214. /// set of options.
  215. void parseCommandLineOptions(std::vector<std::string> &Options);
  216. }
  217. #endif
  218. #ifdef __GNUC__
  219. #pragma GCC diagnostic pop
  220. #endif