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/MCInstrInfo.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/SubtargetFeature.h"
25 #include "llvm/Target/TargetAsmBackend.h"
26 #include "llvm/Target/TargetAsmParser.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetRegistry.h"
29 #include "llvm/Target/TargetAsmInfo.h" // FIXME.
30 #include "llvm/Target/TargetLowering.h" // FIXME.
31 #include "llvm/Target/TargetLoweringObjectFile.h" // FIXME.
32 #include "llvm/Target/TargetMachine.h" // FIXME.
33 #include "llvm/Target/TargetSelect.h"
34 #include "llvm/ADT/OwningPtr.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/FileUtilities.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/ManagedStatic.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/ToolOutputFile.h"
43 #include "llvm/Support/Host.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/system_error.h"
46 #include "Disassembler.h"
49 static cl::opt<std::string>
50 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
52 static cl::opt<std::string>
53 OutputFilename("o", cl::desc("Output filename"),
54 cl::value_desc("filename"));
57 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
60 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
63 ShowInstOperands("show-inst-operands",
64 cl::desc("Show instructions operands as parsed"));
66 static cl::opt<unsigned>
67 OutputAsmVariant("output-asm-variant",
68 cl::desc("Syntax variant to use for output printing"));
71 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
74 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
77 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
84 static cl::opt<OutputFileType>
85 FileType("filetype", cl::init(OFT_AssemblyFile),
86 cl::desc("Choose an output file type:"),
88 clEnumValN(OFT_AssemblyFile, "asm",
89 "Emit an assembly ('.s') file"),
90 clEnumValN(OFT_Null, "null",
91 "Don't emit anything (for timing purposes)"),
92 clEnumValN(OFT_ObjectFile, "obj",
93 "Emit a native object ('.o') file"),
96 static cl::list<std::string>
97 IncludeDirs("I", cl::desc("Directory of include files"),
98 cl::value_desc("directory"), cl::Prefix);
100 static cl::opt<std::string>
101 ArchName("arch", cl::desc("Target arch to assemble for, "
102 "see -version for available targets"));
104 static cl::opt<std::string>
105 TripleName("triple", cl::desc("Target triple to assemble for, "
106 "see -version for available targets"));
108 static cl::opt<std::string>
110 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
111 cl::value_desc("cpu-name"),
114 static cl::opt<Reloc::Model>
115 RelocModel("relocation-model",
116 cl::desc("Choose relocation model"),
117 cl::init(Reloc::Default),
119 clEnumValN(Reloc::Default, "default",
120 "Target default relocation model"),
121 clEnumValN(Reloc::Static, "static",
122 "Non-relocatable code"),
123 clEnumValN(Reloc::PIC_, "pic",
124 "Fully relocatable, position independent code"),
125 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
126 "Relocatable external references, non-relocatable code"),
130 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
131 "in the text section"));
134 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
143 static cl::opt<ActionType>
144 Action(cl::desc("Action to perform:"),
145 cl::init(AC_Assemble),
146 cl::values(clEnumValN(AC_AsLex, "as-lex",
147 "Lex tokens from a .s file"),
148 clEnumValN(AC_Assemble, "assemble",
149 "Assemble a .s file (default)"),
150 clEnumValN(AC_Disassemble, "disassemble",
151 "Disassemble strings of hex bytes"),
152 clEnumValN(AC_EDisassemble, "edis",
153 "Enhanced disassembly of strings of hex bytes"),
156 static const Target *GetTarget(const char *ProgName) {
157 // Figure out the target triple.
158 if (TripleName.empty())
159 TripleName = sys::getHostTriple();
160 if (!ArchName.empty()) {
161 llvm::Triple TT(TripleName);
162 TT.setArchName(ArchName);
163 TripleName = TT.str();
166 // Get the target specific parser.
168 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
172 errs() << ProgName << ": error: unable to get target for '" << TripleName
173 << "', see --version and --triple.\n";
177 static tool_output_file *GetOutputStream() {
178 if (OutputFilename == "")
179 OutputFilename = "-";
182 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
183 raw_fd_ostream::F_Binary);
185 errs() << Err << '\n';
193 static int AsLexInput(const char *ProgName) {
194 OwningPtr<MemoryBuffer> BufferPtr;
195 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
196 errs() << ProgName << ": " << ec.message() << '\n';
199 MemoryBuffer *Buffer = BufferPtr.take();
203 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
204 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
206 // Record the location of the include directories so that the lexer can find
208 SrcMgr.setIncludeDirs(IncludeDirs);
210 const Target *TheTarget = GetTarget(ProgName);
214 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
215 assert(MAI && "Unable to create target asm info!");
217 AsmLexer Lexer(*MAI);
218 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
220 OwningPtr<tool_output_file> Out(GetOutputStream());
225 while (Lexer.Lex().isNot(AsmToken::Eof)) {
226 AsmToken Tok = Lexer.getTok();
228 switch (Tok.getKind()) {
230 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
233 case AsmToken::Error:
234 Error = true; // error already printed.
236 case AsmToken::Identifier:
237 Out->os() << "identifier: " << Lexer.getTok().getString();
239 case AsmToken::Integer:
240 Out->os() << "int: " << Lexer.getTok().getString();
243 Out->os() << "real: " << Lexer.getTok().getString();
245 case AsmToken::Register:
246 Out->os() << "register: " << Lexer.getTok().getRegVal();
248 case AsmToken::String:
249 Out->os() << "string: " << Lexer.getTok().getString();
252 case AsmToken::Amp: Out->os() << "Amp"; break;
253 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
254 case AsmToken::At: Out->os() << "At"; break;
255 case AsmToken::Caret: Out->os() << "Caret"; break;
256 case AsmToken::Colon: Out->os() << "Colon"; break;
257 case AsmToken::Comma: Out->os() << "Comma"; break;
258 case AsmToken::Dollar: Out->os() << "Dollar"; break;
259 case AsmToken::Dot: Out->os() << "Dot"; break;
260 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
261 case AsmToken::Eof: Out->os() << "Eof"; break;
262 case AsmToken::Equal: Out->os() << "Equal"; break;
263 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
264 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
265 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
266 case AsmToken::Greater: Out->os() << "Greater"; break;
267 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
268 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
269 case AsmToken::Hash: Out->os() << "Hash"; break;
270 case AsmToken::LBrac: Out->os() << "LBrac"; break;
271 case AsmToken::LCurly: Out->os() << "LCurly"; break;
272 case AsmToken::LParen: Out->os() << "LParen"; break;
273 case AsmToken::Less: Out->os() << "Less"; break;
274 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
275 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
276 case AsmToken::LessLess: Out->os() << "LessLess"; break;
277 case AsmToken::Minus: Out->os() << "Minus"; break;
278 case AsmToken::Percent: Out->os() << "Percent"; break;
279 case AsmToken::Pipe: Out->os() << "Pipe"; break;
280 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
281 case AsmToken::Plus: Out->os() << "Plus"; break;
282 case AsmToken::RBrac: Out->os() << "RBrac"; break;
283 case AsmToken::RCurly: Out->os() << "RCurly"; break;
284 case AsmToken::RParen: Out->os() << "RParen"; break;
285 case AsmToken::Slash: Out->os() << "Slash"; break;
286 case AsmToken::Star: Out->os() << "Star"; break;
287 case AsmToken::Tilde: Out->os() << "Tilde"; break;
290 // Print the token string.
292 Out->os().write_escaped(Tok.getString());
293 Out->os() << "\")\n";
296 // Keep output if no errors.
297 if (Error == 0) Out->keep();
302 static int AssembleInput(const char *ProgName) {
303 const Target *TheTarget = GetTarget(ProgName);
307 OwningPtr<MemoryBuffer> BufferPtr;
308 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
309 errs() << ProgName << ": " << ec.message() << '\n';
312 MemoryBuffer *Buffer = BufferPtr.take();
316 // Tell SrcMgr about this buffer, which is what the parser will pick up.
317 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
319 // Record the location of the include directories so that the lexer can find
321 SrcMgr.setIncludeDirs(IncludeDirs);
324 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
325 assert(MAI && "Unable to create target asm info!");
327 llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
328 assert(MRI && "Unable to create target register info!");
330 // Package up features to be passed to target/subtarget
331 std::string FeaturesStr;
333 // FIXME: We shouldn't need to do this (and link in codegen).
334 // When we split this out, we should do it in a way that makes
335 // it straightforward to switch subtargets on the fly (.e.g,
336 // the .cpu and .code16 directives).
337 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
343 errs() << ProgName << ": error: could not create target for triple '"
344 << TripleName << "'.\n";
348 const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
349 MCContext Ctx(*MAI, *MRI, tai);
351 Ctx.setAllowTemporaryLabels(false);
353 OwningPtr<tool_output_file> Out(GetOutputStream());
357 formatted_raw_ostream FOS(Out->os());
358 OwningPtr<MCStreamer> Str;
360 const TargetLoweringObjectFile &TLOF =
361 TM->getTargetLowering()->getObjFileLowering();
362 const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
364 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
365 OwningPtr<MCSubtargetInfo>
366 STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
368 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
369 if (FileType == OFT_AssemblyFile) {
371 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
372 MCCodeEmitter *CE = 0;
373 TargetAsmBackend *TAB = 0;
375 CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
376 TAB = TheTarget->createAsmBackend(TripleName);
378 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
380 /*useCFI*/ true, IP, CE, TAB,
382 } else if (FileType == OFT_Null) {
383 Str.reset(createNullStreamer(Ctx));
385 assert(FileType == OFT_ObjectFile && "Invalid file type!");
386 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
387 TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
388 Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
394 Str.reset(createLoggingStreamer(Str.take(), errs()));
397 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
399 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*STI, *Parser));
402 << ": error: this target does not support assembly parsing.\n";
406 Parser->setShowParsedOperands(ShowInstOperands);
407 Parser->setTargetParser(*TAP.get());
409 int Res = Parser->Run(NoInitialTextSection);
411 // Keep output if no errors.
412 if (Res == 0) Out->keep();
417 static int DisassembleInput(const char *ProgName, bool Enhanced) {
418 const Target *TheTarget = GetTarget(ProgName);
422 OwningPtr<MemoryBuffer> Buffer;
423 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
424 errs() << ProgName << ": " << ec.message() << '\n';
428 OwningPtr<tool_output_file> Out(GetOutputStream());
435 Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
437 Res = Disassembler::disassemble(*TheTarget, TripleName,
438 *Buffer.take(), Out->os());
441 // Keep output if no errors.
442 if (Res == 0) Out->keep();
448 int main(int argc, char **argv) {
449 // Print a stack trace if we signal out.
450 sys::PrintStackTraceOnErrorSignal();
451 PrettyStackTraceProgram X(argc, argv);
452 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
454 // Initialize targets and assembly printers/parsers.
455 llvm::InitializeAllTargetInfos();
456 // FIXME: We shouldn't need to initialize the Target(Machine)s.
457 llvm::InitializeAllTargets();
458 llvm::InitializeAllMCAsmInfos();
459 llvm::InitializeAllMCCodeGenInfos();
460 llvm::InitializeAllMCInstrInfos();
461 llvm::InitializeAllMCRegisterInfos();
462 llvm::InitializeAllMCSubtargetInfos();
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);