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/MCParser/AsmLexer.h"
16 #include "llvm/MC/MCParser/MCAsmLexer.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCCodeEmitter.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/MC/MCSubtargetInfo.h"
23 #include "llvm/MC/SubtargetFeature.h"
24 #include "llvm/Target/TargetAsmBackend.h"
25 #include "llvm/Target/TargetAsmParser.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/Target/TargetAsmInfo.h" // FIXME.
29 #include "llvm/Target/TargetLowering.h" // FIXME.
30 #include "llvm/Target/TargetLoweringObjectFile.h" // FIXME.
31 #include "llvm/Target/TargetMachine.h" // FIXME.
32 #include "llvm/Target/TargetSelect.h"
33 #include "llvm/ADT/OwningPtr.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/FileUtilities.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/system_error.h"
45 #include "Disassembler.h"
48 static cl::opt
<std::string
>
49 InputFilename(cl::Positional
, cl::desc("<input file>"), cl::init("-"));
51 static cl::opt
<std::string
>
52 OutputFilename("o", cl::desc("Output filename"),
53 cl::value_desc("filename"));
56 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
59 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
62 ShowInstOperands("show-inst-operands",
63 cl::desc("Show instructions operands as parsed"));
65 static cl::opt
<unsigned>
66 OutputAsmVariant("output-asm-variant",
67 cl::desc("Syntax variant to use for output printing"));
70 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
73 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
76 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
83 static cl::opt
<OutputFileType
>
84 FileType("filetype", cl::init(OFT_AssemblyFile
),
85 cl::desc("Choose an output file type:"),
87 clEnumValN(OFT_AssemblyFile
, "asm",
88 "Emit an assembly ('.s') file"),
89 clEnumValN(OFT_Null
, "null",
90 "Don't emit anything (for timing purposes)"),
91 clEnumValN(OFT_ObjectFile
, "obj",
92 "Emit a native object ('.o') file"),
95 static cl::list
<std::string
>
96 IncludeDirs("I", cl::desc("Directory of include files"),
97 cl::value_desc("directory"), cl::Prefix
);
99 static cl::opt
<std::string
>
100 ArchName("arch", cl::desc("Target arch to assemble for, "
101 "see -version for available targets"));
103 static cl::opt
<std::string
>
104 TripleName("triple", cl::desc("Target triple to assemble for, "
105 "see -version for available targets"));
107 static cl::opt
<std::string
>
109 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
110 cl::value_desc("cpu-name"),
114 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
115 "in the text section"));
118 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
127 static cl::opt
<ActionType
>
128 Action(cl::desc("Action to perform:"),
129 cl::init(AC_Assemble
),
130 cl::values(clEnumValN(AC_AsLex
, "as-lex",
131 "Lex tokens from a .s file"),
132 clEnumValN(AC_Assemble
, "assemble",
133 "Assemble a .s file (default)"),
134 clEnumValN(AC_Disassemble
, "disassemble",
135 "Disassemble strings of hex bytes"),
136 clEnumValN(AC_EDisassemble
, "edis",
137 "Enhanced disassembly of strings of hex bytes"),
140 static const Target
*GetTarget(const char *ProgName
) {
141 // Figure out the target triple.
142 if (TripleName
.empty())
143 TripleName
= sys::getHostTriple();
144 if (!ArchName
.empty()) {
145 llvm::Triple
TT(TripleName
);
146 TT
.setArchName(ArchName
);
147 TripleName
= TT
.str();
150 // Get the target specific parser.
152 const Target
*TheTarget
= TargetRegistry::lookupTarget(TripleName
, Error
);
156 errs() << ProgName
<< ": error: unable to get target for '" << TripleName
157 << "', see --version and --triple.\n";
161 static tool_output_file
*GetOutputStream() {
162 if (OutputFilename
== "")
163 OutputFilename
= "-";
166 tool_output_file
*Out
= new tool_output_file(OutputFilename
.c_str(), Err
,
167 raw_fd_ostream::F_Binary
);
169 errs() << Err
<< '\n';
177 static int AsLexInput(const char *ProgName
) {
178 OwningPtr
<MemoryBuffer
> BufferPtr
;
179 if (error_code ec
= MemoryBuffer::getFileOrSTDIN(InputFilename
, BufferPtr
)) {
180 errs() << ProgName
<< ": " << ec
.message() << '\n';
183 MemoryBuffer
*Buffer
= BufferPtr
.take();
187 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
188 SrcMgr
.AddNewSourceBuffer(Buffer
, SMLoc());
190 // Record the location of the include directories so that the lexer can find
192 SrcMgr
.setIncludeDirs(IncludeDirs
);
194 const Target
*TheTarget
= GetTarget(ProgName
);
198 llvm::OwningPtr
<MCAsmInfo
> MAI(TheTarget
->createAsmInfo(TripleName
));
199 assert(MAI
&& "Unable to create target asm info!");
201 AsmLexer
Lexer(*MAI
);
202 Lexer
.setBuffer(SrcMgr
.getMemoryBuffer(0));
204 OwningPtr
<tool_output_file
> Out(GetOutputStream());
209 while (Lexer
.Lex().isNot(AsmToken::Eof
)) {
210 AsmToken Tok
= Lexer
.getTok();
212 switch (Tok
.getKind()) {
214 SrcMgr
.PrintMessage(Lexer
.getLoc(), "unknown token", "warning");
217 case AsmToken::Error
:
218 Error
= true; // error already printed.
220 case AsmToken::Identifier
:
221 Out
->os() << "identifier: " << Lexer
.getTok().getString();
223 case AsmToken::Integer
:
224 Out
->os() << "int: " << Lexer
.getTok().getString();
227 Out
->os() << "real: " << Lexer
.getTok().getString();
229 case AsmToken::Register
:
230 Out
->os() << "register: " << Lexer
.getTok().getRegVal();
232 case AsmToken::String
:
233 Out
->os() << "string: " << Lexer
.getTok().getString();
236 case AsmToken::Amp
: Out
->os() << "Amp"; break;
237 case AsmToken::AmpAmp
: Out
->os() << "AmpAmp"; break;
238 case AsmToken::At
: Out
->os() << "At"; break;
239 case AsmToken::Caret
: Out
->os() << "Caret"; break;
240 case AsmToken::Colon
: Out
->os() << "Colon"; break;
241 case AsmToken::Comma
: Out
->os() << "Comma"; break;
242 case AsmToken::Dollar
: Out
->os() << "Dollar"; break;
243 case AsmToken::Dot
: Out
->os() << "Dot"; break;
244 case AsmToken::EndOfStatement
: Out
->os() << "EndOfStatement"; break;
245 case AsmToken::Eof
: Out
->os() << "Eof"; break;
246 case AsmToken::Equal
: Out
->os() << "Equal"; break;
247 case AsmToken::EqualEqual
: Out
->os() << "EqualEqual"; break;
248 case AsmToken::Exclaim
: Out
->os() << "Exclaim"; break;
249 case AsmToken::ExclaimEqual
: Out
->os() << "ExclaimEqual"; break;
250 case AsmToken::Greater
: Out
->os() << "Greater"; break;
251 case AsmToken::GreaterEqual
: Out
->os() << "GreaterEqual"; break;
252 case AsmToken::GreaterGreater
: Out
->os() << "GreaterGreater"; break;
253 case AsmToken::Hash
: Out
->os() << "Hash"; break;
254 case AsmToken::LBrac
: Out
->os() << "LBrac"; break;
255 case AsmToken::LCurly
: Out
->os() << "LCurly"; break;
256 case AsmToken::LParen
: Out
->os() << "LParen"; break;
257 case AsmToken::Less
: Out
->os() << "Less"; break;
258 case AsmToken::LessEqual
: Out
->os() << "LessEqual"; break;
259 case AsmToken::LessGreater
: Out
->os() << "LessGreater"; break;
260 case AsmToken::LessLess
: Out
->os() << "LessLess"; break;
261 case AsmToken::Minus
: Out
->os() << "Minus"; break;
262 case AsmToken::Percent
: Out
->os() << "Percent"; break;
263 case AsmToken::Pipe
: Out
->os() << "Pipe"; break;
264 case AsmToken::PipePipe
: Out
->os() << "PipePipe"; break;
265 case AsmToken::Plus
: Out
->os() << "Plus"; break;
266 case AsmToken::RBrac
: Out
->os() << "RBrac"; break;
267 case AsmToken::RCurly
: Out
->os() << "RCurly"; break;
268 case AsmToken::RParen
: Out
->os() << "RParen"; break;
269 case AsmToken::Slash
: Out
->os() << "Slash"; break;
270 case AsmToken::Star
: Out
->os() << "Star"; break;
271 case AsmToken::Tilde
: Out
->os() << "Tilde"; break;
274 // Print the token string.
276 Out
->os().write_escaped(Tok
.getString());
277 Out
->os() << "\")\n";
280 // Keep output if no errors.
281 if (Error
== 0) Out
->keep();
286 static int AssembleInput(const char *ProgName
) {
287 const Target
*TheTarget
= GetTarget(ProgName
);
291 OwningPtr
<MemoryBuffer
> BufferPtr
;
292 if (error_code ec
= MemoryBuffer::getFileOrSTDIN(InputFilename
, BufferPtr
)) {
293 errs() << ProgName
<< ": " << ec
.message() << '\n';
296 MemoryBuffer
*Buffer
= BufferPtr
.take();
300 // Tell SrcMgr about this buffer, which is what the parser will pick up.
301 SrcMgr
.AddNewSourceBuffer(Buffer
, SMLoc());
303 // Record the location of the include directories so that the lexer can find
305 SrcMgr
.setIncludeDirs(IncludeDirs
);
308 llvm::OwningPtr
<MCAsmInfo
> MAI(TheTarget
->createAsmInfo(TripleName
));
309 assert(MAI
&& "Unable to create target asm info!");
311 // Package up features to be passed to target/subtarget
312 std::string FeaturesStr
;
314 // FIXME: We shouldn't need to do this (and link in codegen).
315 // When we split this out, we should do it in a way that makes
316 // it straightforward to switch subtargets on the fly (.e.g,
317 // the .cpu and .code16 directives).
318 OwningPtr
<TargetMachine
> TM(TheTarget
->createTargetMachine(TripleName
,
323 errs() << ProgName
<< ": error: could not create target for triple '"
324 << TripleName
<< "'.\n";
328 const TargetAsmInfo
*tai
= new TargetAsmInfo(*TM
);
329 MCContext
Ctx(*MAI
, tai
);
331 Ctx
.setAllowTemporaryLabels(false);
333 OwningPtr
<tool_output_file
> Out(GetOutputStream());
337 formatted_raw_ostream
FOS(Out
->os());
338 OwningPtr
<MCStreamer
> Str
;
340 const TargetLoweringObjectFile
&TLOF
=
341 TM
->getTargetLowering()->getObjFileLowering();
342 const_cast<TargetLoweringObjectFile
&>(TLOF
).Initialize(Ctx
, *TM
);
344 OwningPtr
<MCSubtargetInfo
>
345 STI(TheTarget
->createMCSubtargetInfo(TripleName
, MCPU
, FeaturesStr
));
347 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
348 if (FileType
== OFT_AssemblyFile
) {
350 TheTarget
->createMCInstPrinter(OutputAsmVariant
, *MAI
);
351 MCCodeEmitter
*CE
= 0;
352 TargetAsmBackend
*TAB
= 0;
354 CE
= TheTarget
->createCodeEmitter(*TM
, Ctx
);
355 TAB
= TheTarget
->createAsmBackend(TripleName
);
357 Str
.reset(TheTarget
->createAsmStreamer(Ctx
, FOS
, /*asmverbose*/true,
359 /*useCFI*/ true, IP
, CE
, TAB
,
361 } else if (FileType
== OFT_Null
) {
362 Str
.reset(createNullStreamer(Ctx
));
364 assert(FileType
== OFT_ObjectFile
&& "Invalid file type!");
365 MCCodeEmitter
*CE
= TheTarget
->createCodeEmitter(*TM
, Ctx
);
366 TargetAsmBackend
*TAB
= TheTarget
->createAsmBackend(TripleName
);
367 Str
.reset(TheTarget
->createObjectStreamer(TripleName
, Ctx
, *TAB
,
373 Str
.reset(createLoggingStreamer(Str
.take(), errs()));
376 OwningPtr
<MCAsmParser
> Parser(createMCAsmParser(*TheTarget
, SrcMgr
, Ctx
,
378 OwningPtr
<TargetAsmParser
> TAP(TheTarget
->createAsmParser(*STI
, *Parser
));
381 << ": error: this target does not support assembly parsing.\n";
385 Parser
->setShowParsedOperands(ShowInstOperands
);
386 Parser
->setTargetParser(*TAP
.get());
388 int Res
= Parser
->Run(NoInitialTextSection
);
390 // Keep output if no errors.
391 if (Res
== 0) Out
->keep();
396 static int DisassembleInput(const char *ProgName
, bool Enhanced
) {
397 const Target
*TheTarget
= GetTarget(ProgName
);
401 OwningPtr
<MemoryBuffer
> Buffer
;
402 if (error_code ec
= MemoryBuffer::getFileOrSTDIN(InputFilename
, Buffer
)) {
403 errs() << ProgName
<< ": " << ec
.message() << '\n';
407 OwningPtr
<tool_output_file
> Out(GetOutputStream());
414 Disassembler::disassembleEnhanced(TripleName
, *Buffer
.take(), Out
->os());
416 // Package up features to be passed to target/subtarget
417 std::string FeaturesStr
;
419 // FIXME: We shouldn't need to do this (and link in codegen).
420 // When we split this out, we should do it in a way that makes
421 // it straightforward to switch subtargets on the fly (.e.g,
422 // the .cpu and .code16 directives).
423 OwningPtr
<TargetMachine
> TM(TheTarget
->createTargetMachine(TripleName
,
428 errs() << ProgName
<< ": error: could not create target for triple '"
429 << TripleName
<< "'.\n";
433 Res
= Disassembler::disassemble(*TheTarget
, TripleName
,
434 *Buffer
.take(), Out
->os());
437 // Keep output if no errors.
438 if (Res
== 0) Out
->keep();
444 int main(int argc
, char **argv
) {
445 // Print a stack trace if we signal out.
446 sys::PrintStackTraceOnErrorSignal();
447 PrettyStackTraceProgram
X(argc
, argv
);
448 llvm_shutdown_obj Y
; // Call llvm_shutdown() on exit.
450 // Initialize targets and assembly printers/parsers.
451 llvm::InitializeAllTargetInfos();
452 // FIXME: We shouldn't need to initialize the Target(Machine)s.
453 llvm::InitializeAllTargets();
454 llvm::InitializeAllMCSubtargetInfos();
455 llvm::InitializeAllAsmPrinters();
456 llvm::InitializeAllAsmParsers();
457 llvm::InitializeAllDisassemblers();
459 cl::ParseCommandLineOptions(argc
, argv
, "llvm machine code playground\n");
460 TripleName
= Triple::normalize(TripleName
);
465 return AsLexInput(argv
[0]);
467 return AssembleInput(argv
[0]);
469 return DisassembleInput(argv
[0], false);
470 case AC_EDisassemble
:
471 return DisassembleInput(argv
[0], true);