lto.cpp revision e5c9cb5eb6bce502faaedea04014dab46f6540f4
1//===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by Devang Patel and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implementes link time optimization library. This library is 11// intended to be used by linker to optimize code at link time. 12// 13//===----------------------------------------------------------------------===// 14 15#include "llvm/Module.h" 16#include "llvm/PassManager.h" 17#include "llvm/Linker.h" 18#include "llvm/Constants.h" 19#include "llvm/DerivedTypes.h" 20#include "llvm/SymbolTable.h" 21#include "llvm/Bytecode/Reader.h" 22#include "llvm/Bytecode/Writer.h" 23#include "llvm/Support/CommandLine.h" 24#include "llvm/Support/FileUtilities.h" 25#include "llvm/Support/SystemUtils.h" 26#include "llvm/Support/Mangler.h" 27#include "llvm/System/Program.h" 28#include "llvm/System/Signals.h" 29#include "llvm/Analysis/Passes.h" 30#include "llvm/Analysis/Verifier.h" 31#include "llvm/Target/SubtargetFeature.h" 32#include "llvm/Target/TargetData.h" 33#include "llvm/Target/TargetMachine.h" 34#include "llvm/Target/TargetMachineRegistry.h" 35#include "llvm/Transforms/IPO.h" 36#include "llvm/Transforms/Scalar.h" 37#include "llvm/Analysis/LoadValueNumbering.h" 38#include "llvm/LinkTimeOptimizer.h" 39#include <fstream> 40#include <iostream> 41 42using namespace llvm; 43 44extern "C" 45llvm::LinkTimeOptimizer *createLLVMOptimizer() 46{ 47 llvm::LinkTimeOptimizer *l = new llvm::LinkTimeOptimizer(); 48 return l; 49} 50 51 52 53/// If symbol is not used then make it internal and let optimizer takes 54/// care of it. 55void LLVMSymbol::mayBeNotUsed() { 56 gv->setLinkage(GlobalValue::InternalLinkage); 57} 58 59// Helper routine 60// FIXME : Take advantage of GlobalPrefix from AsmPrinter 61static const char *addUnderscore(const char *name) { 62 size_t namelen = strlen(name); 63 char *symName = (char*)malloc(namelen+2); 64 symName[0] = '_'; 65 strcpy(&symName[1], name); 66 return symName; 67} 68 69// Map LLVM LinkageType to LTO LinakgeType 70static LTOLinkageTypes 71getLTOLinkageType(GlobalValue *v) 72{ 73 LTOLinkageTypes lt; 74 if (v->hasExternalLinkage()) 75 lt = LTOExternalLinkage; 76 else if (v->hasLinkOnceLinkage()) 77 lt = LTOLinkOnceLinkage; 78 else if (v->hasWeakLinkage()) 79 lt = LTOWeakLinkage; 80 else 81 // Otherwise it is internal linkage for link time optimizer 82 lt = LTOInternalLinkage; 83 return lt; 84} 85 86// Find exeternal symbols referenced by VALUE. This is a recursive function. 87static void 88findExternalRefs(Value *value, std::set<std::string> &references, 89 Mangler &mangler) { 90 91 if (GlobalValue *gv = dyn_cast<GlobalValue>(value)) { 92 LTOLinkageTypes lt = getLTOLinkageType(gv); 93 if (lt != LTOInternalLinkage && strncmp (gv->getName().c_str(), "llvm.", 5)) 94 references.insert(mangler.getValueName(gv)); 95 } 96 else if (Constant *c = dyn_cast<Constant>(value)) 97 // Handle ConstantExpr, ConstantStruct, ConstantArry etc.. 98 for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i) 99 findExternalRefs(c->getOperand(i), references, mangler); 100} 101 102/// InputFilename is a LLVM bytecode file. Read it using bytecode reader. 103/// Collect global functions and symbol names in symbols vector. 104/// Collect external references in references vector. 105/// Return LTO_READ_SUCCESS if there is no error. 106enum LTOStatus 107LinkTimeOptimizer::readLLVMObjectFile(const std::string &InputFilename, 108 NameToSymbolMap &symbols, 109 std::set<std::string> &references) 110{ 111 Module *m = ParseBytecodeFile(InputFilename); 112 if (!m) 113 return LTO_READ_FAILURE; 114 115 // Use mangler to add GlobalPrefix to names to match linker names. 116 // FIXME : Instead of hard coding "-" use GlobalPrefix. 117 Mangler mangler(*m, "_"); 118 119 modules.push_back(m); 120 121 for (Module::iterator f = m->begin(), e = m->end(); f != e; ++f) { 122 123 LTOLinkageTypes lt = getLTOLinkageType(f); 124 125 if (!f->isExternal() && lt != LTOInternalLinkage 126 && strncmp (f->getName().c_str(), "llvm.", 5)) { 127 LLVMSymbol *newSymbol = new LLVMSymbol(lt, f, f->getName(), 128 mangler.getValueName(f)); 129 symbols[newSymbol->getMangledName()] = newSymbol; 130 allSymbols[newSymbol->getMangledName()] = newSymbol; 131 } 132 133 // Collect external symbols referenced by this function. 134 for (Function::iterator b = f->begin(), fe = f->end(); b != fe; ++b) 135 for (BasicBlock::iterator i = b->begin(), be = b->end(); 136 i != be; ++i) 137 for (unsigned count = 0, total = i->getNumOperands(); 138 count != total; ++count) 139 findExternalRefs(i->getOperand(count), references, mangler); 140 } 141 142 for (Module::global_iterator v = m->global_begin(), e = m->global_end(); 143 v != e; ++v) { 144 LTOLinkageTypes lt = getLTOLinkageType(v); 145 if (!v->isExternal() && lt != LTOInternalLinkage 146 && strncmp (v->getName().c_str(), "llvm.", 5)) { 147 LLVMSymbol *newSymbol = new LLVMSymbol(lt, v, v->getName(), 148 mangler.getValueName(v)); 149 symbols[newSymbol->getMangledName()] = newSymbol; 150 151 for (unsigned count = 0, total = v->getNumOperands(); 152 count != total; ++count) 153 findExternalRefs(v->getOperand(count), references, mangler); 154 155 } 156 } 157 158 return LTO_READ_SUCCESS; 159} 160 161/// Optimize module M using various IPO passes. Use exportList to 162/// internalize selected symbols. Target platform is selected 163/// based on information available to module M. No new target 164/// features are selected. 165static enum LTOStatus lto_optimize(Module *M, std::ostream &Out, 166 std::vector<const char *> &exportList) 167{ 168 // Instantiate the pass manager to organize the passes. 169 PassManager Passes; 170 171 // Collect Target info 172 std::string Err; 173 const TargetMachineRegistry::Entry* March = 174 TargetMachineRegistry::getClosestStaticTargetForModule(*M, Err); 175 176 if (March == 0) 177 return LTO_NO_TARGET; 178 179 // Create target 180 std::string Features; 181 std::auto_ptr<TargetMachine> target(March->CtorFn(*M, Features)); 182 if (!target.get()) 183 return LTO_NO_TARGET; 184 185 TargetMachine &Target = *target.get(); 186 187 // Start off with a verification pass. 188 Passes.add(createVerifierPass()); 189 190 // Add an appropriate TargetData instance for this module... 191 Passes.add(new TargetData(*Target.getTargetData())); 192 193 // Often if the programmer does not specify proper prototypes for the 194 // functions they are calling, they end up calling a vararg version of the 195 // function that does not get a body filled in (the real function has typed 196 // arguments). This pass merges the two functions. 197 Passes.add(createFunctionResolvingPass()); 198 199 // Internalize symbols if export list is nonemty 200 if (!exportList.empty()) 201 Passes.add(createInternalizePass(exportList)); 202 203 // Now that we internalized some globals, see if we can hack on them! 204 Passes.add(createGlobalOptimizerPass()); 205 206 // Linking modules together can lead to duplicated global constants, only 207 // keep one copy of each constant... 208 Passes.add(createConstantMergePass()); 209 210 // If the -s command line option was specified, strip the symbols out of the 211 // resulting program to make it smaller. -s is a GLD option that we are 212 // supporting. 213 Passes.add(createStripSymbolsPass()); 214 215 // Propagate constants at call sites into the functions they call. 216 Passes.add(createIPConstantPropagationPass()); 217 218 // Remove unused arguments from functions... 219 Passes.add(createDeadArgEliminationPass()); 220 221 Passes.add(createFunctionInliningPass()); // Inline small functions 222 223 Passes.add(createPruneEHPass()); // Remove dead EH info 224 225 Passes.add(createGlobalDCEPass()); // Remove dead functions 226 227 // If we didn't decide to inline a function, check to see if we can 228 // transform it to pass arguments by value instead of by reference. 229 Passes.add(createArgumentPromotionPass()); 230 231 // The IPO passes may leave cruft around. Clean up after them. 232 Passes.add(createInstructionCombiningPass()); 233 234 Passes.add(createScalarReplAggregatesPass()); // Break up allocas 235 236 // Run a few AA driven optimizations here and now, to cleanup the code. 237 Passes.add(createGlobalsModRefPass()); // IP alias analysis 238 239 Passes.add(createLICMPass()); // Hoist loop invariants 240 Passes.add(createLoadValueNumberingPass()); // GVN for load instrs 241 Passes.add(createGCSEPass()); // Remove common subexprs 242 Passes.add(createDeadStoreEliminationPass()); // Nuke dead stores 243 244 // Cleanup and simplify the code after the scalar optimizations. 245 Passes.add(createInstructionCombiningPass()); 246 247 // Delete basic blocks, which optimization passes may have killed... 248 Passes.add(createCFGSimplificationPass()); 249 250 // Now that we have optimized the program, discard unreachable functions... 251 Passes.add(createGlobalDCEPass()); 252 253 // Make sure everything is still good. 254 Passes.add(createVerifierPass()); 255 256 Target.addPassesToEmitFile(Passes, Out, TargetMachine::AssemblyFile, true); 257 258 // Run our queue of passes all at once now, efficiently. 259 Passes.run(*M); 260 261 return LTO_OPT_SUCCESS; 262} 263 264///Link all modules together and optimize them using IPO. Generate 265/// native object file using OutputFilename 266/// Return appropriate LTOStatus. 267enum LTOStatus 268LinkTimeOptimizer::optimizeModules(const std::string &OutputFilename, 269 std::vector<const char *> &exportList) 270{ 271 if (modules.empty()) 272 return LTO_NO_WORK; 273 274 std::ios::openmode io_mode = 275 std::ios::out | std::ios::trunc | std::ios::binary; 276 std::string *errMsg = NULL; 277 Module *bigOne = modules[0]; 278 Linker theLinker("LinkTimeOptimizer", bigOne, false); 279 for (unsigned i = 1, e = modules.size(); i != e; ++i) 280 if (theLinker.LinkModules(bigOne, modules[i], errMsg)) 281 return LTO_MODULE_MERGE_FAILURE; 282 283#if 0 284 // Enable this when -save-temps is used 285 std::ofstream Out("big.bc", io_mode); 286 WriteBytecodeToFile(bigOne, Out, true); 287#endif 288 289 // Strip leading underscore because it was added to match names 290 // seen by linker. 291 for (unsigned i = 0, e = exportList.size(); i != e; ++i) { 292 const char *name = exportList[i]; 293 if (strlen(name) > 2 && name[0] == '_') 294 exportList[i] = &name[1]; 295 } 296 297 sys::Path tmpAsmFilePath("/tmp/"); 298 std::string ErrMsg; 299 if (tmpAsmFilePath.createTemporaryFileOnDisk(&ErrMsg)) { 300 std::cerr << "lto: " << ErrMsg << "\n"; 301 return; 302 } 303 sys::RemoveFileOnSignal(tmpAsmFilePath); 304 305 std::ofstream asmFile(tmpAsmFilePath.c_str(), io_mode); 306 if (!asmFile.is_open() || asmFile.bad()) { 307 if (tmpAsmFilePath.exists()) 308 tmpAsmFilePath.eraseFromDisk(); 309 return LTO_WRITE_FAILURE; 310 } 311 312 enum LTOStatus status = lto_optimize(bigOne, asmFile, exportList); 313 asmFile.close(); 314 if (status != LTO_OPT_SUCCESS) { 315 tmpAsmFilePath.eraseFromDisk(); 316 return status; 317 } 318 319 // Run GCC to assemble and link the program into native code. 320 // 321 // Note: 322 // We can't just assemble and link the file with the system assembler 323 // and linker because we don't know where to put the _start symbol. 324 // GCC mysteriously knows how to do it. 325 const sys::Path gcc = FindExecutable("gcc", "/"); 326 if (gcc.isEmpty()) { 327 tmpAsmFilePath.eraseFromDisk(); 328 return LTO_ASM_FAILURE; 329 } 330 331 std::vector<const char*> args; 332 args.push_back(gcc.c_str()); 333 args.push_back("-c"); 334 args.push_back("-x"); 335 args.push_back("assembler"); 336 args.push_back("-o"); 337 args.push_back(OutputFilename.c_str()); 338 args.push_back(tmpAsmFilePath.c_str()); 339 args.push_back(0); 340 341 sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 1); 342 343 tmpAsmFilePath.eraseFromDisk(); 344 345 return LTO_OPT_SUCCESS; 346} 347