66e126092db226c01bd347404159d3a09239f224
[oota-llvm.git] / tools / llvm-mc / llvm-mc.cpp
1 //===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
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 is a simple driver that allows command line hacking on machine
11 // code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/MC/MCParser/MCAsmLexer.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCInstPrinter.h"
19 #include "llvm/MC/MCSectionMachO.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/FormattedStream.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/PrettyStackTrace.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/System/Host.h"
30 #include "llvm/System/Signals.h"
31 #include "llvm/Target/TargetAsmBackend.h"
32 #include "llvm/Target/TargetAsmParser.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetRegistry.h"
35 #include "llvm/Target/TargetMachine.h"  // FIXME.
36 #include "llvm/Target/TargetSelect.h"
37 #include "llvm/MC/MCParser/AsmParser.h"
38 #include "Disassembler.h"
39 using namespace llvm;
40
41 static cl::opt<std::string>
42 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
43
44 static cl::opt<std::string>
45 OutputFilename("o", cl::desc("Output filename"),
46                cl::value_desc("filename"));
47
48 static cl::opt<bool>
49 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
50
51 static cl::opt<bool>
52 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
53
54 static cl::opt<unsigned>
55 OutputAsmVariant("output-asm-variant",
56                  cl::desc("Syntax variant to use for output printing"));
57
58 enum OutputFileType {
59   OFT_AssemblyFile,
60   OFT_ObjectFile
61 };
62 static cl::opt<OutputFileType>
63 FileType("filetype", cl::init(OFT_AssemblyFile),
64   cl::desc("Choose an output file type:"),
65   cl::values(
66        clEnumValN(OFT_AssemblyFile, "asm",
67                   "Emit an assembly ('.s') file"),
68        clEnumValN(OFT_ObjectFile, "obj",
69                   "Emit a native object ('.o') file"),
70        clEnumValEnd));
71
72 static cl::opt<bool>
73 Force("f", cl::desc("Enable binary output on terminals"));
74
75 static cl::list<std::string>
76 IncludeDirs("I", cl::desc("Directory of include files"),
77             cl::value_desc("directory"), cl::Prefix);
78
79 static cl::opt<std::string>
80 ArchName("arch", cl::desc("Target arch to assemble for, "
81                             "see -version for available targets"));
82
83 static cl::opt<std::string>
84 TripleName("triple", cl::desc("Target triple to assemble for, "
85                               "see -version for available targets"));
86
87 static cl::opt<bool>
88 NoInitialTextSection("n", cl::desc(
89                    "Don't assume assembly file starts in the text section"));
90
91 enum ActionType {
92   AC_AsLex,
93   AC_Assemble,
94   AC_Disassemble
95 };
96
97 static cl::opt<ActionType>
98 Action(cl::desc("Action to perform:"),
99        cl::init(AC_Assemble),
100        cl::values(clEnumValN(AC_AsLex, "as-lex",
101                              "Lex tokens from a .s file"),
102                   clEnumValN(AC_Assemble, "assemble",
103                              "Assemble a .s file (default)"),
104                   clEnumValN(AC_Disassemble, "disassemble",
105                              "Disassemble strings of hex bytes"),
106                   clEnumValEnd));
107
108 static const Target *GetTarget(const char *ProgName) {
109   // Figure out the target triple.
110   if (TripleName.empty())
111     TripleName = sys::getHostTriple();
112   if (!ArchName.empty()) {
113     llvm::Triple TT(TripleName);
114     TT.setArchName(ArchName);
115     TripleName = TT.str();
116   }
117
118   // Get the target specific parser.
119   std::string Error;
120   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
121   if (TheTarget)
122     return TheTarget;
123
124   errs() << ProgName << ": error: unable to get target for '" << TripleName
125          << "', see --version and --triple.\n";
126   return 0;
127 }
128
129 static int AsLexInput(const char *ProgName) {
130   std::string ErrorMessage;
131   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
132                                                       &ErrorMessage);
133   if (Buffer == 0) {
134     errs() << ProgName << ": ";
135     if (ErrorMessage.size())
136       errs() << ErrorMessage << "\n";
137     else
138       errs() << "input file didn't read correctly.\n";
139     return 1;
140   }
141
142   SourceMgr SrcMgr;
143   
144   // Tell SrcMgr about this buffer, which is what TGParser will pick up.
145   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
146   
147   // Record the location of the include directories so that the lexer can find
148   // it later.
149   SrcMgr.setIncludeDirs(IncludeDirs);
150
151   const Target *TheTarget = GetTarget(ProgName);
152   if (!TheTarget)
153     return 1;
154
155   const MCAsmInfo *MAI = TheTarget->createAsmInfo(TripleName);
156   assert(MAI && "Unable to create target asm info!");
157
158   AsmLexer Lexer(*MAI);
159   
160   bool Error = false;
161   
162   while (Lexer.Lex().isNot(AsmToken::Eof)) {
163     switch (Lexer.getKind()) {
164     default:
165       SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
166       Error = true;
167       break;
168     case AsmToken::Error:
169       Error = true; // error already printed.
170       break;
171     case AsmToken::Identifier:
172       outs() << "identifier: " << Lexer.getTok().getString() << '\n';
173       break;
174     case AsmToken::String:
175       outs() << "string: " << Lexer.getTok().getString() << '\n';
176       break;
177     case AsmToken::Integer:
178       outs() << "int: " << Lexer.getTok().getString() << '\n';
179       break;
180
181     case AsmToken::Amp:            outs() << "Amp\n"; break;
182     case AsmToken::AmpAmp:         outs() << "AmpAmp\n"; break;
183     case AsmToken::Caret:          outs() << "Caret\n"; break;
184     case AsmToken::Colon:          outs() << "Colon\n"; break;
185     case AsmToken::Comma:          outs() << "Comma\n"; break;
186     case AsmToken::Dollar:         outs() << "Dollar\n"; break;
187     case AsmToken::EndOfStatement: outs() << "EndOfStatement\n"; break;
188     case AsmToken::Eof:            outs() << "Eof\n"; break;
189     case AsmToken::Equal:          outs() << "Equal\n"; break;
190     case AsmToken::EqualEqual:     outs() << "EqualEqual\n"; break;
191     case AsmToken::Exclaim:        outs() << "Exclaim\n"; break;
192     case AsmToken::ExclaimEqual:   outs() << "ExclaimEqual\n"; break;
193     case AsmToken::Greater:        outs() << "Greater\n"; break;
194     case AsmToken::GreaterEqual:   outs() << "GreaterEqual\n"; break;
195     case AsmToken::GreaterGreater: outs() << "GreaterGreater\n"; break;
196     case AsmToken::LParen:         outs() << "LParen\n"; break;
197     case AsmToken::Less:           outs() << "Less\n"; break;
198     case AsmToken::LessEqual:      outs() << "LessEqual\n"; break;
199     case AsmToken::LessGreater:    outs() << "LessGreater\n"; break;
200     case AsmToken::LessLess:       outs() << "LessLess\n"; break;
201     case AsmToken::Minus:          outs() << "Minus\n"; break;
202     case AsmToken::Percent:        outs() << "Percent\n"; break;
203     case AsmToken::Pipe:           outs() << "Pipe\n"; break;
204     case AsmToken::PipePipe:       outs() << "PipePipe\n"; break;
205     case AsmToken::Plus:           outs() << "Plus\n"; break;
206     case AsmToken::RParen:         outs() << "RParen\n"; break;
207     case AsmToken::Slash:          outs() << "Slash\n"; break;
208     case AsmToken::Star:           outs() << "Star\n"; break;
209     case AsmToken::Tilde:          outs() << "Tilde\n"; break;
210     }
211   }
212   
213   return Error;
214 }
215
216 static formatted_raw_ostream *GetOutputStream() {
217   if (OutputFilename == "")
218     OutputFilename = "-";
219
220   // Make sure that the Out file gets unlinked from the disk if we get a
221   // SIGINT.
222   if (OutputFilename != "-")
223     sys::RemoveFileOnSignal(sys::Path(OutputFilename));
224
225   std::string Err;
226   raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Err,
227                                            raw_fd_ostream::F_Binary);
228   if (!Err.empty()) {
229     errs() << Err << '\n';
230     delete Out;
231     return 0;
232   }
233   
234   return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
235 }
236
237 static int AssembleInput(const char *ProgName) {
238   const Target *TheTarget = GetTarget(ProgName);
239   if (!TheTarget)
240     return 1;
241
242   std::string Error;
243   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
244   if (Buffer == 0) {
245     errs() << ProgName << ": ";
246     if (Error.size())
247       errs() << Error << "\n";
248     else
249       errs() << "input file didn't read correctly.\n";
250     return 1;
251   }
252   
253   SourceMgr SrcMgr;
254   
255   // Tell SrcMgr about this buffer, which is what the parser will pick up.
256   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
257   
258   // Record the location of the include directories so that the lexer can find
259   // it later.
260   SrcMgr.setIncludeDirs(IncludeDirs);
261   
262   
263   const MCAsmInfo *MAI = TheTarget->createAsmInfo(TripleName);
264   assert(MAI && "Unable to create target asm info!");
265   
266   MCContext Ctx(*MAI);
267   formatted_raw_ostream *Out = GetOutputStream();
268   if (!Out)
269     return 1;
270
271
272   // FIXME: We shouldn't need to do this (and link in codegen).
273   OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
274
275   if (!TM) {
276     errs() << ProgName << ": error: could not create target for triple '"
277            << TripleName << "'.\n";
278     return 1;
279   }
280
281   OwningPtr<MCInstPrinter> IP;
282   OwningPtr<MCCodeEmitter> CE;
283   OwningPtr<MCStreamer> Str;
284   OwningPtr<TargetAsmBackend> TAB;
285
286   if (FileType == OFT_AssemblyFile) {
287     IP.reset(TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *Out));
288     if (ShowEncoding)
289       CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
290     Str.reset(createAsmStreamer(Ctx, *Out,TM->getTargetData()->isLittleEndian(),
291                                 /*asmverbose*/true, IP.get(), CE.get(),
292                                 ShowInst));
293   } else {
294     assert(FileType == OFT_ObjectFile && "Invalid file type!");
295     CE.reset(TheTarget->createCodeEmitter(*TM, Ctx));
296     TAB.reset(TheTarget->createAsmBackend(TripleName));
297     Str.reset(createMachOStreamer(Ctx, *TAB, *Out, CE.get()));
298   }
299
300   AsmParser Parser(SrcMgr, Ctx, *Str.get(), *MAI);
301   OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
302   if (!TAP) {
303     errs() << ProgName 
304            << ": error: this target does not support assembly parsing.\n";
305     return 1;
306   }
307
308   Parser.setTargetParser(*TAP.get());
309
310   int Res = Parser.Run(NoInitialTextSection);
311   if (Out != &fouts())
312     delete Out;
313
314   // Delete output on errors.
315   if (Res && OutputFilename != "-")
316     sys::Path(OutputFilename).eraseFromDisk();
317
318   return Res;
319 }
320
321 static int DisassembleInput(const char *ProgName) {
322   std::string Error;
323   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
324   if (TheTarget == 0) {
325     errs() << ProgName << ": error: unable to get target for '" << TripleName
326     << "', see --version and --triple.\n";
327     return 0;
328   }
329   
330   std::string ErrorMessage;
331   
332   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
333                                                       &ErrorMessage);
334
335   if (Buffer == 0) {
336     errs() << ProgName << ": ";
337     if (ErrorMessage.size())
338       errs() << ErrorMessage << "\n";
339     else
340       errs() << "input file didn't read correctly.\n";
341     return 1;
342   }
343   
344   return Disassembler::disassemble(*TheTarget, TripleName, *Buffer);
345 }
346
347
348 int main(int argc, char **argv) {
349   // Print a stack trace if we signal out.
350   sys::PrintStackTraceOnErrorSignal();
351   PrettyStackTraceProgram X(argc, argv);
352   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
353
354   // Initialize targets and assembly printers/parsers.
355   llvm::InitializeAllTargetInfos();
356   // FIXME: We shouldn't need to initialize the Target(Machine)s.
357   llvm::InitializeAllTargets();
358   llvm::InitializeAllAsmPrinters();
359   llvm::InitializeAllAsmParsers();
360   llvm::InitializeAllDisassemblers();
361   
362   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
363
364   switch (Action) {
365   default:
366   case AC_AsLex:
367     return AsLexInput(argv[0]);
368   case AC_Assemble:
369     return AssembleInput(argv[0]);
370   case AC_Disassemble:
371     return DisassembleInput(argv[0]);
372   }
373   
374   return 0;
375 }
376