llvm-mc.cpp revision c22e0b2443afdedb6d9b225b938ad404d63cdbe6
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/MCContext.h"
16#include "llvm/MC/MCSectionMachO.h"
17#include "llvm/MC/MCStreamer.h"
18#include "llvm/ADT/OwningPtr.h"
19#include "llvm/CodeGen/AsmPrinter.h"
20#include "llvm/Support/CommandLine.h"
21#include "llvm/Support/FormattedStream.h"
22#include "llvm/Support/ManagedStatic.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/PrettyStackTrace.h"
25#include "llvm/Support/SourceMgr.h"
26#include "llvm/Support/raw_ostream.h"
27#include "llvm/System/Signals.h"
28#include "llvm/Target/TargetAsmParser.h"
29#include "llvm/Target/TargetRegistry.h"
30#include "llvm/Target/TargetSelect.h"
31#include "AsmParser.h"
32using namespace llvm;
33
34static cl::opt<std::string>
35InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
36
37static cl::opt<std::string>
38OutputFilename("o", cl::desc("Output filename"),
39               cl::value_desc("filename"));
40
41static cl::opt<bool>
42Force("f", cl::desc("Overwrite output files"));
43
44static cl::list<std::string>
45IncludeDirs("I", cl::desc("Directory of include files"),
46            cl::value_desc("directory"), cl::Prefix);
47
48static cl::opt<std::string>
49TripleName("triple", cl::desc("Target triple to assemble for,"
50                          "see -version for available targets"),
51       cl::init(LLVM_HOSTTRIPLE));
52
53enum ActionType {
54  AC_AsLex,
55  AC_Assemble
56};
57
58static cl::opt<ActionType>
59Action(cl::desc("Action to perform:"),
60       cl::init(AC_Assemble),
61       cl::values(clEnumValN(AC_AsLex, "as-lex",
62                             "Lex tokens from a .s file"),
63                  clEnumValN(AC_Assemble, "assemble",
64                             "Assemble a .s file (default)"),
65                  clEnumValEnd));
66
67static int AsLexInput(const char *ProgName) {
68  std::string ErrorMessage;
69  MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
70                                                      &ErrorMessage);
71  if (Buffer == 0) {
72    errs() << ProgName << ": ";
73    if (ErrorMessage.size())
74      errs() << ErrorMessage << "\n";
75    else
76      errs() << "input file didn't read correctly.\n";
77    return 1;
78  }
79
80  SourceMgr SrcMgr;
81
82  // Tell SrcMgr about this buffer, which is what TGParser will pick up.
83  SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
84
85  // Record the location of the include directories so that the lexer can find
86  // it later.
87  SrcMgr.setIncludeDirs(IncludeDirs);
88
89  AsmLexer Lexer(SrcMgr);
90
91  bool Error = false;
92
93  while (Lexer.Lex().isNot(AsmToken::Eof)) {
94    switch (Lexer.getKind()) {
95    default:
96      Lexer.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
97      Error = true;
98      break;
99    case AsmToken::Error:
100      Error = true; // error already printed.
101      break;
102    case AsmToken::Identifier:
103      outs() << "identifier: " << Lexer.getTok().getString() << '\n';
104      break;
105    case AsmToken::Register:
106      outs() << "register: " << Lexer.getTok().getString() << '\n';
107      break;
108    case AsmToken::String:
109      outs() << "string: " << Lexer.getTok().getString() << '\n';
110      break;
111    case AsmToken::Integer:
112      outs() << "int: " << Lexer.getTok().getString() << '\n';
113      break;
114
115    case AsmToken::Amp:            outs() << "Amp\n"; break;
116    case AsmToken::AmpAmp:         outs() << "AmpAmp\n"; break;
117    case AsmToken::Caret:          outs() << "Caret\n"; break;
118    case AsmToken::Colon:          outs() << "Colon\n"; break;
119    case AsmToken::Comma:          outs() << "Comma\n"; break;
120    case AsmToken::Dollar:         outs() << "Dollar\n"; break;
121    case AsmToken::EndOfStatement: outs() << "EndOfStatement\n"; break;
122    case AsmToken::Eof:            outs() << "Eof\n"; break;
123    case AsmToken::Equal:          outs() << "Equal\n"; break;
124    case AsmToken::EqualEqual:     outs() << "EqualEqual\n"; break;
125    case AsmToken::Exclaim:        outs() << "Exclaim\n"; break;
126    case AsmToken::ExclaimEqual:   outs() << "ExclaimEqual\n"; break;
127    case AsmToken::Greater:        outs() << "Greater\n"; break;
128    case AsmToken::GreaterEqual:   outs() << "GreaterEqual\n"; break;
129    case AsmToken::GreaterGreater: outs() << "GreaterGreater\n"; break;
130    case AsmToken::LParen:         outs() << "LParen\n"; break;
131    case AsmToken::Less:           outs() << "Less\n"; break;
132    case AsmToken::LessEqual:      outs() << "LessEqual\n"; break;
133    case AsmToken::LessGreater:    outs() << "LessGreater\n"; break;
134    case AsmToken::LessLess:       outs() << "LessLess\n"; break;
135    case AsmToken::Minus:          outs() << "Minus\n"; break;
136    case AsmToken::Percent:        outs() << "Percent\n"; break;
137    case AsmToken::Pipe:           outs() << "Pipe\n"; break;
138    case AsmToken::PipePipe:       outs() << "PipePipe\n"; break;
139    case AsmToken::Plus:           outs() << "Plus\n"; break;
140    case AsmToken::RParen:         outs() << "RParen\n"; break;
141    case AsmToken::Slash:          outs() << "Slash\n"; break;
142    case AsmToken::Star:           outs() << "Star\n"; break;
143    case AsmToken::Tilde:          outs() << "Tilde\n"; break;
144    }
145  }
146
147  return Error;
148}
149
150static const Target *GetTarget(const char *ProgName) {
151  // Get the target specific parser.
152  std::string Error;
153  const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
154  if (TheTarget)
155    return TheTarget;
156
157  errs() << ProgName << ": error: unable to get target for '" << TripleName
158         << "', see --version and --triple.\n";
159  return 0;
160}
161
162static formatted_raw_ostream *GetOutputStream() {
163  if (OutputFilename == "" || OutputFilename == "-")
164    return &fouts();
165
166  // Make sure that the Out file gets unlinked from the disk if we get a
167  // SIGINT
168  sys::RemoveFileOnSignal(sys::Path(OutputFilename));
169
170  std::string Err;
171  raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(),
172                                           /*Binary=*/false, Force, Err);
173  if (!Err.empty()) {
174    errs() << Err << '\n';
175    if (!Force)
176      errs() << "Use -f command line argument to force output\n";
177    delete Out;
178    return 0;
179  }
180
181  return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
182}
183
184static int AssembleInput(const char *ProgName) {
185  const Target *TheTarget = GetTarget(ProgName);
186  if (!TheTarget)
187    return 1;
188
189  std::string Error;
190  MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
191  if (Buffer == 0) {
192    errs() << ProgName << ": ";
193    if (Error.size())
194      errs() << Error << "\n";
195    else
196      errs() << "input file didn't read correctly.\n";
197    return 1;
198  }
199
200  SourceMgr SrcMgr;
201
202  // Tell SrcMgr about this buffer, which is what TGParser will pick up.
203  SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
204
205  // Record the location of the include directories so that the lexer can find
206  // it later.
207  SrcMgr.setIncludeDirs(IncludeDirs);
208
209  MCContext Ctx;
210  formatted_raw_ostream *Out = GetOutputStream();
211  if (!Out)
212    return 1;
213
214  // See if we can get an asm printer.
215  OwningPtr<AsmPrinter> AP(0);
216
217  // FIXME: We shouldn't need to do this (and link in codegen).
218  OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
219  const TargetAsmInfo *TAI = 0;
220
221  if (TM) {
222    TAI = TheTarget->createAsmInfo(TripleName);
223    assert(TAI && "Unable to create target asm info!");
224
225    AP.reset(TheTarget->createAsmPrinter(*Out, *TM, TAI, true));
226  }
227
228  OwningPtr<MCStreamer> Str(createAsmStreamer(Ctx, *Out, AP.get()));
229
230  // FIXME: Target hook & command line option for initial section.
231  Str.get()->SwitchSection(MCSectionMachO::Create("__TEXT","__text",
232                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
233                                                  0, SectionKind::getText(),
234                                                  Ctx));
235
236  AsmParser Parser(SrcMgr, Ctx, *Str.get());
237  OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
238  if (!TAP) {
239    errs() << ProgName
240           << ": error: this target does not support assembly parsing.\n";
241    return 1;
242  }
243
244  Parser.setTargetParser(*TAP.get());
245
246  int Res = Parser.Run();
247  if (Out != &fouts())
248    delete Out;
249
250  return Res;
251}
252
253
254int main(int argc, char **argv) {
255  // Print a stack trace if we signal out.
256  sys::PrintStackTraceOnErrorSignal();
257  PrettyStackTraceProgram X(argc, argv);
258  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
259
260  // Initialize targets and assembly printers/parsers.
261  llvm::InitializeAllTargetInfos();
262  // FIXME: We shouldn't need to initialize the Target(Machine)s.
263  llvm::InitializeAllTargets();
264  llvm::InitializeAllAsmPrinters();
265  llvm::InitializeAllAsmParsers();
266
267  cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
268
269  switch (Action) {
270  default:
271  case AC_AsLex:
272    return AsLexInput(argv[0]);
273  case AC_Assemble:
274    return AssembleInput(argv[0]);
275  }
276
277  return 0;
278}
279
280