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/Target/TargetAsmBackend.h"
23 #include "llvm/Target/TargetAsmParser.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/Target/SubtargetFeature.h" // FIXME.
27 #include "llvm/Target/TargetAsmInfo.h" // FIXME.
28 #include "llvm/Target/TargetLowering.h" // FIXME.
29 #include "llvm/Target/TargetLoweringObjectFile.h" // FIXME.
30 #include "llvm/Target/TargetMachine.h" // FIXME.
31 #include "llvm/Target/TargetSelect.h"
32 #include "llvm/ADT/OwningPtr.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileUtilities.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/PrettyStackTrace.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/system_error.h"
44 #include "Disassembler.h"
47 static cl::opt<std::string>
48 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
50 static cl::opt<std::string>
51 OutputFilename("o", cl::desc("Output filename"),
52 cl::value_desc("filename"));
55 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
58 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
61 ShowInstOperands("show-inst-operands",
62 cl::desc("Show instructions operands as parsed"));
65 DecodeLSDA("decode-lsda",
66 cl::desc("Print LSDA in human readable format"));
68 static cl::opt<unsigned>
69 OutputAsmVariant("output-asm-variant",
70 cl::desc("Syntax variant to use for output printing"));
73 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
76 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
79 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
86 static cl::opt<OutputFileType>
87 FileType("filetype", cl::init(OFT_AssemblyFile),
88 cl::desc("Choose an output file type:"),
90 clEnumValN(OFT_AssemblyFile, "asm",
91 "Emit an assembly ('.s') file"),
92 clEnumValN(OFT_Null, "null",
93 "Don't emit anything (for timing purposes)"),
94 clEnumValN(OFT_ObjectFile, "obj",
95 "Emit a native object ('.o') file"),
98 static cl::list<std::string>
99 IncludeDirs("I", cl::desc("Directory of include files"),
100 cl::value_desc("directory"), cl::Prefix);
102 static cl::opt<std::string>
103 ArchName("arch", cl::desc("Target arch to assemble for, "
104 "see -version for available targets"));
106 static cl::opt<std::string>
107 TripleName("triple", cl::desc("Target triple to assemble for, "
108 "see -version for available targets"));
110 static cl::opt<std::string>
112 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
113 cl::value_desc("cpu-name"),
117 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
118 "in the text section"));
121 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
130 static cl::opt<ActionType>
131 Action(cl::desc("Action to perform:"),
132 cl::init(AC_Assemble),
133 cl::values(clEnumValN(AC_AsLex, "as-lex",
134 "Lex tokens from a .s file"),
135 clEnumValN(AC_Assemble, "assemble",
136 "Assemble a .s file (default)"),
137 clEnumValN(AC_Disassemble, "disassemble",
138 "Disassemble strings of hex bytes"),
139 clEnumValN(AC_EDisassemble, "edis",
140 "Enhanced disassembly of strings of hex bytes"),
143 static const Target *GetTarget(const char *ProgName) {
144 // Figure out the target triple.
145 if (TripleName.empty())
146 TripleName = sys::getHostTriple();
147 if (!ArchName.empty()) {
148 llvm::Triple TT(TripleName);
149 TT.setArchName(ArchName);
150 TripleName = TT.str();
153 // Get the target specific parser.
155 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
159 errs() << ProgName << ": error: unable to get target for '" << TripleName
160 << "', see --version and --triple.\n";
164 static tool_output_file *GetOutputStream() {
165 if (OutputFilename == "")
166 OutputFilename = "-";
169 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
170 raw_fd_ostream::F_Binary);
172 errs() << Err << '\n';
180 static int AsLexInput(const char *ProgName) {
181 OwningPtr<MemoryBuffer> BufferPtr;
182 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
183 errs() << ProgName << ": " << ec.message() << '\n';
186 MemoryBuffer *Buffer = BufferPtr.take();
190 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
191 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
193 // Record the location of the include directories so that the lexer can find
195 SrcMgr.setIncludeDirs(IncludeDirs);
197 const Target *TheTarget = GetTarget(ProgName);
201 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
202 assert(MAI && "Unable to create target asm info!");
204 AsmLexer Lexer(*MAI);
205 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
207 OwningPtr<tool_output_file> Out(GetOutputStream());
212 while (Lexer.Lex().isNot(AsmToken::Eof)) {
213 AsmToken Tok = Lexer.getTok();
215 switch (Tok.getKind()) {
217 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
220 case AsmToken::Error:
221 Error = true; // error already printed.
223 case AsmToken::Identifier:
224 Out->os() << "identifier: " << Lexer.getTok().getString();
226 case AsmToken::Integer:
227 Out->os() << "int: " << Lexer.getTok().getString();
230 Out->os() << "real: " << Lexer.getTok().getString();
232 case AsmToken::Register:
233 Out->os() << "register: " << Lexer.getTok().getRegVal();
235 case AsmToken::String:
236 Out->os() << "string: " << Lexer.getTok().getString();
239 case AsmToken::Amp: Out->os() << "Amp"; break;
240 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
241 case AsmToken::At: Out->os() << "At"; break;
242 case AsmToken::Caret: Out->os() << "Caret"; break;
243 case AsmToken::Colon: Out->os() << "Colon"; break;
244 case AsmToken::Comma: Out->os() << "Comma"; break;
245 case AsmToken::Dollar: Out->os() << "Dollar"; break;
246 case AsmToken::Dot: Out->os() << "Dot"; break;
247 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
248 case AsmToken::Eof: Out->os() << "Eof"; break;
249 case AsmToken::Equal: Out->os() << "Equal"; break;
250 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
251 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
252 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
253 case AsmToken::Greater: Out->os() << "Greater"; break;
254 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
255 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
256 case AsmToken::Hash: Out->os() << "Hash"; break;
257 case AsmToken::LBrac: Out->os() << "LBrac"; break;
258 case AsmToken::LCurly: Out->os() << "LCurly"; break;
259 case AsmToken::LParen: Out->os() << "LParen"; break;
260 case AsmToken::Less: Out->os() << "Less"; break;
261 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
262 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
263 case AsmToken::LessLess: Out->os() << "LessLess"; break;
264 case AsmToken::Minus: Out->os() << "Minus"; break;
265 case AsmToken::Percent: Out->os() << "Percent"; break;
266 case AsmToken::Pipe: Out->os() << "Pipe"; break;
267 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
268 case AsmToken::Plus: Out->os() << "Plus"; break;
269 case AsmToken::RBrac: Out->os() << "RBrac"; break;
270 case AsmToken::RCurly: Out->os() << "RCurly"; break;
271 case AsmToken::RParen: Out->os() << "RParen"; break;
272 case AsmToken::Slash: Out->os() << "Slash"; break;
273 case AsmToken::Star: Out->os() << "Star"; break;
274 case AsmToken::Tilde: Out->os() << "Tilde"; break;
277 // Print the token string.
279 Out->os().write_escaped(Tok.getString());
280 Out->os() << "\")\n";
283 // Keep output if no errors.
284 if (Error == 0) Out->keep();
289 static int AssembleInput(const char *ProgName) {
290 const Target *TheTarget = GetTarget(ProgName);
294 OwningPtr<MemoryBuffer> BufferPtr;
295 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
296 errs() << ProgName << ": " << ec.message() << '\n';
299 MemoryBuffer *Buffer = BufferPtr.take();
303 // Tell SrcMgr about this buffer, which is what the parser will pick up.
304 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
306 // Record the location of the include directories so that the lexer can find
308 SrcMgr.setIncludeDirs(IncludeDirs);
311 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
312 assert(MAI && "Unable to create target asm info!");
314 // Package up features to be passed to target/subtarget
315 std::string FeaturesStr;
317 SubtargetFeatures Features;
318 Features.setCPU(MCPU);
319 FeaturesStr = Features.getString();
322 // FIXME: We shouldn't need to do this (and link in codegen).
323 // When we split this out, we should do it in a way that makes
324 // it straightforward to switch subtargets on the fly (.e.g,
325 // the .cpu and .code16 directives).
326 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
330 errs() << ProgName << ": error: could not create target for triple '"
331 << TripleName << "'.\n";
335 const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
336 MCContext Ctx(*MAI, tai);
338 Ctx.setAllowTemporaryLabels(false);
340 OwningPtr<tool_output_file> Out(GetOutputStream());
344 formatted_raw_ostream FOS(Out->os());
345 OwningPtr<MCStreamer> Str;
347 const TargetLoweringObjectFile &TLOF =
348 TM->getTargetLowering()->getObjFileLowering();
349 const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
351 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
352 if (FileType == OFT_AssemblyFile) {
354 TheTarget->createMCInstPrinter(*TM, OutputAsmVariant, *MAI);
355 MCCodeEmitter *CE = 0;
356 TargetAsmBackend *TAB = 0;
358 CE = TheTarget->createCodeEmitter(*TM, Ctx);
359 TAB = TheTarget->createAsmBackend(TripleName);
361 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
363 /*useCFI*/ true, IP, CE, TAB,
366 } else if (FileType == OFT_Null) {
367 Str.reset(createNullStreamer(Ctx));
369 assert(FileType == OFT_ObjectFile && "Invalid file type!");
370 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
371 TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
372 Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
378 Str.reset(createLoggingStreamer(Str.take(), errs()));
381 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
383 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
386 << ": error: this target does not support assembly parsing.\n";
390 Parser->setShowParsedOperands(ShowInstOperands);
391 Parser->setTargetParser(*TAP.get());
393 int Res = Parser->Run(NoInitialTextSection);
395 // Keep output if no errors.
396 if (Res == 0) Out->keep();
401 static int DisassembleInput(const char *ProgName, bool Enhanced) {
402 const Target *TheTarget = GetTarget(ProgName);
406 OwningPtr<MemoryBuffer> Buffer;
407 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
408 errs() << ProgName << ": " << ec.message() << '\n';
412 OwningPtr<tool_output_file> Out(GetOutputStream());
419 Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
421 // Package up features to be passed to target/subtarget
422 std::string FeaturesStr;
424 SubtargetFeatures Features;
425 Features.setCPU(MCPU);
426 FeaturesStr = Features.getString();
429 // FIXME: We shouldn't need to do this (and link in codegen).
430 // When we split this out, we should do it in a way that makes
431 // it straightforward to switch subtargets on the fly (.e.g,
432 // the .cpu and .code16 directives).
433 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
437 errs() << ProgName << ": error: could not create target for triple '"
438 << TripleName << "'.\n";
442 Res = Disassembler::disassemble(*TheTarget, *TM, TripleName,
443 *Buffer.take(), Out->os());
446 // Keep output if no errors.
447 if (Res == 0) Out->keep();
453 int main(int argc, char **argv) {
454 // Print a stack trace if we signal out.
455 sys::PrintStackTraceOnErrorSignal();
456 PrettyStackTraceProgram X(argc, argv);
457 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
459 // Initialize targets and assembly printers/parsers.
460 llvm::InitializeAllTargetInfos();
461 // FIXME: We shouldn't need to initialize the Target(Machine)s.
462 llvm::InitializeAllTargets();
463 llvm::InitializeAllAsmPrinters();
464 llvm::InitializeAllAsmParsers();
465 llvm::InitializeAllDisassemblers();
467 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
468 TripleName = Triple::normalize(TripleName);
473 return AsLexInput(argv[0]);
475 return AssembleInput(argv[0]);
477 return DisassembleInput(argv[0], false);
478 case AC_EDisassemble:
479 return DisassembleInput(argv[0], true);