Add support for annotated disassembly output for X86 and arm.
[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/MCAsmBackend.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCCodeEmitter.h"
21 #include "llvm/MC/MCInstPrinter.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/MC/MCObjectFileInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCTargetAsmParser.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/FileUtilities.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/ToolOutputFile.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.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 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
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::list<std::string>
110 MAttrs("mattr",
111   cl::CommaSeparated,
112   cl::desc("Target specific attributes (-mattr=help for details)"),
113   cl::value_desc("a1,+a2,-a3,..."));
114
115 static cl::opt<Reloc::Model>
116 RelocModel("relocation-model",
117              cl::desc("Choose relocation model"),
118              cl::init(Reloc::Default),
119              cl::values(
120             clEnumValN(Reloc::Default, "default",
121                        "Target default relocation model"),
122             clEnumValN(Reloc::Static, "static",
123                        "Non-relocatable code"),
124             clEnumValN(Reloc::PIC_, "pic",
125                        "Fully relocatable, position independent code"),
126             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
127                        "Relocatable external references, non-relocatable code"),
128             clEnumValEnd));
129
130 static cl::opt<llvm::CodeModel::Model>
131 CMModel("code-model",
132         cl::desc("Choose code model"),
133         cl::init(CodeModel::Default),
134         cl::values(clEnumValN(CodeModel::Default, "default",
135                               "Target default code model"),
136                    clEnumValN(CodeModel::Small, "small",
137                               "Small code model"),
138                    clEnumValN(CodeModel::Kernel, "kernel",
139                               "Kernel code model"),
140                    clEnumValN(CodeModel::Medium, "medium",
141                               "Medium code model"),
142                    clEnumValN(CodeModel::Large, "large",
143                               "Large code model"),
144                    clEnumValEnd));
145
146 static cl::opt<bool>
147 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
148                                    "in the text section"));
149
150 static cl::opt<bool>
151 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
152
153 static cl::opt<bool>
154 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
155                                   "source files"));
156
157 enum ActionType {
158   AC_AsLex,
159   AC_Assemble,
160   AC_Disassemble,
161   AC_EDisassemble,
162   AC_MDisassemble
163 };
164
165 static cl::opt<ActionType>
166 Action(cl::desc("Action to perform:"),
167        cl::init(AC_Assemble),
168        cl::values(clEnumValN(AC_AsLex, "as-lex",
169                              "Lex tokens from a .s file"),
170                   clEnumValN(AC_Assemble, "assemble",
171                              "Assemble a .s file (default)"),
172                   clEnumValN(AC_Disassemble, "disassemble",
173                              "Disassemble strings of hex bytes"),
174                   clEnumValN(AC_EDisassemble, "edis",
175                              "Enhanced disassembly of strings of hex bytes"),
176                   clEnumValN(AC_MDisassemble, "mdis",
177                              "Marked up disassembly of strings of hex bytes"),
178                   clEnumValEnd));
179
180 static const Target *GetTarget(const char *ProgName) {
181   // Figure out the target triple.
182   if (TripleName.empty())
183     TripleName = sys::getDefaultTargetTriple();
184   Triple TheTriple(Triple::normalize(TripleName));
185
186   // Get the target specific parser.
187   std::string Error;
188   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
189                                                          Error);
190   if (!TheTarget) {
191     errs() << ProgName << ": " << Error;
192     return 0;
193   }
194
195   // Update the triple name and return the found target.
196   TripleName = TheTriple.getTriple();
197   return TheTarget;
198 }
199
200 static tool_output_file *GetOutputStream() {
201   if (OutputFilename == "")
202     OutputFilename = "-";
203
204   std::string Err;
205   tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
206                                                raw_fd_ostream::F_Binary);
207   if (!Err.empty()) {
208     errs() << Err << '\n';
209     delete Out;
210     return 0;
211   }
212
213   return Out;
214 }
215
216 static std::string DwarfDebugFlags;
217 static void setDwarfDebugFlags(int argc, char **argv) {
218   if (!getenv("RC_DEBUG_OPTIONS"))
219     return;
220   for (int i = 0; i < argc; i++) {
221     DwarfDebugFlags += argv[i];
222     if (i + 1 < argc)
223       DwarfDebugFlags += " ";
224   }
225 }
226
227 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, tool_output_file *Out) {
228
229   AsmLexer Lexer(MAI);
230   Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
231
232   bool Error = false;
233   while (Lexer.Lex().isNot(AsmToken::Eof)) {
234     AsmToken Tok = Lexer.getTok();
235
236     switch (Tok.getKind()) {
237     default:
238       SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
239                           "unknown token");
240       Error = true;
241       break;
242     case AsmToken::Error:
243       Error = true; // error already printed.
244       break;
245     case AsmToken::Identifier:
246       Out->os() << "identifier: " << Lexer.getTok().getString();
247       break;
248     case AsmToken::Integer:
249       Out->os() << "int: " << Lexer.getTok().getString();
250       break;
251     case AsmToken::Real:
252       Out->os() << "real: " << Lexer.getTok().getString();
253       break;
254     case AsmToken::Register:
255       Out->os() << "register: " << Lexer.getTok().getRegVal();
256       break;
257     case AsmToken::String:
258       Out->os() << "string: " << Lexer.getTok().getString();
259       break;
260
261     case AsmToken::Amp:            Out->os() << "Amp"; break;
262     case AsmToken::AmpAmp:         Out->os() << "AmpAmp"; break;
263     case AsmToken::At:             Out->os() << "At"; break;
264     case AsmToken::Caret:          Out->os() << "Caret"; break;
265     case AsmToken::Colon:          Out->os() << "Colon"; break;
266     case AsmToken::Comma:          Out->os() << "Comma"; break;
267     case AsmToken::Dollar:         Out->os() << "Dollar"; break;
268     case AsmToken::Dot:            Out->os() << "Dot"; break;
269     case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
270     case AsmToken::Eof:            Out->os() << "Eof"; break;
271     case AsmToken::Equal:          Out->os() << "Equal"; break;
272     case AsmToken::EqualEqual:     Out->os() << "EqualEqual"; break;
273     case AsmToken::Exclaim:        Out->os() << "Exclaim"; break;
274     case AsmToken::ExclaimEqual:   Out->os() << "ExclaimEqual"; break;
275     case AsmToken::Greater:        Out->os() << "Greater"; break;
276     case AsmToken::GreaterEqual:   Out->os() << "GreaterEqual"; break;
277     case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
278     case AsmToken::Hash:           Out->os() << "Hash"; break;
279     case AsmToken::LBrac:          Out->os() << "LBrac"; break;
280     case AsmToken::LCurly:         Out->os() << "LCurly"; break;
281     case AsmToken::LParen:         Out->os() << "LParen"; break;
282     case AsmToken::Less:           Out->os() << "Less"; break;
283     case AsmToken::LessEqual:      Out->os() << "LessEqual"; break;
284     case AsmToken::LessGreater:    Out->os() << "LessGreater"; break;
285     case AsmToken::LessLess:       Out->os() << "LessLess"; break;
286     case AsmToken::Minus:          Out->os() << "Minus"; break;
287     case AsmToken::Percent:        Out->os() << "Percent"; break;
288     case AsmToken::Pipe:           Out->os() << "Pipe"; break;
289     case AsmToken::PipePipe:       Out->os() << "PipePipe"; break;
290     case AsmToken::Plus:           Out->os() << "Plus"; break;
291     case AsmToken::RBrac:          Out->os() << "RBrac"; break;
292     case AsmToken::RCurly:         Out->os() << "RCurly"; break;
293     case AsmToken::RParen:         Out->os() << "RParen"; break;
294     case AsmToken::Slash:          Out->os() << "Slash"; break;
295     case AsmToken::Star:           Out->os() << "Star"; break;
296     case AsmToken::Tilde:          Out->os() << "Tilde"; break;
297     }
298
299     // Print the token string.
300     Out->os() << " (\"";
301     Out->os().write_escaped(Tok.getString());
302     Out->os() << "\")\n";
303   }
304
305   return Error;
306 }
307
308 static int AssembleInput(const char *ProgName, const Target *TheTarget, 
309                          SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
310                          MCAsmInfo &MAI, MCSubtargetInfo &STI) {
311   OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
312                                                   Str, MAI));
313   OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(STI, *Parser));
314   if (!TAP) {
315     errs() << ProgName
316            << ": error: this target does not support assembly parsing.\n";
317     return 1;
318   }
319
320   Parser->setShowParsedOperands(ShowInstOperands);
321   Parser->setTargetParser(*TAP.get());
322
323   int Res = Parser->Run(NoInitialTextSection);
324
325   return Res;
326 }
327
328 int main(int argc, char **argv) {
329   // Print a stack trace if we signal out.
330   sys::PrintStackTraceOnErrorSignal();
331   PrettyStackTraceProgram X(argc, argv);
332   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
333
334   // Initialize targets and assembly printers/parsers.
335   llvm::InitializeAllTargetInfos();
336   llvm::InitializeAllTargetMCs();
337   llvm::InitializeAllAsmParsers();
338   llvm::InitializeAllDisassemblers();
339
340   // Register the target printer for --version.
341   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
342
343   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
344   TripleName = Triple::normalize(TripleName);
345   setDwarfDebugFlags(argc, argv);
346
347   const char *ProgName = argv[0];
348   const Target *TheTarget = GetTarget(ProgName);
349   if (!TheTarget)
350     return 1;
351
352   OwningPtr<MemoryBuffer> BufferPtr;
353   if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
354     errs() << ProgName << ": " << ec.message() << '\n';
355     return 1;
356   }
357   MemoryBuffer *Buffer = BufferPtr.take();
358
359   SourceMgr SrcMgr;
360
361   // Tell SrcMgr about this buffer, which is what the parser will pick up.
362   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
363
364   // Record the location of the include directories so that the lexer can find
365   // it later.
366   SrcMgr.setIncludeDirs(IncludeDirs);
367
368
369   llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
370   assert(MAI && "Unable to create target asm info!");
371
372   llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
373   assert(MRI && "Unable to create target register info!");
374
375   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
376   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
377   OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
378   MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
379   MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
380
381   if (SaveTempLabels)
382     Ctx.setAllowTemporaryLabels(false);
383
384   Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
385   if (!DwarfDebugFlags.empty()) 
386     Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
387
388   // Package up features to be passed to target/subtarget
389   std::string FeaturesStr;
390   if (MAttrs.size()) {
391     SubtargetFeatures Features;
392     for (unsigned i = 0; i != MAttrs.size(); ++i)
393       Features.AddFeature(MAttrs[i]);
394     FeaturesStr = Features.getString();
395   }
396
397   OwningPtr<tool_output_file> Out(GetOutputStream());
398   if (!Out)
399     return 1;
400
401   formatted_raw_ostream FOS(Out->os());
402   OwningPtr<MCStreamer> Str;
403
404   OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
405   OwningPtr<MCSubtargetInfo>
406     STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
407
408   MCInstPrinter *IP;
409   if (FileType == OFT_AssemblyFile) {
410     IP =
411       TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
412     MCCodeEmitter *CE = 0;
413     MCAsmBackend *MAB = 0;
414     if (ShowEncoding) {
415       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
416       MAB = TheTarget->createMCAsmBackend(TripleName, MCPU);
417     }
418     Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
419                                            /*useLoc*/ true,
420                                            /*useCFI*/ true,
421                                            /*useDwarfDirectory*/ true,
422                                            IP, CE, MAB, ShowInst));
423
424   } else if (FileType == OFT_Null) {
425     Str.reset(createNullStreamer(Ctx));
426   } else {
427     assert(FileType == OFT_ObjectFile && "Invalid file type!");
428     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
429     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(TripleName, MCPU);
430     Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
431                                                 FOS, CE, RelaxAll,
432                                                 NoExecStack));
433   }
434
435   int Res = 1;
436   switch (Action) {
437   case AC_AsLex:
438     Res = AsLexInput(SrcMgr, *MAI, Out.get());
439     break;
440   case AC_Assemble:
441     Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI);
442     break;
443   case AC_MDisassemble:
444     IP->setUseMarkup(1);
445     // Fall through to do disassembly.
446   case AC_Disassemble:
447     Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
448                                     *Buffer, SrcMgr, Out->os());
449     break;
450   case AC_EDisassemble:
451     Res =  Disassembler::disassembleEnhanced(TripleName, *Buffer, SrcMgr, Out->os());
452     break;
453   }
454
455   // Keep output if no errors.
456   if (Res == 0) Out->keep();
457   return Res;
458 }