1 //===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This utility is a simple driver that allows command line hacking on machine
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"
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"));
45 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
51 static cl::opt
<OutputFileType
>
52 FileType("filetype", cl::init(OFT_AssemblyFile
),
53 cl::desc("Choose an output file type:"),
55 clEnumValN(OFT_AssemblyFile
, "asm",
56 "Emit an assembly ('.s') file"),
57 clEnumValN(OFT_ObjectFile
, "obj",
58 "Emit a native object ('.o') file"),
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
));
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)"),
87 static const Target
*GetTarget(const char *ProgName
) {
88 // Get the target specific parser.
90 const Target
*TheTarget
= TargetRegistry::lookupTarget(TripleName
, Error
);
94 errs() << ProgName
<< ": error: unable to get target for '" << TripleName
95 << "', see --version and --triple.\n";
99 static int AsLexInput(const char *ProgName
) {
100 std::string ErrorMessage
;
101 MemoryBuffer
*Buffer
= MemoryBuffer::getFileOrSTDIN(InputFilename
,
104 errs() << ProgName
<< ": ";
105 if (ErrorMessage
.size())
106 errs() << ErrorMessage
<< "\n";
108 errs() << "input file didn't read correctly.\n";
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
119 SrcMgr
.setIncludeDirs(IncludeDirs
);
121 const Target
*TheTarget
= GetTarget(ProgName
);
125 const MCAsmInfo
*MAI
= TheTarget
->createAsmInfo(TripleName
);
126 assert(MAI
&& "Unable to create target asm info!");
128 AsmLexer
Lexer(SrcMgr
, *MAI
);
132 while (Lexer
.Lex().isNot(AsmToken::Eof
)) {
133 switch (Lexer
.getKind()) {
135 Lexer
.PrintMessage(Lexer
.getLoc(), "unknown token", "warning");
138 case AsmToken::Error
:
139 Error
= true; // error already printed.
141 case AsmToken::Identifier
:
142 outs() << "identifier: " << Lexer
.getTok().getString() << '\n';
144 case AsmToken::String
:
145 outs() << "string: " << Lexer
.getTok().getString() << '\n';
147 case AsmToken::Integer
:
148 outs() << "int: " << Lexer
.getTok().getString() << '\n';
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;
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
192 if (OutputFilename
!= "-")
193 sys::RemoveFileOnSignal(sys::Path(OutputFilename
));
196 raw_fd_ostream
*Out
= new raw_fd_ostream(OutputFilename
.c_str(), Err
,
197 raw_fd_ostream::F_Binary
);
199 errs() << Err
<< '\n';
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
);
213 MemoryBuffer
*Buffer
= MemoryBuffer::getFileOrSTDIN(InputFilename
, &Error
);
215 errs() << ProgName
<< ": ";
217 errs() << Error
<< "\n";
219 errs() << "input file didn't read correctly.\n";
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
230 SrcMgr
.setIncludeDirs(IncludeDirs
);
233 formatted_raw_ostream
*Out
= GetOutputStream();
238 // FIXME: We shouldn't need to do this (and link in codegen).
239 OwningPtr
<TargetMachine
> TM(TheTarget
->createTargetMachine(TripleName
, ""));
242 errs() << ProgName
<< ": error: could not create target for triple '"
243 << TripleName
<< "'.\n";
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
));
259 CE
.reset(TheTarget
->createCodeEmitter(*TM
));
260 Str
.reset(createAsmStreamer(Ctx
, *Out
, *MAI
, IP
.get(), CE
.get()));
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
));
271 << ": error: this target does not support assembly parsing.\n";
275 Parser
.setTargetParser(*TAP
.get());
277 int Res
= Parser
.Run();
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");
303 return AsLexInput(argv
[0]);
305 return AssembleInput(argv
[0]);