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/MCAsmBackend.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCCodeEmitter.h"
20 #include "llvm/MC/MCInstPrinter.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCRegisterInfo.h"
24 #include "llvm/MC/MCSectionMachO.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCTargetAsmParser.h"
28 #include "llvm/MC/SubtargetFeature.h"
29 #include "llvm/Target/TargetRegistry.h"
30 #include "llvm/Target/TargetSelect.h"
31 #include "llvm/ADT/OwningPtr.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/ToolOutputFile.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/system_error.h"
43 #include "Disassembler.h"
46 static cl::opt<std::string>
47 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
49 static cl::opt<std::string>
50 OutputFilename("o", cl::desc("Output filename"),
51 cl::value_desc("filename"));
54 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
57 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
60 ShowInstOperands("show-inst-operands",
61 cl::desc("Show instructions operands as parsed"));
63 static cl::opt<unsigned>
64 OutputAsmVariant("output-asm-variant",
65 cl::desc("Syntax variant to use for output printing"));
68 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
71 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
74 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
81 static cl::opt<OutputFileType>
82 FileType("filetype", cl::init(OFT_AssemblyFile),
83 cl::desc("Choose an output file type:"),
85 clEnumValN(OFT_AssemblyFile, "asm",
86 "Emit an assembly ('.s') file"),
87 clEnumValN(OFT_Null, "null",
88 "Don't emit anything (for timing purposes)"),
89 clEnumValN(OFT_ObjectFile, "obj",
90 "Emit a native object ('.o') file"),
93 static cl::list<std::string>
94 IncludeDirs("I", cl::desc("Directory of include files"),
95 cl::value_desc("directory"), cl::Prefix);
97 static cl::opt<std::string>
98 ArchName("arch", cl::desc("Target arch to assemble for, "
99 "see -version for available targets"));
101 static cl::opt<std::string>
102 TripleName("triple", cl::desc("Target triple to assemble for, "
103 "see -version for available targets"));
105 static cl::opt<std::string>
107 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108 cl::value_desc("cpu-name"),
111 static cl::opt<Reloc::Model>
112 RelocModel("relocation-model",
113 cl::desc("Choose relocation model"),
114 cl::init(Reloc::Default),
116 clEnumValN(Reloc::Default, "default",
117 "Target default relocation model"),
118 clEnumValN(Reloc::Static, "static",
119 "Non-relocatable code"),
120 clEnumValN(Reloc::PIC_, "pic",
121 "Fully relocatable, position independent code"),
122 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
123 "Relocatable external references, non-relocatable code"),
126 static cl::opt<llvm::CodeModel::Model>
127 CMModel("code-model",
128 cl::desc("Choose code model"),
129 cl::init(CodeModel::Default),
130 cl::values(clEnumValN(CodeModel::Default, "default",
131 "Target default code model"),
132 clEnumValN(CodeModel::Small, "small",
134 clEnumValN(CodeModel::Kernel, "kernel",
135 "Kernel code model"),
136 clEnumValN(CodeModel::Medium, "medium",
137 "Medium code model"),
138 clEnumValN(CodeModel::Large, "large",
143 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
144 "in the text section"));
147 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
156 static cl::opt<ActionType>
157 Action(cl::desc("Action to perform:"),
158 cl::init(AC_Assemble),
159 cl::values(clEnumValN(AC_AsLex, "as-lex",
160 "Lex tokens from a .s file"),
161 clEnumValN(AC_Assemble, "assemble",
162 "Assemble a .s file (default)"),
163 clEnumValN(AC_Disassemble, "disassemble",
164 "Disassemble strings of hex bytes"),
165 clEnumValN(AC_EDisassemble, "edis",
166 "Enhanced disassembly of strings of hex bytes"),
169 static const Target *GetTarget(const char *ProgName) {
170 // Figure out the target triple.
171 if (TripleName.empty())
172 TripleName = sys::getHostTriple();
173 Triple TheTriple(Triple::normalize(TripleName));
175 const Target *TheTarget = 0;
176 if (!ArchName.empty()) {
177 for (TargetRegistry::iterator it = TargetRegistry::begin(),
178 ie = TargetRegistry::end(); it != ie; ++it) {
179 if (ArchName == it->getName()) {
186 errs() << ProgName << ": error: invalid target '" << ArchName << "'.\n";
190 // Adjust the triple to match (if known), otherwise stick with the
191 // module/host triple.
192 Triple::ArchType Type = Triple::getArchTypeForLLVMName(ArchName);
193 if (Type != Triple::UnknownArch)
194 TheTriple.setArch(Type);
196 // Get the target specific parser.
198 TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Error);
199 if (TheTarget == 0) {
200 errs() << ProgName << ": error: unable to get target for '"
201 << TheTriple.getTriple()
202 << "', see --version and --triple.\n";
207 TripleName = TheTriple.getTriple();
211 static tool_output_file *GetOutputStream() {
212 if (OutputFilename == "")
213 OutputFilename = "-";
216 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
217 raw_fd_ostream::F_Binary);
219 errs() << Err << '\n';
227 static int AsLexInput(const char *ProgName) {
228 OwningPtr<MemoryBuffer> BufferPtr;
229 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
230 errs() << ProgName << ": " << ec.message() << '\n';
233 MemoryBuffer *Buffer = BufferPtr.take();
237 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
238 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
240 // Record the location of the include directories so that the lexer can find
242 SrcMgr.setIncludeDirs(IncludeDirs);
244 const Target *TheTarget = GetTarget(ProgName);
248 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
249 assert(MAI && "Unable to create target asm info!");
251 AsmLexer Lexer(*MAI);
252 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
254 OwningPtr<tool_output_file> Out(GetOutputStream());
259 while (Lexer.Lex().isNot(AsmToken::Eof)) {
260 AsmToken Tok = Lexer.getTok();
262 switch (Tok.getKind()) {
264 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
267 case AsmToken::Error:
268 Error = true; // error already printed.
270 case AsmToken::Identifier:
271 Out->os() << "identifier: " << Lexer.getTok().getString();
273 case AsmToken::Integer:
274 Out->os() << "int: " << Lexer.getTok().getString();
277 Out->os() << "real: " << Lexer.getTok().getString();
279 case AsmToken::Register:
280 Out->os() << "register: " << Lexer.getTok().getRegVal();
282 case AsmToken::String:
283 Out->os() << "string: " << Lexer.getTok().getString();
286 case AsmToken::Amp: Out->os() << "Amp"; break;
287 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
288 case AsmToken::At: Out->os() << "At"; break;
289 case AsmToken::Caret: Out->os() << "Caret"; break;
290 case AsmToken::Colon: Out->os() << "Colon"; break;
291 case AsmToken::Comma: Out->os() << "Comma"; break;
292 case AsmToken::Dollar: Out->os() << "Dollar"; break;
293 case AsmToken::Dot: Out->os() << "Dot"; break;
294 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
295 case AsmToken::Eof: Out->os() << "Eof"; break;
296 case AsmToken::Equal: Out->os() << "Equal"; break;
297 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
298 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
299 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
300 case AsmToken::Greater: Out->os() << "Greater"; break;
301 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
302 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
303 case AsmToken::Hash: Out->os() << "Hash"; break;
304 case AsmToken::LBrac: Out->os() << "LBrac"; break;
305 case AsmToken::LCurly: Out->os() << "LCurly"; break;
306 case AsmToken::LParen: Out->os() << "LParen"; break;
307 case AsmToken::Less: Out->os() << "Less"; break;
308 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
309 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
310 case AsmToken::LessLess: Out->os() << "LessLess"; break;
311 case AsmToken::Minus: Out->os() << "Minus"; break;
312 case AsmToken::Percent: Out->os() << "Percent"; break;
313 case AsmToken::Pipe: Out->os() << "Pipe"; break;
314 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
315 case AsmToken::Plus: Out->os() << "Plus"; break;
316 case AsmToken::RBrac: Out->os() << "RBrac"; break;
317 case AsmToken::RCurly: Out->os() << "RCurly"; break;
318 case AsmToken::RParen: Out->os() << "RParen"; break;
319 case AsmToken::Slash: Out->os() << "Slash"; break;
320 case AsmToken::Star: Out->os() << "Star"; break;
321 case AsmToken::Tilde: Out->os() << "Tilde"; break;
324 // Print the token string.
326 Out->os().write_escaped(Tok.getString());
327 Out->os() << "\")\n";
330 // Keep output if no errors.
331 if (Error == 0) Out->keep();
336 static int AssembleInput(const char *ProgName) {
337 const Target *TheTarget = GetTarget(ProgName);
341 OwningPtr<MemoryBuffer> BufferPtr;
342 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
343 errs() << ProgName << ": " << ec.message() << '\n';
346 MemoryBuffer *Buffer = BufferPtr.take();
350 // Tell SrcMgr about this buffer, which is what the parser will pick up.
351 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
353 // Record the location of the include directories so that the lexer can find
355 SrcMgr.setIncludeDirs(IncludeDirs);
358 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
359 assert(MAI && "Unable to create target asm info!");
361 llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
362 assert(MRI && "Unable to create target register info!");
364 // Package up features to be passed to target/subtarget
365 std::string FeaturesStr;
367 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
368 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
369 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
370 MCContext Ctx(*MAI, *MRI, MOFI.get());
371 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
374 Ctx.setAllowTemporaryLabels(false);
376 OwningPtr<tool_output_file> Out(GetOutputStream());
380 formatted_raw_ostream FOS(Out->os());
381 OwningPtr<MCStreamer> Str;
383 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
384 OwningPtr<MCSubtargetInfo>
385 STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
387 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
388 if (FileType == OFT_AssemblyFile) {
390 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
391 MCCodeEmitter *CE = 0;
392 MCAsmBackend *MAB = 0;
394 CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);
395 MAB = TheTarget->createMCAsmBackend(TripleName);
397 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
399 /*useCFI*/ true, IP, CE, MAB,
401 } else if (FileType == OFT_Null) {
402 Str.reset(createNullStreamer(Ctx));
404 assert(FileType == OFT_ObjectFile && "Invalid file type!");
405 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);
406 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(TripleName);
407 Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
413 Str.reset(createLoggingStreamer(Str.take(), errs()));
416 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
418 OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser));
421 << ": error: this target does not support assembly parsing.\n";
425 Parser->setShowParsedOperands(ShowInstOperands);
426 Parser->setTargetParser(*TAP.get());
428 int Res = Parser->Run(NoInitialTextSection);
430 // Keep output if no errors.
431 if (Res == 0) Out->keep();
436 static int DisassembleInput(const char *ProgName, bool Enhanced) {
437 const Target *TheTarget = GetTarget(ProgName);
441 OwningPtr<MemoryBuffer> Buffer;
442 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
443 errs() << ProgName << ": " << ec.message() << '\n';
447 OwningPtr<tool_output_file> Out(GetOutputStream());
454 Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
456 Res = Disassembler::disassemble(*TheTarget, TripleName,
457 *Buffer.take(), Out->os());
460 // Keep output if no errors.
461 if (Res == 0) Out->keep();
467 int main(int argc, char **argv) {
468 // Print a stack trace if we signal out.
469 sys::PrintStackTraceOnErrorSignal();
470 PrettyStackTraceProgram X(argc, argv);
471 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
473 // Initialize targets and assembly printers/parsers.
474 llvm::InitializeAllTargetInfos();
475 llvm::InitializeAllTargetMCs();
476 llvm::InitializeAllAsmParsers();
477 llvm::InitializeAllDisassemblers();
479 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
480 TripleName = Triple::normalize(TripleName);
485 return AsLexInput(argv[0]);
487 return AssembleInput(argv[0]);
489 return DisassembleInput(argv[0], false);
490 case AC_EDisassemble:
491 return DisassembleInput(argv[0], true);