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