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