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
18 #include "llvm/Bitcode/BitcodeReader.h"
19 #include "llvm/IR/AssemblyAnnotationWriter.h"
20 #include "llvm/IR/DebugInfo.h"
21 #include "llvm/IR/DiagnosticInfo.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/ModuleSummaryIndex.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/InitLLVM.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/ToolOutputFile.h"
35 #include "llvm/Support/WithColor.h"
36 #include <system_error>
37 using namespace llvm;
38
39 static cl::OptionCategory DisCategory("Disassembler Options");
40
41 static cl::list<std::string> InputFilenames(cl::Positional,
42 cl::desc("[input bitcode]..."),
43 cl::cat(DisCategory));
44
45 static cl::opt<std::string> OutputFilename("o",
46 cl::desc("Override output filename"),
47 cl::value_desc("filename"),
48 cl::cat(DisCategory));
49
50 static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals"),
51 cl::cat(DisCategory));
52
53 static cl::opt<bool> DontPrint("disable-output",
54 cl::desc("Don't output the .ll file"),
55 cl::Hidden, cl::cat(DisCategory));
56
57 static cl::opt<bool>
58 SetImporting("set-importing",
59 cl::desc("Set lazy loading to pretend to import a module"),
60 cl::Hidden, cl::cat(DisCategory));
61
62 static cl::opt<bool>
63 ShowAnnotations("show-annotations",
64 cl::desc("Add informational comments to the .ll file"),
65 cl::cat(DisCategory));
66
67 static cl::opt<bool> PreserveAssemblyUseListOrder(
68 "preserve-ll-uselistorder",
69 cl::desc("Preserve use-list order when writing LLVM assembly."),
70 cl::init(false), cl::Hidden, cl::cat(DisCategory));
71
72 static cl::opt<bool>
73 MaterializeMetadata("materialize-metadata",
74 cl::desc("Load module without materializing metadata, "
75 "then materialize only the metadata"),
76 cl::cat(DisCategory));
77
78 static cl::opt<bool> PrintThinLTOIndexOnly(
79 "print-thinlto-index-only",
80 cl::desc("Only read thinlto index and print the index as LLVM assembly."),
81 cl::init(false), cl::Hidden, cl::cat(DisCategory));
82
83 namespace {
84
printDebugLoc(const DebugLoc & DL,formatted_raw_ostream & OS)85 static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) {
86 OS << DL.getLine() << ":" << DL.getCol();
87 if (DILocation *IDL = DL.getInlinedAt()) {
88 OS << "@";
89 printDebugLoc(IDL, OS);
90 }
91 }
92 class CommentWriter : public AssemblyAnnotationWriter {
93 public:
emitFunctionAnnot(const Function * F,formatted_raw_ostream & OS)94 void emitFunctionAnnot(const Function *F,
95 formatted_raw_ostream &OS) override {
96 OS << "; [#uses=" << F->getNumUses() << ']'; // Output # uses
97 OS << '\n';
98 }
printInfoComment(const Value & V,formatted_raw_ostream & OS)99 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
100 bool Padded = false;
101 if (!V.getType()->isVoidTy()) {
102 OS.PadToColumn(50);
103 Padded = true;
104 // Output # uses and type
105 OS << "; [#uses=" << V.getNumUses() << " type=" << *V.getType() << "]";
106 }
107 if (const Instruction *I = dyn_cast<Instruction>(&V)) {
108 if (const DebugLoc &DL = I->getDebugLoc()) {
109 if (!Padded) {
110 OS.PadToColumn(50);
111 Padded = true;
112 OS << ";";
113 }
114 OS << " [debug line = ";
115 printDebugLoc(DL,OS);
116 OS << "]";
117 }
118 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
119 if (!Padded) {
120 OS.PadToColumn(50);
121 OS << ";";
122 }
123 OS << " [debug variable = " << DDI->getVariable()->getName() << "]";
124 }
125 else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
126 if (!Padded) {
127 OS.PadToColumn(50);
128 OS << ";";
129 }
130 OS << " [debug variable = " << DVI->getVariable()->getName() << "]";
131 }
132 }
133 }
134 };
135
136 struct LLVMDisDiagnosticHandler : public DiagnosticHandler {
137 char *Prefix;
LLVMDisDiagnosticHandler__anon32ae7c800111::LLVMDisDiagnosticHandler138 LLVMDisDiagnosticHandler(char *PrefixPtr) : Prefix(PrefixPtr) {}
handleDiagnostics__anon32ae7c800111::LLVMDisDiagnosticHandler139 bool handleDiagnostics(const DiagnosticInfo &DI) override {
140 raw_ostream &OS = errs();
141 OS << Prefix << ": ";
142 switch (DI.getSeverity()) {
143 case DS_Error: WithColor::error(OS); break;
144 case DS_Warning: WithColor::warning(OS); break;
145 case DS_Remark: OS << "remark: "; break;
146 case DS_Note: WithColor::note(OS); break;
147 }
148
149 DiagnosticPrinterRawOStream DP(OS);
150 DI.print(DP);
151 OS << '\n';
152
153 if (DI.getSeverity() == DS_Error)
154 exit(1);
155 return true;
156 }
157 };
158 } // end anon namespace
159
160 static ExitOnError ExitOnErr;
161
main(int argc,char ** argv)162 int main(int argc, char **argv) {
163 InitLLVM X(argc, argv);
164
165 ExitOnErr.setBanner(std::string(argv[0]) + ": error: ");
166
167 cl::HideUnrelatedOptions({&DisCategory, &getColorCategory()});
168 cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n");
169
170 LLVMContext Context;
171 Context.setDiagnosticHandler(
172 std::make_unique<LLVMDisDiagnosticHandler>(argv[0]));
173
174 if (InputFilenames.size() < 1) {
175 InputFilenames.push_back("-");
176 } else if (InputFilenames.size() > 1 && !OutputFilename.empty()) {
177 errs()
178 << "error: output file name cannot be set for multiple input files\n";
179 return 1;
180 }
181
182 for (std::string InputFilename : InputFilenames) {
183 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
184 MemoryBuffer::getFileOrSTDIN(InputFilename);
185 if (std::error_code EC = BufferOrErr.getError()) {
186 WithColor::error() << InputFilename << ": " << EC.message() << '\n';
187 return 1;
188 }
189 std::unique_ptr<MemoryBuffer> MB = std::move(BufferOrErr.get());
190
191 BitcodeFileContents IF = ExitOnErr(llvm::getBitcodeFileContents(*MB));
192
193 const size_t N = IF.Mods.size();
194
195 if (OutputFilename == "-" && N > 1)
196 errs() << "only single module bitcode files can be written to stdout\n";
197
198 for (size_t I = 0; I < N; ++I) {
199 BitcodeModule MB = IF.Mods[I];
200
201 std::unique_ptr<Module> M;
202
203 if (!PrintThinLTOIndexOnly) {
204 M = ExitOnErr(
205 MB.getLazyModule(Context, MaterializeMetadata, SetImporting));
206 if (MaterializeMetadata)
207 ExitOnErr(M->materializeMetadata());
208 else
209 ExitOnErr(M->materializeAll());
210 }
211
212 BitcodeLTOInfo LTOInfo = ExitOnErr(MB.getLTOInfo());
213 std::unique_ptr<ModuleSummaryIndex> Index;
214 if (LTOInfo.HasSummary)
215 Index = ExitOnErr(MB.getSummary());
216
217 std::string FinalFilename(OutputFilename);
218
219 // Just use stdout. We won't actually print anything on it.
220 if (DontPrint)
221 FinalFilename = "-";
222
223 if (FinalFilename.empty()) { // Unspecified output, infer it.
224 if (InputFilename == "-") {
225 FinalFilename = "-";
226 } else {
227 StringRef IFN = InputFilename;
228 FinalFilename = (IFN.endswith(".bc") ? IFN.drop_back(3) : IFN).str();
229 if (N > 1)
230 FinalFilename += std::string(".") + std::to_string(I);
231 FinalFilename += ".ll";
232 }
233 } else {
234 if (N > 1)
235 FinalFilename += std::string(".") + std::to_string(I);
236 }
237
238 std::error_code EC;
239 std::unique_ptr<ToolOutputFile> Out(
240 new ToolOutputFile(FinalFilename, EC, sys::fs::OF_TextWithCRLF));
241 if (EC) {
242 errs() << EC.message() << '\n';
243 return 1;
244 }
245
246 std::unique_ptr<AssemblyAnnotationWriter> Annotator;
247 if (ShowAnnotations)
248 Annotator.reset(new CommentWriter());
249
250 // All that llvm-dis does is write the assembly to a file.
251 if (!DontPrint) {
252 if (M)
253 M->print(Out->os(), Annotator.get(), PreserveAssemblyUseListOrder);
254 if (Index)
255 Index->print(Out->os());
256 }
257
258 // Declare success.
259 Out->keep();
260 }
261 }
262
263 return 0;
264 }
265