1 //===-LTOCodeGenerator.h - LLVM Link Time Optimizer -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file declares the LTOCodeGenerator class. 11 // 12 // LTO compilation consists of three phases: Pre-IPO, IPO and Post-IPO. 13 // 14 // The Pre-IPO phase compiles source code into bitcode file. The resulting 15 // bitcode files, along with object files and libraries, will be fed to the 16 // linker to through the IPO and Post-IPO phases. By using obj-file extension, 17 // the resulting bitcode file disguises itself as an object file, and therefore 18 // obviates the need of writing a special set of the make-rules only for LTO 19 // compilation. 20 // 21 // The IPO phase perform inter-procedural analyses and optimizations, and 22 // the Post-IPO consists two sub-phases: intra-procedural scalar optimizations 23 // (SOPT), and intra-procedural target-dependent code generator (CG). 24 // 25 // As of this writing, we don't separate IPO and the Post-IPO SOPT. They 26 // are intermingled together, and are driven by a single pass manager (see 27 // PassManagerBuilder::populateLTOPassManager()). 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_LTOCODEGENERATOR_H 36 #define LLVM_LTO_LTOCODEGENERATOR_H 37 38 #include "llvm-c/lto.h" 39 #include "llvm/ADT/SmallPtrSet.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/Target/TargetMachine.h" 45 #include "llvm/Target/TargetOptions.h" 46 #include <string> 47 #include <vector> 48 49 namespace llvm { 50 template <typename T> class ArrayRef; 51 class LLVMContext; 52 class DiagnosticInfo; 53 class Linker; 54 class Mangler; 55 class MemoryBuffer; 56 class TargetLibraryInfo; 57 class TargetMachine; 58 class raw_ostream; 59 class raw_pwrite_stream; 60 61 //===----------------------------------------------------------------------===// 62 /// C++ class which implements the opaque lto_code_gen_t type. 63 /// 64 struct LTOCodeGenerator { 65 static const char *getVersionString(); 66 67 LTOCodeGenerator(LLVMContext &Context); 68 ~LTOCodeGenerator(); 69 70 /// Merge given module. Return true on success. 71 /// 72 /// Resets \a HasVerifiedInput. 73 bool addModule(struct LTOModule *); 74 75 /// Set the destination module. 76 /// 77 /// Resets \a HasVerifiedInput. 78 void setModule(std::unique_ptr<LTOModule> M); 79 80 void setTargetOptions(const TargetOptions &Options); 81 void setDebugInfo(lto_debug_model); 82 void setCodePICModel(Optional<Reloc::Model> Model) { RelocModel = Model; } 83 84 /// Set the file type to be emitted (assembly or object code). 85 /// The default is TargetMachine::CGFT_ObjectFile. 86 void setFileType(TargetMachine::CodeGenFileType FT) { FileType = FT; } 87 88 void setCpu(const char *MCpu) { this->MCpu = MCpu; } 89 void setAttr(const char *MAttr) { this->MAttr = MAttr; } 90 void setOptLevel(unsigned OptLevel); 91 92 void setShouldInternalize(bool Value) { ShouldInternalize = Value; } 93 void setShouldEmbedUselists(bool Value) { ShouldEmbedUselists = Value; } 94 95 /// Restore linkage of globals 96 /// 97 /// When set, the linkage of globals will be restored prior to code 98 /// generation. That is, a global symbol that had external linkage prior to 99 /// LTO will be emitted with external linkage again; and a local will remain 100 /// local. Note that this option only affects the end result - globals may 101 /// still be internalized in the process of LTO and may be modified and/or 102 /// deleted where legal. 103 /// 104 /// The default behavior will internalize globals (unless on the preserve 105 /// list) and, if parallel code generation is enabled, will externalize 106 /// all locals. 107 void setShouldRestoreGlobalsLinkage(bool Value) { 108 ShouldRestoreGlobalsLinkage = Value; 109 } 110 111 void addMustPreserveSymbol(StringRef Sym) { MustPreserveSymbols[Sym] = 1; } 112 113 /// Pass options to the driver and optimization passes. 114 /// 115 /// These options are not necessarily for debugging purpose (the function 116 /// name is misleading). This function should be called before 117 /// LTOCodeGenerator::compilexxx(), and 118 /// LTOCodeGenerator::writeMergedModules(). 119 void setCodeGenDebugOptions(const char *Opts); 120 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 128 /// Write the merged module to the file specified by the given path. Return 129 /// true on success. 130 /// 131 /// Calls \a verifyMergedModuleOnce(). 132 bool writeMergedModules(const char *Path); 133 134 /// Compile the merged module into a *single* output file; the path to output 135 /// file is returned to the caller via argument "name". Return true on 136 /// success. 137 /// 138 /// \note It is up to the linker to remove the intermediate output file. Do 139 /// not try to remove the object file in LTOCodeGenerator's destructor as we 140 /// don't who (LTOCodeGenerator or the output file) will last longer. 141 bool compile_to_file(const char **Name, bool DisableVerify, 142 bool DisableInline, bool DisableGVNLoadPRE, 143 bool DisableVectorization); 144 145 /// As with compile_to_file(), this function compiles the merged module into 146 /// single output file. Instead of returning the output file path to the 147 /// caller (linker), it brings the output to a buffer, and returns the buffer 148 /// to the caller. This function should delete the intermediate file once 149 /// its content is brought to memory. Return NULL if the compilation was not 150 /// successful. 151 std::unique_ptr<MemoryBuffer> compile(bool DisableVerify, bool DisableInline, 152 bool DisableGVNLoadPRE, 153 bool DisableVectorization); 154 155 /// Optimizes the merged module. Returns true on success. 156 /// 157 /// Calls \a verifyMergedModuleOnce(). 158 bool optimize(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, 159 bool DisableVectorization); 160 161 /// Compiles the merged optimized module into a single output file. It brings 162 /// the output to a buffer, and returns the buffer to the caller. Return NULL 163 /// if the compilation was not successful. 164 std::unique_ptr<MemoryBuffer> compileOptimized(); 165 166 /// Compile the merged optimized module into out.size() output files each 167 /// representing a linkable partition of the module. If out contains more 168 /// than one element, code generation is done in parallel with out.size() 169 /// threads. Output files will be written to members of out. Returns true on 170 /// success. 171 /// 172 /// Calls \a verifyMergedModuleOnce(). 173 bool compileOptimized(ArrayRef<raw_pwrite_stream *> Out); 174 175 void setDiagnosticHandler(lto_diagnostic_handler_t, void *); 176 177 LLVMContext &getContext() { return Context; } 178 179 void resetMergedModule() { MergedModule.reset(); } 180 181 private: 182 void initializeLTOPasses(); 183 184 /// Verify the merged module on first call. 185 /// 186 /// Sets \a HasVerifiedInput on first call and doesn't run again on the same 187 /// input. 188 void verifyMergedModuleOnce(); 189 190 bool compileOptimizedToFile(const char **Name); 191 void restoreLinkageForExternals(); 192 void applyScopeRestrictions(); 193 void preserveDiscardableGVs( 194 Module &TheModule, 195 llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV); 196 197 bool determineTarget(); 198 std::unique_ptr<TargetMachine> createTargetMachine(); 199 200 static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context); 201 202 void DiagnosticHandler2(const DiagnosticInfo &DI); 203 204 void emitError(const std::string &ErrMsg); 205 void emitWarning(const std::string &ErrMsg); 206 207 LLVMContext &Context; 208 std::unique_ptr<Module> MergedModule; 209 std::unique_ptr<Linker> TheLinker; 210 std::unique_ptr<TargetMachine> TargetMach; 211 bool EmitDwarfDebugInfo = false; 212 bool ScopeRestrictionsDone = false; 213 bool HasVerifiedInput = false; 214 Optional<Reloc::Model> RelocModel; 215 StringSet<> MustPreserveSymbols; 216 StringSet<> AsmUndefinedRefs; 217 StringMap<GlobalValue::LinkageTypes> ExternalSymbols; 218 std::vector<std::string> CodegenOptions; 219 std::string FeatureStr; 220 std::string MCpu; 221 std::string MAttr; 222 std::string NativeObjectPath; 223 TargetOptions Options; 224 CodeGenOpt::Level CGOptLevel = CodeGenOpt::Default; 225 const Target *MArch = nullptr; 226 std::string TripleStr; 227 unsigned OptLevel = 2; 228 lto_diagnostic_handler_t DiagHandler = nullptr; 229 void *DiagContext = nullptr; 230 bool ShouldInternalize = true; 231 bool ShouldEmbedUselists = false; 232 bool ShouldRestoreGlobalsLinkage = false; 233 TargetMachine::CodeGenFileType FileType = TargetMachine::CGFT_ObjectFile; 234 }; 235 } 236 #endif 237