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/MCContext.h"
16 #include "llvm/MC/MCCodeEmitter.h"
17 #include "llvm/MC/MCSectionMachO.h"
18 #include "llvm/MC/MCStreamer.h"
19 #include "llvm/MC/MCAsmLexer.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/CodeGen/AsmPrinter.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/TargetSelect.h"
33 #include "AsmParser.h"
36 static cl::opt
<std::string
>
37 InputFilename(cl::Positional
, cl::desc("<input file>"), cl::init("-"));
39 static cl::opt
<std::string
>
40 OutputFilename("o", cl::desc("Output filename"),
41 cl::value_desc("filename"));
44 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
50 static cl::opt
<OutputFileType
>
51 FileType("filetype", cl::init(OFT_AssemblyFile
),
52 cl::desc("Choose an output file type:"),
54 clEnumValN(OFT_AssemblyFile
, "asm",
55 "Emit an assembly ('.s') file"),
56 clEnumValN(OFT_ObjectFile
, "obj",
57 "Emit a native object ('.o') file"),
61 Force("f", cl::desc("Enable binary output on terminals"));
63 static cl::list
<std::string
>
64 IncludeDirs("I", cl::desc("Directory of include files"),
65 cl::value_desc("directory"), cl::Prefix
);
67 static cl::opt
<std::string
>
68 TripleName("triple", cl::desc("Target triple to assemble for,"
69 "see -version for available targets"),
70 cl::init(LLVM_HOSTTRIPLE
));
77 static cl::opt
<ActionType
>
78 Action(cl::desc("Action to perform:"),
79 cl::init(AC_Assemble
),
80 cl::values(clEnumValN(AC_AsLex
, "as-lex",
81 "Lex tokens from a .s file"),
82 clEnumValN(AC_Assemble
, "assemble",
83 "Assemble a .s file (default)"),
86 static const Target
*GetTarget(const char *ProgName
) {
87 // Get the target specific parser.
89 const Target
*TheTarget
= TargetRegistry::lookupTarget(TripleName
, Error
);
93 errs() << ProgName
<< ": error: unable to get target for '" << TripleName
94 << "', see --version and --triple.\n";
98 static int AsLexInput(const char *ProgName
) {
99 std::string ErrorMessage
;
100 MemoryBuffer
*Buffer
= MemoryBuffer::getFileOrSTDIN(InputFilename
,
103 errs() << ProgName
<< ": ";
104 if (ErrorMessage
.size())
105 errs() << ErrorMessage
<< "\n";
107 errs() << "input file didn't read correctly.\n";
113 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
114 SrcMgr
.AddNewSourceBuffer(Buffer
, SMLoc());
116 // Record the location of the include directories so that the lexer can find
118 SrcMgr
.setIncludeDirs(IncludeDirs
);
120 const Target
*TheTarget
= GetTarget(ProgName
);
124 const MCAsmInfo
*MAI
= TheTarget
->createAsmInfo(TripleName
);
125 assert(MAI
&& "Unable to create target asm info!");
127 AsmLexer
Lexer(SrcMgr
, *MAI
);
131 while (Lexer
.Lex().isNot(AsmToken::Eof
)) {
132 switch (Lexer
.getKind()) {
134 Lexer
.PrintMessage(Lexer
.getLoc(), "unknown token", "warning");
137 case AsmToken::Error
:
138 Error
= true; // error already printed.
140 case AsmToken::Identifier
:
141 outs() << "identifier: " << Lexer
.getTok().getString() << '\n';
143 case AsmToken::String
:
144 outs() << "string: " << Lexer
.getTok().getString() << '\n';
146 case AsmToken::Integer
:
147 outs() << "int: " << Lexer
.getTok().getString() << '\n';
150 case AsmToken::Amp
: outs() << "Amp\n"; break;
151 case AsmToken::AmpAmp
: outs() << "AmpAmp\n"; break;
152 case AsmToken::Caret
: outs() << "Caret\n"; break;
153 case AsmToken::Colon
: outs() << "Colon\n"; break;
154 case AsmToken::Comma
: outs() << "Comma\n"; break;
155 case AsmToken::Dollar
: outs() << "Dollar\n"; break;
156 case AsmToken::EndOfStatement
: outs() << "EndOfStatement\n"; break;
157 case AsmToken::Eof
: outs() << "Eof\n"; break;
158 case AsmToken::Equal
: outs() << "Equal\n"; break;
159 case AsmToken::EqualEqual
: outs() << "EqualEqual\n"; break;
160 case AsmToken::Exclaim
: outs() << "Exclaim\n"; break;
161 case AsmToken::ExclaimEqual
: outs() << "ExclaimEqual\n"; break;
162 case AsmToken::Greater
: outs() << "Greater\n"; break;
163 case AsmToken::GreaterEqual
: outs() << "GreaterEqual\n"; break;
164 case AsmToken::GreaterGreater
: outs() << "GreaterGreater\n"; break;
165 case AsmToken::LParen
: outs() << "LParen\n"; break;
166 case AsmToken::Less
: outs() << "Less\n"; break;
167 case AsmToken::LessEqual
: outs() << "LessEqual\n"; break;
168 case AsmToken::LessGreater
: outs() << "LessGreater\n"; break;
169 case AsmToken::LessLess
: outs() << "LessLess\n"; break;
170 case AsmToken::Minus
: outs() << "Minus\n"; break;
171 case AsmToken::Percent
: outs() << "Percent\n"; break;
172 case AsmToken::Pipe
: outs() << "Pipe\n"; break;
173 case AsmToken::PipePipe
: outs() << "PipePipe\n"; break;
174 case AsmToken::Plus
: outs() << "Plus\n"; break;
175 case AsmToken::RParen
: outs() << "RParen\n"; break;
176 case AsmToken::Slash
: outs() << "Slash\n"; break;
177 case AsmToken::Star
: outs() << "Star\n"; break;
178 case AsmToken::Tilde
: outs() << "Tilde\n"; break;
185 static formatted_raw_ostream
*GetOutputStream() {
186 if (OutputFilename
== "")
187 OutputFilename
= "-";
189 // Make sure that the Out file gets unlinked from the disk if we get a
191 if (OutputFilename
!= "-")
192 sys::RemoveFileOnSignal(sys::Path(OutputFilename
));
195 raw_fd_ostream
*Out
= new raw_fd_ostream(OutputFilename
.c_str(), Err
,
196 raw_fd_ostream::F_Binary
);
198 errs() << Err
<< '\n';
203 return new formatted_raw_ostream(*Out
, formatted_raw_ostream::DELETE_STREAM
);
206 static int AssembleInput(const char *ProgName
) {
207 const Target
*TheTarget
= GetTarget(ProgName
);
212 MemoryBuffer
*Buffer
= MemoryBuffer::getFileOrSTDIN(InputFilename
, &Error
);
214 errs() << ProgName
<< ": ";
216 errs() << Error
<< "\n";
218 errs() << "input file didn't read correctly.\n";
224 // Tell SrcMgr about this buffer, which is what the parser will pick up.
225 SrcMgr
.AddNewSourceBuffer(Buffer
, SMLoc());
227 // Record the location of the include directories so that the lexer can find
229 SrcMgr
.setIncludeDirs(IncludeDirs
);
232 formatted_raw_ostream
*Out
= GetOutputStream();
237 // FIXME: We shouldn't need to do this (and link in codegen).
238 OwningPtr
<TargetMachine
> TM(TheTarget
->createTargetMachine(TripleName
, ""));
241 errs() << ProgName
<< ": error: could not create target for triple '"
242 << TripleName
<< "'.\n";
246 OwningPtr
<AsmPrinter
> AP
;
247 OwningPtr
<MCCodeEmitter
> CE
;
248 OwningPtr
<MCStreamer
> Str
;
250 const MCAsmInfo
*MAI
= TheTarget
->createAsmInfo(TripleName
);
251 assert(MAI
&& "Unable to create target asm info!");
253 if (FileType
== OFT_AssemblyFile
) {
254 AP
.reset(TheTarget
->createAsmPrinter(*Out
, *TM
, MAI
, true));
256 CE
.reset(TheTarget
->createCodeEmitter(*TM
));
257 Str
.reset(createAsmStreamer(Ctx
, *Out
, *MAI
, AP
.get(), CE
.get()));
259 assert(FileType
== OFT_ObjectFile
&& "Invalid file type!");
260 CE
.reset(TheTarget
->createCodeEmitter(*TM
));
261 Str
.reset(createMachOStreamer(Ctx
, *Out
, CE
.get()));
264 AsmParser
Parser(SrcMgr
, Ctx
, *Str
.get(), *MAI
);
265 OwningPtr
<TargetAsmParser
> TAP(TheTarget
->createAsmParser(Parser
));
268 << ": error: this target does not support assembly parsing.\n";
272 Parser
.setTargetParser(*TAP
.get());
274 int Res
= Parser
.Run();
282 int main(int argc
, char **argv
) {
283 // Print a stack trace if we signal out.
284 sys::PrintStackTraceOnErrorSignal();
285 PrettyStackTraceProgram
X(argc
, argv
);
286 llvm_shutdown_obj Y
; // Call llvm_shutdown() on exit.
288 // Initialize targets and assembly printers/parsers.
289 llvm::InitializeAllTargetInfos();
290 // FIXME: We shouldn't need to initialize the Target(Machine)s.
291 llvm::InitializeAllTargets();
292 llvm::InitializeAllAsmPrinters();
293 llvm::InitializeAllAsmParsers();
295 cl::ParseCommandLineOptions(argc
, argv
, "llvm machine code playground\n");
300 return AsLexInput(argv
[0]);
302 return AssembleInput(argv
[0]);