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