llvm-dis.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. //===-- llvm-dis.cpp - The low-level LLVM disassembler --------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This utility may be invoked in the following manner:
  10. // llvm-dis [options] - Read LLVM bitcode from stdin, write asm to stdout
  11. // llvm-dis [options] x.bc - Read LLVM bitcode from the x.bc file, write asm
  12. // to the x.ll file.
  13. // Options:
  14. // --help - Output information about command line switches
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Bitcode/BitcodeReader.h"
  18. #include "llvm/IR/AssemblyAnnotationWriter.h"
  19. #include "llvm/IR/DebugInfo.h"
  20. #include "llvm/IR/DiagnosticInfo.h"
  21. #include "llvm/IR/DiagnosticPrinter.h"
  22. #include "llvm/IR/IntrinsicInst.h"
  23. #include "llvm/IR/LLVMContext.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/IR/Type.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/Error.h"
  28. #include "llvm/Support/FileSystem.h"
  29. #include "llvm/Support/FormattedStream.h"
  30. #include "llvm/Support/InitLLVM.h"
  31. #include "llvm/Support/MemoryBuffer.h"
  32. #include "llvm/Support/ToolOutputFile.h"
  33. #include "llvm/Support/WithColor.h"
  34. #include <system_error>
  35. using namespace llvm;
  36. static cl::opt<std::string>
  37. InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
  38. static cl::opt<std::string>
  39. OutputFilename("o", cl::desc("Override output filename"),
  40. cl::value_desc("filename"));
  41. static cl::opt<bool>
  42. Force("f", cl::desc("Enable binary output on terminals"));
  43. static cl::opt<bool>
  44. DontPrint("disable-output", cl::desc("Don't output the .ll file"), cl::Hidden);
  45. static cl::opt<bool>
  46. SetImporting("set-importing",
  47. cl::desc("Set lazy loading to pretend to import a module"),
  48. cl::Hidden);
  49. static cl::opt<bool>
  50. ShowAnnotations("show-annotations",
  51. cl::desc("Add informational comments to the .ll file"));
  52. static cl::opt<bool> PreserveAssemblyUseListOrder(
  53. "preserve-ll-uselistorder",
  54. cl::desc("Preserve use-list order when writing LLVM assembly."),
  55. cl::init(false), cl::Hidden);
  56. static cl::opt<bool>
  57. MaterializeMetadata("materialize-metadata",
  58. cl::desc("Load module without materializing metadata, "
  59. "then materialize only the metadata"));
  60. namespace {
  61. static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) {
  62. OS << DL.getLine() << ":" << DL.getCol();
  63. if (DILocation *IDL = DL.getInlinedAt()) {
  64. OS << "@";
  65. printDebugLoc(IDL, OS);
  66. }
  67. }
  68. class CommentWriter : public AssemblyAnnotationWriter {
  69. public:
  70. void emitFunctionAnnot(const Function *F,
  71. formatted_raw_ostream &OS) override {
  72. OS << "; [#uses=" << F->getNumUses() << ']'; // Output # uses
  73. OS << '\n';
  74. }
  75. void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
  76. bool Padded = false;
  77. if (!V.getType()->isVoidTy()) {
  78. OS.PadToColumn(50);
  79. Padded = true;
  80. // Output # uses and type
  81. OS << "; [#uses=" << V.getNumUses() << " type=" << *V.getType() << "]";
  82. }
  83. if (const Instruction *I = dyn_cast<Instruction>(&V)) {
  84. if (const DebugLoc &DL = I->getDebugLoc()) {
  85. if (!Padded) {
  86. OS.PadToColumn(50);
  87. Padded = true;
  88. OS << ";";
  89. }
  90. OS << " [debug line = ";
  91. printDebugLoc(DL,OS);
  92. OS << "]";
  93. }
  94. if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
  95. if (!Padded) {
  96. OS.PadToColumn(50);
  97. OS << ";";
  98. }
  99. OS << " [debug variable = " << DDI->getVariable()->getName() << "]";
  100. }
  101. else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
  102. if (!Padded) {
  103. OS.PadToColumn(50);
  104. OS << ";";
  105. }
  106. OS << " [debug variable = " << DVI->getVariable()->getName() << "]";
  107. }
  108. }
  109. }
  110. };
  111. struct LLVMDisDiagnosticHandler : public DiagnosticHandler {
  112. char *Prefix;
  113. LLVMDisDiagnosticHandler(char *PrefixPtr) : Prefix(PrefixPtr) {}
  114. bool handleDiagnostics(const DiagnosticInfo &DI) override {
  115. raw_ostream &OS = errs();
  116. OS << Prefix << ": ";
  117. switch (DI.getSeverity()) {
  118. case DS_Error: WithColor::error(OS); break;
  119. case DS_Warning: WithColor::warning(OS); break;
  120. case DS_Remark: OS << "remark: "; break;
  121. case DS_Note: WithColor::note(OS); break;
  122. }
  123. DiagnosticPrinterRawOStream DP(OS);
  124. DI.print(DP);
  125. OS << '\n';
  126. if (DI.getSeverity() == DS_Error)
  127. exit(1);
  128. return true;
  129. }
  130. };
  131. } // end anon namespace
  132. static ExitOnError ExitOnErr;
  133. int main(int argc, char **argv) {
  134. InitLLVM X(argc, argv);
  135. ExitOnErr.setBanner(std::string(argv[0]) + ": error: ");
  136. LLVMContext Context;
  137. Context.setDiagnosticHandler(
  138. std::make_unique<LLVMDisDiagnosticHandler>(argv[0]));
  139. cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n");
  140. std::unique_ptr<MemoryBuffer> MB =
  141. ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename)));
  142. BitcodeFileContents IF = ExitOnErr(llvm::getBitcodeFileContents(*MB));
  143. const size_t N = IF.Mods.size();
  144. if (OutputFilename == "-" && N > 1)
  145. errs() << "only single module bitcode files can be written to stdout\n";
  146. for (size_t i = 0; i < N; ++i) {
  147. BitcodeModule MB = IF.Mods[i];
  148. std::unique_ptr<Module> M = ExitOnErr(MB.getLazyModule(Context, MaterializeMetadata,
  149. SetImporting));
  150. if (MaterializeMetadata)
  151. ExitOnErr(M->materializeMetadata());
  152. else
  153. ExitOnErr(M->materializeAll());
  154. BitcodeLTOInfo LTOInfo = ExitOnErr(MB.getLTOInfo());
  155. std::unique_ptr<ModuleSummaryIndex> Index;
  156. if (LTOInfo.HasSummary)
  157. Index = ExitOnErr(MB.getSummary());
  158. std::string FinalFilename(OutputFilename);
  159. // Just use stdout. We won't actually print anything on it.
  160. if (DontPrint)
  161. FinalFilename = "-";
  162. if (FinalFilename.empty()) { // Unspecified output, infer it.
  163. if (InputFilename == "-") {
  164. FinalFilename = "-";
  165. } else {
  166. StringRef IFN = InputFilename;
  167. FinalFilename = (IFN.endswith(".bc") ? IFN.drop_back(3) : IFN).str();
  168. if (N > 1)
  169. FinalFilename += std::string(".") + std::to_string(i);
  170. FinalFilename += ".ll";
  171. }
  172. } else {
  173. if (N > 1)
  174. FinalFilename += std::string(".") + std::to_string(i);
  175. }
  176. std::error_code EC;
  177. std::unique_ptr<ToolOutputFile> Out(
  178. new ToolOutputFile(FinalFilename, EC, sys::fs::OF_Text));
  179. if (EC) {
  180. errs() << EC.message() << '\n';
  181. return 1;
  182. }
  183. std::unique_ptr<AssemblyAnnotationWriter> Annotator;
  184. if (ShowAnnotations)
  185. Annotator.reset(new CommentWriter());
  186. // All that llvm-dis does is write the assembly to a file.
  187. if (!DontPrint) {
  188. M->print(Out->os(), Annotator.get(), PreserveAssemblyUseListOrder);
  189. if (Index)
  190. Index->print(Out->os());
  191. }
  192. // Declare success.
  193. Out->keep();
  194. }
  195. return 0;
  196. }