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