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