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