uselistorder: Pull the assembly bit up out of the printer
[oota-llvm.git] / tools / llvm-dis / llvm-dis.cpp
1 //===-- llvm-dis.cpp - The low-level LLVM disassembler --------------------===//
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 utility may be invoked in the following manner:
11 //  llvm-dis [options]      - Read LLVM bitcode from stdin, write asm to stdout
12 //  llvm-dis [options] x.bc - Read LLVM bitcode from the x.bc file, write asm
13 //                            to the x.ll file.
14 //  Options:
15 //      --help   - Output information about command line switches
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/IR/AssemblyAnnotationWriter.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/IR/DiagnosticInfo.h"
24 #include "llvm/IR/DiagnosticPrinter.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/IR/UseListOrder.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DataStream.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/ToolOutputFile.h"
38 #include <system_error>
39 using namespace llvm;
40
41 static cl::opt<std::string>
42 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
43
44 static cl::opt<std::string>
45 OutputFilename("o", cl::desc("Override output filename"),
46                cl::value_desc("filename"));
47
48 static cl::opt<bool>
49 Force("f", cl::desc("Enable binary output on terminals"));
50
51 static cl::opt<bool>
52 DontPrint("disable-output", cl::desc("Don't output the .ll file"), cl::Hidden);
53
54 static cl::opt<bool>
55 ShowAnnotations("show-annotations",
56                 cl::desc("Add informational comments to the .ll file"));
57
58 namespace {
59
60 static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) {
61   OS << DL.getLine() << ":" << DL.getCol();
62   if (MDLocation *IDL = DL.getInlinedAt()) {
63     OS << "@";
64     printDebugLoc(IDL, OS);
65   }
66 }
67 class CommentWriter : public AssemblyAnnotationWriter {
68 public:
69   void emitFunctionAnnot(const Function *F,
70                          formatted_raw_ostream &OS) override {
71     OS << "; [#uses=" << F->getNumUses() << ']';  // Output # uses
72     OS << '\n';
73   }
74   void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
75     bool Padded = false;
76     if (!V.getType()->isVoidTy()) {
77       OS.PadToColumn(50);
78       Padded = true;
79       OS << "; [#uses=" << V.getNumUses() << " type=" << *V.getType() << "]";  // Output # uses and type
80     }
81     if (const Instruction *I = dyn_cast<Instruction>(&V)) {
82       if (const DebugLoc &DL = I->getDebugLoc()) {
83         if (!Padded) {
84           OS.PadToColumn(50);
85           Padded = true;
86           OS << ";";
87         }
88         OS << " [debug line = ";
89         printDebugLoc(DL,OS);
90         OS << "]";
91       }
92       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
93         DIVariable Var(DDI->getVariable());
94         if (!Padded) {
95           OS.PadToColumn(50);
96           OS << ";";
97         }
98         OS << " [debug variable = " << Var->getName() << "]";
99       }
100       else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
101         DIVariable Var(DVI->getVariable());
102         if (!Padded) {
103           OS.PadToColumn(50);
104           OS << ";";
105         }
106         OS << " [debug variable = " << Var->getName() << "]";
107       }
108     }
109   }
110 };
111
112 } // end anon namespace
113
114 static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
115   raw_ostream &OS = errs();
116   OS << (char *)Context << ": ";
117   switch (DI.getSeverity()) {
118   case DS_Error: OS << "error: "; break;
119   case DS_Warning: OS << "warning: "; break;
120   case DS_Remark: OS << "remark: "; break;
121   case DS_Note: OS << "note: "; break;
122   }
123
124   DiagnosticPrinterRawOStream DP(OS);
125   DI.print(DP);
126   OS << '\n';
127
128   if (DI.getSeverity() == DS_Error)
129     exit(1);
130 }
131
132 int main(int argc, char **argv) {
133   // Print a stack trace if we signal out.
134   sys::PrintStackTraceOnErrorSignal();
135   PrettyStackTraceProgram X(argc, argv);
136
137   LLVMContext &Context = getGlobalContext();
138   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
139
140   Context.setDiagnosticHandler(diagnosticHandler, argv[0]);
141
142   cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n");
143
144   std::string ErrorMessage;
145   std::unique_ptr<Module> M;
146
147   // Use the bitcode streaming interface
148   DataStreamer *Streamer = getDataFileStreamer(InputFilename, &ErrorMessage);
149   if (Streamer) {
150     std::string DisplayFilename;
151     if (InputFilename == "-")
152       DisplayFilename = "<stdin>";
153     else
154       DisplayFilename = InputFilename;
155     ErrorOr<std::unique_ptr<Module>> MOrErr =
156         getStreamedBitcodeModule(DisplayFilename, Streamer, Context);
157     M = std::move(*MOrErr);
158     M->materializeAllPermanently();
159   }
160
161   // Just use stdout.  We won't actually print anything on it.
162   if (DontPrint)
163     OutputFilename = "-";
164
165   if (OutputFilename.empty()) { // Unspecified output, infer it.
166     if (InputFilename == "-") {
167       OutputFilename = "-";
168     } else {
169       const std::string &IFN = InputFilename;
170       int Len = IFN.length();
171       // If the source ends in .bc, strip it off.
172       if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c')
173         OutputFilename = std::string(IFN.begin(), IFN.end()-3)+".ll";
174       else
175         OutputFilename = IFN+".ll";
176     }
177   }
178
179   std::error_code EC;
180   std::unique_ptr<tool_output_file> Out(
181       new tool_output_file(OutputFilename, EC, sys::fs::F_None));
182   if (EC) {
183     errs() << EC.message() << '\n';
184     return 1;
185   }
186
187   std::unique_ptr<AssemblyAnnotationWriter> Annotator;
188   if (ShowAnnotations)
189     Annotator.reset(new CommentWriter());
190
191   // All that llvm-dis does is write the assembly to a file.
192   if (!DontPrint)
193     M->print(Out->os(), Annotator.get(), shouldPreserveAssemblyUseListOrder());
194
195   // Declare success.
196   Out->keep();
197
198   return 0;
199 }