LTOCodeGenerator.cpp 19 KB

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