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