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