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/ADT/StringExtras.h" 17 #include "llvm/Analysis/Passes.h" 18 #include "llvm/Analysis/TargetLibraryInfo.h" 19 #include "llvm/Analysis/TargetTransformInfo.h" 20 #include "llvm/Bitcode/ReaderWriter.h" 21 #include "llvm/CodeGen/ParallelCG.h" 22 #include "llvm/CodeGen/RuntimeLibcalls.h" 23 #include "llvm/Config/config.h" 24 #include "llvm/IR/Constants.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/DerivedTypes.h" 27 #include "llvm/IR/DiagnosticInfo.h" 28 #include "llvm/IR/DiagnosticPrinter.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/LegacyPassManager.h" 31 #include "llvm/IR/Mangler.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/Verifier.h" 34 #include "llvm/InitializePasses.h" 35 #include "llvm/LTO/LTOModule.h" 36 #include "llvm/Linker/Linker.h" 37 #include "llvm/MC/MCAsmInfo.h" 38 #include "llvm/MC/MCContext.h" 39 #include "llvm/MC/SubtargetFeature.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/FileSystem.h" 42 #include "llvm/Support/Host.h" 43 #include "llvm/Support/MemoryBuffer.h" 44 #include "llvm/Support/Signals.h" 45 #include "llvm/Support/TargetRegistry.h" 46 #include "llvm/Support/TargetSelect.h" 47 #include "llvm/Support/ToolOutputFile.h" 48 #include "llvm/Support/raw_ostream.h" 49 #include "llvm/Target/TargetLowering.h" 50 #include "llvm/Target/TargetOptions.h" 51 #include "llvm/Target/TargetRegisterInfo.h" 52 #include "llvm/Target/TargetSubtargetInfo.h" 53 #include "llvm/Transforms/IPO.h" 54 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 55 #include "llvm/Transforms/ObjCARC.h" 56 #include <system_error> 57 using namespace llvm; 58 59 const char* LTOCodeGenerator::getVersionString() { 60 #ifdef LLVM_VERSION_INFO 61 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO; 62 #else 63 return PACKAGE_NAME " version " PACKAGE_VERSION; 64 #endif 65 } 66 67 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context) 68 : Context(Context), MergedModule(new Module("ld-temp.o", Context)), 69 IRLinker(new Linker(*MergedModule, [this](const DiagnosticInfo &DI) { 70 MergedModule->getContext().diagnose(DI); 71 })) { 72 initializeLTOPasses(); 73 } 74 75 LTOCodeGenerator::~LTOCodeGenerator() {} 76 77 // Initialize LTO passes. Please keep this function in sync with 78 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO 79 // passes are initialized. 80 void LTOCodeGenerator::initializeLTOPasses() { 81 PassRegistry &R = *PassRegistry::getPassRegistry(); 82 83 initializeInternalizePassPass(R); 84 initializeIPSCCPPass(R); 85 initializeGlobalOptPass(R); 86 initializeConstantMergePass(R); 87 initializeDAHPass(R); 88 initializeInstructionCombiningPassPass(R); 89 initializeSimpleInlinerPass(R); 90 initializePruneEHPass(R); 91 initializeGlobalDCEPass(R); 92 initializeArgPromotionPass(R); 93 initializeJumpThreadingPass(R); 94 initializeSROALegacyPassPass(R); 95 initializeSROA_DTPass(R); 96 initializeSROA_SSAUpPass(R); 97 initializeFunctionAttrsPass(R); 98 initializeGlobalsAAWrapperPassPass(R); 99 initializeLICMPass(R); 100 initializeMergedLoadStoreMotionPass(R); 101 initializeGVNPass(R); 102 initializeMemCpyOptPass(R); 103 initializeDCEPass(R); 104 initializeCFGSimplifyPassPass(R); 105 } 106 107 bool LTOCodeGenerator::addModule(LTOModule *Mod) { 108 assert(&Mod->getModule().getContext() == &Context && 109 "Expected module in same context"); 110 111 bool ret = IRLinker->linkInModule(Mod->getModule()); 112 113 const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs(); 114 for (int i = 0, e = undefs.size(); i != e; ++i) 115 AsmUndefinedRefs[undefs[i]] = 1; 116 117 return !ret; 118 } 119 120 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) { 121 assert(&Mod->getModule().getContext() == &Context && 122 "Expected module in same context"); 123 124 AsmUndefinedRefs.clear(); 125 126 MergedModule = Mod->takeModule(); 127 IRLinker = llvm::make_unique<Linker>(*MergedModule, 128 IRLinker->getDiagnosticHandler()); 129 130 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs(); 131 for (int I = 0, E = Undefs.size(); I != E; ++I) 132 AsmUndefinedRefs[Undefs[I]] = 1; 133 } 134 135 void LTOCodeGenerator::setTargetOptions(TargetOptions Options) { 136 this->Options = Options; 137 } 138 139 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) { 140 switch (Debug) { 141 case LTO_DEBUG_MODEL_NONE: 142 EmitDwarfDebugInfo = false; 143 return; 144 145 case LTO_DEBUG_MODEL_DWARF: 146 EmitDwarfDebugInfo = true; 147 return; 148 } 149 llvm_unreachable("Unknown debug format!"); 150 } 151 152 void LTOCodeGenerator::setOptLevel(unsigned Level) { 153 OptLevel = Level; 154 switch (OptLevel) { 155 case 0: 156 CGOptLevel = CodeGenOpt::None; 157 break; 158 case 1: 159 CGOptLevel = CodeGenOpt::Less; 160 break; 161 case 2: 162 CGOptLevel = CodeGenOpt::Default; 163 break; 164 case 3: 165 CGOptLevel = CodeGenOpt::Aggressive; 166 break; 167 } 168 } 169 170 bool LTOCodeGenerator::writeMergedModules(const char *Path) { 171 if (!determineTarget()) 172 return false; 173 174 // mark which symbols can not be internalized 175 applyScopeRestrictions(); 176 177 // create output file 178 std::error_code EC; 179 tool_output_file Out(Path, EC, sys::fs::F_None); 180 if (EC) { 181 std::string ErrMsg = "could not open bitcode file for writing: "; 182 ErrMsg += Path; 183 emitError(ErrMsg); 184 return false; 185 } 186 187 // write bitcode to it 188 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists); 189 Out.os().close(); 190 191 if (Out.os().has_error()) { 192 std::string ErrMsg = "could not write bitcode file: "; 193 ErrMsg += Path; 194 emitError(ErrMsg); 195 Out.os().clear_error(); 196 return false; 197 } 198 199 Out.keep(); 200 return true; 201 } 202 203 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) { 204 // make unique temp output file to put generated code 205 SmallString<128> Filename; 206 int FD; 207 208 const char *Extension = 209 (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o"); 210 211 std::error_code EC = 212 sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename); 213 if (EC) { 214 emitError(EC.message()); 215 return false; 216 } 217 218 // generate object file 219 tool_output_file objFile(Filename.c_str(), FD); 220 221 bool genResult = compileOptimized(&objFile.os()); 222 objFile.os().close(); 223 if (objFile.os().has_error()) { 224 objFile.os().clear_error(); 225 sys::fs::remove(Twine(Filename)); 226 return false; 227 } 228 229 objFile.keep(); 230 if (!genResult) { 231 sys::fs::remove(Twine(Filename)); 232 return false; 233 } 234 235 NativeObjectPath = Filename.c_str(); 236 *Name = NativeObjectPath.c_str(); 237 return true; 238 } 239 240 std::unique_ptr<MemoryBuffer> 241 LTOCodeGenerator::compileOptimized() { 242 const char *name; 243 if (!compileOptimizedToFile(&name)) 244 return nullptr; 245 246 // read .o file into memory buffer 247 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = 248 MemoryBuffer::getFile(name, -1, false); 249 if (std::error_code EC = BufferOrErr.getError()) { 250 emitError(EC.message()); 251 sys::fs::remove(NativeObjectPath); 252 return nullptr; 253 } 254 255 // remove temp files 256 sys::fs::remove(NativeObjectPath); 257 258 return std::move(*BufferOrErr); 259 } 260 261 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify, 262 bool DisableInline, 263 bool DisableGVNLoadPRE, 264 bool DisableVectorization) { 265 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE, 266 DisableVectorization)) 267 return false; 268 269 return compileOptimizedToFile(Name); 270 } 271 272 std::unique_ptr<MemoryBuffer> 273 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline, 274 bool DisableGVNLoadPRE, bool DisableVectorization) { 275 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE, 276 DisableVectorization)) 277 return nullptr; 278 279 return compileOptimized(); 280 } 281 282 bool LTOCodeGenerator::determineTarget() { 283 if (TargetMach) 284 return true; 285 286 std::string TripleStr = MergedModule->getTargetTriple(); 287 if (TripleStr.empty()) { 288 TripleStr = sys::getDefaultTargetTriple(); 289 MergedModule->setTargetTriple(TripleStr); 290 } 291 llvm::Triple Triple(TripleStr); 292 293 // create target machine from info for merged modules 294 std::string ErrMsg; 295 const Target *march = TargetRegistry::lookupTarget(TripleStr, ErrMsg); 296 if (!march) { 297 emitError(ErrMsg); 298 return false; 299 } 300 301 // Construct LTOModule, hand over ownership of module and target. Use MAttr as 302 // the default set of features. 303 SubtargetFeatures Features(MAttr); 304 Features.getDefaultSubtargetFeatures(Triple); 305 FeatureStr = Features.getString(); 306 // Set a default CPU for Darwin triples. 307 if (MCpu.empty() && Triple.isOSDarwin()) { 308 if (Triple.getArch() == llvm::Triple::x86_64) 309 MCpu = "core2"; 310 else if (Triple.getArch() == llvm::Triple::x86) 311 MCpu = "yonah"; 312 else if (Triple.getArch() == llvm::Triple::aarch64) 313 MCpu = "cyclone"; 314 } 315 316 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr, 317 Options, RelocModel, 318 CodeModel::Default, CGOptLevel)); 319 return true; 320 } 321 322 void LTOCodeGenerator:: 323 applyRestriction(GlobalValue &GV, 324 ArrayRef<StringRef> Libcalls, 325 std::vector<const char*> &MustPreserveList, 326 SmallPtrSetImpl<GlobalValue*> &AsmUsed, 327 Mangler &Mangler) { 328 // There are no restrictions to apply to declarations. 329 if (GV.isDeclaration()) 330 return; 331 332 // There is nothing more restrictive than private linkage. 333 if (GV.hasPrivateLinkage()) 334 return; 335 336 SmallString<64> Buffer; 337 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler); 338 339 if (MustPreserveSymbols.count(Buffer)) 340 MustPreserveList.push_back(GV.getName().data()); 341 if (AsmUndefinedRefs.count(Buffer)) 342 AsmUsed.insert(&GV); 343 344 // Conservatively append user-supplied runtime library functions to 345 // llvm.compiler.used. These could be internalized and deleted by 346 // optimizations like -globalopt, causing problems when later optimizations 347 // add new library calls (e.g., llvm.memset => memset and printf => puts). 348 // Leave it to the linker to remove any dead code (e.g. with -dead_strip). 349 if (isa<Function>(GV) && 350 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName())) 351 AsmUsed.insert(&GV); 352 } 353 354 static void findUsedValues(GlobalVariable *LLVMUsed, 355 SmallPtrSetImpl<GlobalValue*> &UsedValues) { 356 if (!LLVMUsed) return; 357 358 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer()); 359 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) 360 if (GlobalValue *GV = 361 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts())) 362 UsedValues.insert(GV); 363 } 364 365 // Collect names of runtime library functions. User-defined functions with the 366 // same names are added to llvm.compiler.used to prevent them from being 367 // deleted by optimizations. 368 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls, 369 const TargetLibraryInfo& TLI, 370 const Module &Mod, 371 const TargetMachine &TM) { 372 // TargetLibraryInfo has info on C runtime library calls on the current 373 // target. 374 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs); 375 I != E; ++I) { 376 LibFunc::Func F = static_cast<LibFunc::Func>(I); 377 if (TLI.has(F)) 378 Libcalls.push_back(TLI.getName(F)); 379 } 380 381 SmallPtrSet<const TargetLowering *, 1> TLSet; 382 383 for (const Function &F : Mod) { 384 const TargetLowering *Lowering = 385 TM.getSubtargetImpl(F)->getTargetLowering(); 386 387 if (Lowering && TLSet.insert(Lowering).second) 388 // TargetLowering has info on library calls that CodeGen expects to be 389 // available, both from the C runtime and compiler-rt. 390 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL); 391 I != E; ++I) 392 if (const char *Name = 393 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I))) 394 Libcalls.push_back(Name); 395 } 396 397 array_pod_sort(Libcalls.begin(), Libcalls.end()); 398 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()), 399 Libcalls.end()); 400 } 401 402 void LTOCodeGenerator::applyScopeRestrictions() { 403 if (ScopeRestrictionsDone || !ShouldInternalize) 404 return; 405 406 // Start off with a verification pass. 407 legacy::PassManager passes; 408 passes.add(createVerifierPass()); 409 410 // mark which symbols can not be internalized 411 Mangler Mangler; 412 std::vector<const char*> MustPreserveList; 413 SmallPtrSet<GlobalValue*, 8> AsmUsed; 414 std::vector<StringRef> Libcalls; 415 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple())); 416 TargetLibraryInfo TLI(TLII); 417 418 accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach); 419 420 for (Function &f : *MergedModule) 421 applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler); 422 for (GlobalVariable &v : MergedModule->globals()) 423 applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler); 424 for (GlobalAlias &a : MergedModule->aliases()) 425 applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler); 426 427 GlobalVariable *LLVMCompilerUsed = 428 MergedModule->getGlobalVariable("llvm.compiler.used"); 429 findUsedValues(LLVMCompilerUsed, AsmUsed); 430 if (LLVMCompilerUsed) 431 LLVMCompilerUsed->eraseFromParent(); 432 433 if (!AsmUsed.empty()) { 434 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context); 435 std::vector<Constant*> asmUsed2; 436 for (auto *GV : AsmUsed) { 437 Constant *c = ConstantExpr::getBitCast(GV, i8PTy); 438 asmUsed2.push_back(c); 439 } 440 441 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size()); 442 LLVMCompilerUsed = 443 new llvm::GlobalVariable(*MergedModule, ATy, false, 444 llvm::GlobalValue::AppendingLinkage, 445 llvm::ConstantArray::get(ATy, asmUsed2), 446 "llvm.compiler.used"); 447 448 LLVMCompilerUsed->setSection("llvm.metadata"); 449 } 450 451 passes.add(createInternalizePass(MustPreserveList)); 452 453 // apply scope restrictions 454 passes.run(*MergedModule); 455 456 ScopeRestrictionsDone = true; 457 } 458 459 /// Optimize merged modules using various IPO passes 460 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline, 461 bool DisableGVNLoadPRE, 462 bool DisableVectorization) { 463 if (!this->determineTarget()) 464 return false; 465 466 // Mark which symbols can not be internalized 467 this->applyScopeRestrictions(); 468 469 // Instantiate the pass manager to organize the passes. 470 legacy::PassManager passes; 471 472 // Add an appropriate DataLayout instance for this module... 473 MergedModule->setDataLayout(TargetMach->createDataLayout()); 474 475 passes.add( 476 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis())); 477 478 Triple TargetTriple(TargetMach->getTargetTriple()); 479 PassManagerBuilder PMB; 480 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE; 481 PMB.LoopVectorize = !DisableVectorization; 482 PMB.SLPVectorize = !DisableVectorization; 483 if (!DisableInline) 484 PMB.Inliner = createFunctionInliningPass(); 485 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple); 486 PMB.OptLevel = OptLevel; 487 PMB.VerifyInput = !DisableVerify; 488 PMB.VerifyOutput = !DisableVerify; 489 490 PMB.populateLTOPassManager(passes); 491 492 // Run our queue of passes all at once now, efficiently. 493 passes.run(*MergedModule); 494 495 return true; 496 } 497 498 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) { 499 if (!this->determineTarget()) 500 return false; 501 502 legacy::PassManager preCodeGenPasses; 503 504 // If the bitcode files contain ARC code and were compiled with optimization, 505 // the ObjCARCContractPass must be run, so do it unconditionally here. 506 preCodeGenPasses.add(createObjCARCContractPass()); 507 preCodeGenPasses.run(*MergedModule); 508 509 // Do code generation. We need to preserve the module in case the client calls 510 // writeMergedModules() after compilation, but we only need to allow this at 511 // parallelism level 1. This is achieved by having splitCodeGen return the 512 // original module at parallelism level 1 which we then assign back to 513 // MergedModule. 514 MergedModule = 515 splitCodeGen(std::move(MergedModule), Out, MCpu, FeatureStr, Options, 516 RelocModel, CodeModel::Default, CGOptLevel, FileType); 517 518 return true; 519 } 520 521 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging 522 /// LTO problems. 523 void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) { 524 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty(); 525 o = getToken(o.second)) 526 CodegenOptions.push_back(o.first); 527 } 528 529 void LTOCodeGenerator::parseCodeGenDebugOptions() { 530 // if options were requested, set them 531 if (!CodegenOptions.empty()) { 532 // ParseCommandLineOptions() expects argv[0] to be program name. 533 std::vector<const char *> CodegenArgv(1, "libLLVMLTO"); 534 for (std::string &Arg : CodegenOptions) 535 CodegenArgv.push_back(Arg.c_str()); 536 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data()); 537 } 538 } 539 540 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI, 541 void *Context) { 542 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI); 543 } 544 545 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) { 546 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity. 547 lto_codegen_diagnostic_severity_t Severity; 548 switch (DI.getSeverity()) { 549 case DS_Error: 550 Severity = LTO_DS_ERROR; 551 break; 552 case DS_Warning: 553 Severity = LTO_DS_WARNING; 554 break; 555 case DS_Remark: 556 Severity = LTO_DS_REMARK; 557 break; 558 case DS_Note: 559 Severity = LTO_DS_NOTE; 560 break; 561 } 562 // Create the string that will be reported to the external diagnostic handler. 563 std::string MsgStorage; 564 raw_string_ostream Stream(MsgStorage); 565 DiagnosticPrinterRawOStream DP(Stream); 566 DI.print(DP); 567 Stream.flush(); 568 569 // If this method has been called it means someone has set up an external 570 // diagnostic handler. Assert on that. 571 assert(DiagHandler && "Invalid diagnostic handler"); 572 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext); 573 } 574 575 void 576 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler, 577 void *Ctxt) { 578 this->DiagHandler = DiagHandler; 579 this->DiagContext = Ctxt; 580 if (!DiagHandler) 581 return Context.setDiagnosticHandler(nullptr, nullptr); 582 // Register the LTOCodeGenerator stub in the LLVMContext to forward the 583 // diagnostic to the external DiagHandler. 584 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this, 585 /* RespectFilters */ true); 586 } 587 588 namespace { 589 class LTODiagnosticInfo : public DiagnosticInfo { 590 const Twine &Msg; 591 public: 592 LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error) 593 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {} 594 void print(DiagnosticPrinter &DP) const override { DP << Msg; } 595 }; 596 } 597 598 void LTOCodeGenerator::emitError(const std::string &ErrMsg) { 599 if (DiagHandler) 600 (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext); 601 else 602 Context.diagnose(LTODiagnosticInfo(ErrMsg)); 603 } 604