1 //===-LTOCodeGenerator.cpp - 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 implements the 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/LTO/LTOCodeGenerator.h" 16 #include "llvm/LTO/LTOModule.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/Analysis/Passes.h" 19 #include "llvm/Analysis/Verifier.h" 20 #include "llvm/Bitcode/ReaderWriter.h" 21 #include "llvm/Config/config.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/LLVMContext.h" 26 #include "llvm/IR/Module.h" 27 #include "llvm/InitializePasses.h" 28 #include "llvm/Linker.h" 29 #include "llvm/MC/MCAsmInfo.h" 30 #include "llvm/MC/MCContext.h" 31 #include "llvm/MC/SubtargetFeature.h" 32 #include "llvm/PassManager.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/FileSystem.h" 35 #include "llvm/Support/FormattedStream.h" 36 #include "llvm/Support/Host.h" 37 #include "llvm/Support/MemoryBuffer.h" 38 #include "llvm/Support/Signals.h" 39 #include "llvm/Support/TargetRegistry.h" 40 #include "llvm/Support/TargetSelect.h" 41 #include "llvm/Support/ToolOutputFile.h" 42 #include "llvm/Support/system_error.h" 43 #include "llvm/Target/TargetOptions.h" 44 #include "llvm/Target/TargetRegisterInfo.h" 45 #include "llvm/Target/Mangler.h" 46 #include "llvm/Transforms/IPO.h" 47 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 48 #include "llvm/Transforms/ObjCARC.h" 49 using namespace llvm; 50 51 const char* LTOCodeGenerator::getVersionString() { 52 #ifdef LLVM_VERSION_INFO 53 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO; 54 #else 55 return PACKAGE_NAME " version " PACKAGE_VERSION; 56 #endif 57 } 58 59 LTOCodeGenerator::LTOCodeGenerator() 60 : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)), 61 TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false), 62 CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL) { 63 initializeLTOPasses(); 64 } 65 66 LTOCodeGenerator::~LTOCodeGenerator() { 67 delete TargetMach; 68 delete NativeObjectFile; 69 delete Linker.getModule(); 70 71 for (std::vector<char *>::iterator I = CodegenOptions.begin(), 72 E = CodegenOptions.end(); 73 I != E; ++I) 74 free(*I); 75 } 76 77 // Initialize LTO passes. Please keep this funciton in sync with 78 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO 79 // passes are initialized. 80 // 81 void LTOCodeGenerator::initializeLTOPasses() { 82 PassRegistry &R = *PassRegistry::getPassRegistry(); 83 84 initializeInternalizePassPass(R); 85 initializeIPSCCPPass(R); 86 initializeGlobalOptPass(R); 87 initializeConstantMergePass(R); 88 initializeDAHPass(R); 89 initializeInstCombinerPass(R); 90 initializeSimpleInlinerPass(R); 91 initializePruneEHPass(R); 92 initializeGlobalDCEPass(R); 93 initializeArgPromotionPass(R); 94 initializeJumpThreadingPass(R); 95 initializeSROAPass(R); 96 initializeSROA_DTPass(R); 97 initializeSROA_SSAUpPass(R); 98 initializeFunctionAttrsPass(R); 99 initializeGlobalsModRefPass(R); 100 initializeLICMPass(R); 101 initializeGVNPass(R); 102 initializeMemCpyOptPass(R); 103 initializeDCEPass(R); 104 initializeCFGSimplifyPassPass(R); 105 } 106 107 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) { 108 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg); 109 110 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs(); 111 for (int i = 0, e = undefs.size(); i != e; ++i) 112 AsmUndefinedRefs[undefs[i]] = 1; 113 114 return !ret; 115 } 116 117 void LTOCodeGenerator::setTargetOptions(TargetOptions options) { 118 Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption; 119 Options.NoFramePointerElim = options.NoFramePointerElim; 120 Options.AllowFPOpFusion = options.AllowFPOpFusion; 121 Options.UnsafeFPMath = options.UnsafeFPMath; 122 Options.NoInfsFPMath = options.NoInfsFPMath; 123 Options.NoNaNsFPMath = options.NoNaNsFPMath; 124 Options.HonorSignDependentRoundingFPMathOption = 125 options.HonorSignDependentRoundingFPMathOption; 126 Options.UseSoftFloat = options.UseSoftFloat; 127 Options.FloatABIType = options.FloatABIType; 128 Options.NoZerosInBSS = options.NoZerosInBSS; 129 Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt; 130 Options.DisableTailCalls = options.DisableTailCalls; 131 Options.StackAlignmentOverride = options.StackAlignmentOverride; 132 Options.TrapFuncName = options.TrapFuncName; 133 Options.PositionIndependentExecutable = options.PositionIndependentExecutable; 134 Options.EnableSegmentedStacks = options.EnableSegmentedStacks; 135 Options.UseInitArray = options.UseInitArray; 136 } 137 138 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) { 139 switch (debug) { 140 case LTO_DEBUG_MODEL_NONE: 141 EmitDwarfDebugInfo = false; 142 return; 143 144 case LTO_DEBUG_MODEL_DWARF: 145 EmitDwarfDebugInfo = true; 146 return; 147 } 148 llvm_unreachable("Unknown debug format!"); 149 } 150 151 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) { 152 switch (model) { 153 case LTO_CODEGEN_PIC_MODEL_STATIC: 154 case LTO_CODEGEN_PIC_MODEL_DYNAMIC: 155 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC: 156 CodeModel = model; 157 return; 158 } 159 llvm_unreachable("Unknown PIC model!"); 160 } 161 162 bool LTOCodeGenerator::writeMergedModules(const char *path, 163 std::string &errMsg) { 164 if (!determineTarget(errMsg)) 165 return false; 166 167 // mark which symbols can not be internalized 168 applyScopeRestrictions(); 169 170 // create output file 171 std::string ErrInfo; 172 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary); 173 if (!ErrInfo.empty()) { 174 errMsg = "could not open bitcode file for writing: "; 175 errMsg += path; 176 return false; 177 } 178 179 // write bitcode to it 180 WriteBitcodeToFile(Linker.getModule(), Out.os()); 181 Out.os().close(); 182 183 if (Out.os().has_error()) { 184 errMsg = "could not write bitcode file: "; 185 errMsg += path; 186 Out.os().clear_error(); 187 return false; 188 } 189 190 Out.keep(); 191 return true; 192 } 193 194 bool LTOCodeGenerator::compile_to_file(const char** name, 195 bool disableOpt, 196 bool disableInline, 197 bool disableGVNLoadPRE, 198 std::string& errMsg) { 199 // make unique temp .o file to put generated object file 200 SmallString<128> Filename; 201 int FD; 202 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename); 203 if (EC) { 204 errMsg = EC.message(); 205 return false; 206 } 207 208 // generate object file 209 tool_output_file objFile(Filename.c_str(), FD); 210 211 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline, 212 disableGVNLoadPRE, errMsg); 213 objFile.os().close(); 214 if (objFile.os().has_error()) { 215 objFile.os().clear_error(); 216 sys::fs::remove(Twine(Filename)); 217 return false; 218 } 219 220 objFile.keep(); 221 if (!genResult) { 222 sys::fs::remove(Twine(Filename)); 223 return false; 224 } 225 226 NativeObjectPath = Filename.c_str(); 227 *name = NativeObjectPath.c_str(); 228 return true; 229 } 230 231 const void* LTOCodeGenerator::compile(size_t* length, 232 bool disableOpt, 233 bool disableInline, 234 bool disableGVNLoadPRE, 235 std::string& errMsg) { 236 const char *name; 237 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE, 238 errMsg)) 239 return NULL; 240 241 // remove old buffer if compile() called twice 242 delete NativeObjectFile; 243 244 // read .o file into memory buffer 245 OwningPtr<MemoryBuffer> BuffPtr; 246 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) { 247 errMsg = ec.message(); 248 sys::fs::remove(NativeObjectPath); 249 return NULL; 250 } 251 NativeObjectFile = BuffPtr.take(); 252 253 // remove temp files 254 sys::fs::remove(NativeObjectPath); 255 256 // return buffer, unless error 257 if (NativeObjectFile == NULL) 258 return NULL; 259 *length = NativeObjectFile->getBufferSize(); 260 return NativeObjectFile->getBufferStart(); 261 } 262 263 bool LTOCodeGenerator::determineTarget(std::string &errMsg) { 264 if (TargetMach != NULL) 265 return true; 266 267 std::string TripleStr = Linker.getModule()->getTargetTriple(); 268 if (TripleStr.empty()) 269 TripleStr = sys::getDefaultTargetTriple(); 270 llvm::Triple Triple(TripleStr); 271 272 // create target machine from info for merged modules 273 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg); 274 if (march == NULL) 275 return false; 276 277 // The relocation model is actually a static member of TargetMachine and 278 // needs to be set before the TargetMachine is instantiated. 279 Reloc::Model RelocModel = Reloc::Default; 280 switch (CodeModel) { 281 case LTO_CODEGEN_PIC_MODEL_STATIC: 282 RelocModel = Reloc::Static; 283 break; 284 case LTO_CODEGEN_PIC_MODEL_DYNAMIC: 285 RelocModel = Reloc::PIC_; 286 break; 287 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC: 288 RelocModel = Reloc::DynamicNoPIC; 289 break; 290 } 291 292 // construct LTOModule, hand over ownership of module and target 293 SubtargetFeatures Features; 294 Features.getDefaultSubtargetFeatures(Triple); 295 std::string FeatureStr = Features.getString(); 296 // Set a default CPU for Darwin triples. 297 if (MCpu.empty() && Triple.isOSDarwin()) { 298 if (Triple.getArch() == llvm::Triple::x86_64) 299 MCpu = "core2"; 300 else if (Triple.getArch() == llvm::Triple::x86) 301 MCpu = "yonah"; 302 } 303 304 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options, 305 RelocModel, CodeModel::Default, 306 CodeGenOpt::Aggressive); 307 return true; 308 } 309 310 void LTOCodeGenerator:: 311 applyRestriction(GlobalValue &GV, 312 std::vector<const char*> &MustPreserveList, 313 std::vector<const char*> &DSOList, 314 SmallPtrSet<GlobalValue*, 8> &AsmUsed, 315 Mangler &Mangler) { 316 SmallString<64> Buffer; 317 Mangler.getNameWithPrefix(Buffer, &GV, false); 318 319 if (GV.isDeclaration()) 320 return; 321 if (MustPreserveSymbols.count(Buffer)) 322 MustPreserveList.push_back(GV.getName().data()); 323 if (DSOSymbols.count(Buffer)) 324 DSOList.push_back(GV.getName().data()); 325 if (AsmUndefinedRefs.count(Buffer)) 326 AsmUsed.insert(&GV); 327 } 328 329 static void findUsedValues(GlobalVariable *LLVMUsed, 330 SmallPtrSet<GlobalValue*, 8> &UsedValues) { 331 if (LLVMUsed == 0) return; 332 333 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer()); 334 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) 335 if (GlobalValue *GV = 336 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts())) 337 UsedValues.insert(GV); 338 } 339 340 void LTOCodeGenerator::applyScopeRestrictions() { 341 if (ScopeRestrictionsDone) 342 return; 343 Module *mergedModule = Linker.getModule(); 344 345 // Start off with a verification pass. 346 PassManager passes; 347 passes.add(createVerifierPass()); 348 349 // mark which symbols can not be internalized 350 MCContext MContext(TargetMach->getMCAsmInfo(), TargetMach->getRegisterInfo(), 351 NULL); 352 Mangler Mangler(MContext, TargetMach); 353 std::vector<const char*> MustPreserveList; 354 std::vector<const char*> DSOList; 355 SmallPtrSet<GlobalValue*, 8> AsmUsed; 356 357 for (Module::iterator f = mergedModule->begin(), 358 e = mergedModule->end(); f != e; ++f) 359 applyRestriction(*f, MustPreserveList, DSOList, AsmUsed, Mangler); 360 for (Module::global_iterator v = mergedModule->global_begin(), 361 e = mergedModule->global_end(); v != e; ++v) 362 applyRestriction(*v, MustPreserveList, DSOList, AsmUsed, Mangler); 363 for (Module::alias_iterator a = mergedModule->alias_begin(), 364 e = mergedModule->alias_end(); a != e; ++a) 365 applyRestriction(*a, MustPreserveList, DSOList, AsmUsed, Mangler); 366 367 GlobalVariable *LLVMCompilerUsed = 368 mergedModule->getGlobalVariable("llvm.compiler.used"); 369 findUsedValues(LLVMCompilerUsed, AsmUsed); 370 if (LLVMCompilerUsed) 371 LLVMCompilerUsed->eraseFromParent(); 372 373 if (!AsmUsed.empty()) { 374 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context); 375 std::vector<Constant*> asmUsed2; 376 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(), 377 e = AsmUsed.end(); i !=e; ++i) { 378 GlobalValue *GV = *i; 379 Constant *c = ConstantExpr::getBitCast(GV, i8PTy); 380 asmUsed2.push_back(c); 381 } 382 383 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size()); 384 LLVMCompilerUsed = 385 new llvm::GlobalVariable(*mergedModule, ATy, false, 386 llvm::GlobalValue::AppendingLinkage, 387 llvm::ConstantArray::get(ATy, asmUsed2), 388 "llvm.compiler.used"); 389 390 LLVMCompilerUsed->setSection("llvm.metadata"); 391 } 392 393 passes.add(createInternalizePass(MustPreserveList, DSOList)); 394 395 // apply scope restrictions 396 passes.run(*mergedModule); 397 398 ScopeRestrictionsDone = true; 399 } 400 401 /// Optimize merged modules using various IPO passes 402 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out, 403 bool DisableOpt, 404 bool DisableInline, 405 bool DisableGVNLoadPRE, 406 std::string &errMsg) { 407 if (!this->determineTarget(errMsg)) 408 return false; 409 410 Module *mergedModule = Linker.getModule(); 411 412 // Mark which symbols can not be internalized 413 this->applyScopeRestrictions(); 414 415 // Instantiate the pass manager to organize the passes. 416 PassManager passes; 417 418 // Start off with a verification pass. 419 passes.add(createVerifierPass()); 420 421 // Add an appropriate DataLayout instance for this module... 422 passes.add(new DataLayout(*TargetMach->getDataLayout())); 423 TargetMach->addAnalysisPasses(passes); 424 425 // Enabling internalize here would use its AllButMain variant. It 426 // keeps only main if it exists and does nothing for libraries. Instead 427 // we create the pass ourselves with the symbol list provided by the linker. 428 if (!DisableOpt) 429 PassManagerBuilder().populateLTOPassManager(passes, 430 /*Internalize=*/false, 431 !DisableInline, 432 DisableGVNLoadPRE); 433 434 // Make sure everything is still good. 435 passes.add(createVerifierPass()); 436 437 PassManager codeGenPasses; 438 439 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout())); 440 TargetMach->addAnalysisPasses(codeGenPasses); 441 442 formatted_raw_ostream Out(out); 443 444 // If the bitcode files contain ARC code and were compiled with optimization, 445 // the ObjCARCContractPass must be run, so do it unconditionally here. 446 codeGenPasses.add(createObjCARCContractPass()); 447 448 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out, 449 TargetMachine::CGFT_ObjectFile)) { 450 errMsg = "target file type not supported"; 451 return false; 452 } 453 454 // Run our queue of passes all at once now, efficiently. 455 passes.run(*mergedModule); 456 457 // Run the code generator, and write assembly file 458 codeGenPasses.run(*mergedModule); 459 460 return true; 461 } 462 463 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging 464 /// LTO problems. 465 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) { 466 for (std::pair<StringRef, StringRef> o = getToken(options); 467 !o.first.empty(); o = getToken(o.second)) { 468 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add 469 // that. 470 if (CodegenOptions.empty()) 471 CodegenOptions.push_back(strdup("libLLVMLTO")); 472 CodegenOptions.push_back(strdup(o.first.str().c_str())); 473 } 474 } 475 476 void LTOCodeGenerator::parseCodeGenDebugOptions() { 477 // if options were requested, set them 478 if (!CodegenOptions.empty()) 479 cl::ParseCommandLineOptions(CodegenOptions.size(), 480 const_cast<char **>(&CodegenOptions[0])); 481 } 482