a64c8a650524ac9fb646c4abd8d5aa36e258734a
[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/MCContext.h"
16 #include "llvm/MC/MCStreamer.h"
17 #include "llvm/ADT/OwningPtr.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/ManagedStatic.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/PrettyStackTrace.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/System/Signals.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/Target/TargetSelect.h"
27 #include "AsmParser.h"
28 using namespace llvm;
29
30 static cl::opt<std::string>
31 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
32
33 static cl::opt<std::string>
34 OutputFilename("o", cl::desc("Output filename"),
35                cl::value_desc("filename"));
36
37 static cl::list<std::string>
38 IncludeDirs("I", cl::desc("Directory of include files"),
39             cl::value_desc("directory"), cl::Prefix);
40
41 static cl::opt<std::string>
42 TripleName("triple", cl::desc("Target triple to assemble for,"
43                           "see -version for available targets"),
44        cl::init(LLVM_HOSTTRIPLE));
45
46 enum ActionType {
47   AC_AsLex,
48   AC_Assemble
49 };
50
51 static cl::opt<ActionType>
52 Action(cl::desc("Action to perform:"),
53        cl::init(AC_Assemble),
54        cl::values(clEnumValN(AC_AsLex, "as-lex",
55                              "Lex tokens from a .s file"),
56                   clEnumValN(AC_Assemble, "assemble",
57                              "Assemble a .s file (default)"),
58                   clEnumValEnd));
59
60 static int AsLexInput(const char *ProgName) {
61   std::string ErrorMessage;
62   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
63                                                       &ErrorMessage);
64   if (Buffer == 0) {
65     errs() << ProgName << ": ";
66     if (ErrorMessage.size())
67       errs() << ErrorMessage << "\n";
68     else
69       errs() << "input file didn't read correctly.\n";
70     return 1;
71   }
72
73   SourceMgr SrcMgr;
74   
75   // Tell SrcMgr about this buffer, which is what TGParser will pick up.
76   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
77   
78   // Record the location of the include directories so that the lexer can find
79   // it later.
80   SrcMgr.setIncludeDirs(IncludeDirs);
81
82   AsmLexer Lexer(SrcMgr);
83   
84   bool Error = false;
85   
86   while (Lexer.Lex().isNot(AsmToken::Eof)) {
87     switch (Lexer.getKind()) {
88     default:
89       Lexer.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
90       Error = true;
91       break;
92     case AsmToken::Error:
93       Error = true; // error already printed.
94       break;
95     case AsmToken::Identifier:
96       outs() << "identifier: " << Lexer.getTok().getString() << '\n';
97       break;
98     case AsmToken::Register:
99       outs() << "register: " << Lexer.getTok().getString() << '\n';
100       break;
101     case AsmToken::String:
102       outs() << "string: " << Lexer.getTok().getString() << '\n';
103       break;
104     case AsmToken::Integer:
105       outs() << "int: " << Lexer.getTok().getString() << '\n';
106       break;
107
108     case AsmToken::Amp:            outs() << "Amp\n"; break;
109     case AsmToken::AmpAmp:         outs() << "AmpAmp\n"; break;
110     case AsmToken::Caret:          outs() << "Caret\n"; break;
111     case AsmToken::Colon:          outs() << "Colon\n"; break;
112     case AsmToken::Comma:          outs() << "Comma\n"; break;
113     case AsmToken::Dollar:         outs() << "Dollar\n"; break;
114     case AsmToken::EndOfStatement: outs() << "EndOfStatement\n"; break;
115     case AsmToken::Eof:            outs() << "Eof\n"; break;
116     case AsmToken::Equal:          outs() << "Equal\n"; break;
117     case AsmToken::EqualEqual:     outs() << "EqualEqual\n"; break;
118     case AsmToken::Exclaim:        outs() << "Exclaim\n"; break;
119     case AsmToken::ExclaimEqual:   outs() << "ExclaimEqual\n"; break;
120     case AsmToken::Greater:        outs() << "Greater\n"; break;
121     case AsmToken::GreaterEqual:   outs() << "GreaterEqual\n"; break;
122     case AsmToken::GreaterGreater: outs() << "GreaterGreater\n"; break;
123     case AsmToken::LParen:         outs() << "LParen\n"; break;
124     case AsmToken::Less:           outs() << "Less\n"; break;
125     case AsmToken::LessEqual:      outs() << "LessEqual\n"; break;
126     case AsmToken::LessGreater:    outs() << "LessGreater\n"; break;
127     case AsmToken::LessLess:       outs() << "LessLess\n"; break;
128     case AsmToken::Minus:          outs() << "Minus\n"; break;
129     case AsmToken::Percent:        outs() << "Percent\n"; break;
130     case AsmToken::Pipe:           outs() << "Pipe\n"; break;
131     case AsmToken::PipePipe:       outs() << "PipePipe\n"; break;
132     case AsmToken::Plus:           outs() << "Plus\n"; break;
133     case AsmToken::RParen:         outs() << "RParen\n"; break;
134     case AsmToken::Slash:          outs() << "Slash\n"; break;
135     case AsmToken::Star:           outs() << "Star\n"; break;
136     case AsmToken::Tilde:          outs() << "Tilde\n"; break;
137     }
138   }
139   
140   return Error;
141 }
142
143 static int AssembleInput(const char *ProgName) {
144   // Get the target specific parser.
145   std::string Error;
146   const Target *TheTarget =
147     TargetRegistry::lookupTarget(TripleName, 
148                                  /*FallbackToHost=*/true,
149                                  /*RequireJIT=*/false,
150                                  Error);
151   if (TheTarget == 0) {
152     errs() << ProgName << ": error: unable to get target for '" << TripleName
153            << "', see --version and --triple.\n";
154     return 1;
155   }
156
157   TargetAsmParser *TAP = TheTarget->createAsmParser();
158   if (!TAP) {
159     errs() << ProgName 
160            << ": error: this target does not support assembly parsing.\n";
161     return 1;    
162   }
163
164   std::string ErrorMessage;
165   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
166                                                       &ErrorMessage);
167   if (Buffer == 0) {
168     errs() << ProgName << ": ";
169     if (ErrorMessage.size())
170       errs() << ErrorMessage << "\n";
171     else
172       errs() << "input file didn't read correctly.\n";
173     return 1;
174   }
175   
176   SourceMgr SrcMgr;
177   
178   // Tell SrcMgr about this buffer, which is what TGParser will pick up.
179   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
180   
181   // Record the location of the include directories so that the lexer can find
182   // it later.
183   SrcMgr.setIncludeDirs(IncludeDirs);
184   
185   MCContext Ctx;
186   OwningPtr<MCStreamer> Str(createAsmStreamer(Ctx, outs()));
187
188   // FIXME: Target hook & command line option for initial section.
189   Str.get()->SwitchSection(Ctx.GetSection("__TEXT,__text,"
190                                           "regular,pure_instructions"));
191
192   AsmParser Parser(SrcMgr, Ctx, *Str.get(), *TAP);
193   return Parser.Run();
194 }  
195
196
197 int main(int argc, char **argv) {
198   // Print a stack trace if we signal out.
199   sys::PrintStackTraceOnErrorSignal();
200   PrettyStackTraceProgram X(argc, argv);
201   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
202
203   // Initialize targets and assembly parsers.
204   llvm::InitializeAllTargetInfos();
205   llvm::InitializeAllAsmParsers();
206   
207   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
208
209   switch (Action) {
210   default:
211   case AC_AsLex:
212     return AsLexInput(argv[0]);
213   case AC_Assemble:
214     return AssembleInput(argv[0]);
215   }
216   
217   return 0;
218 }
219