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