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