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/MCObjectFileInfo.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSectionMachO.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Target/TargetAsmBackend.h"
28 #include "llvm/Target/TargetAsmParser.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetRegistry.h"
31 #include "llvm/Target/TargetAsmInfo.h" // FIXME.
32 #include "llvm/Target/TargetLowering.h" // FIXME.
33 #include "llvm/Target/TargetLoweringObjectFile.h" // FIXME.
34 #include "llvm/Target/TargetMachine.h" // FIXME.
35 #include "llvm/Target/TargetSelect.h"
36 #include "llvm/ADT/OwningPtr.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/FileUtilities.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/PrettyStackTrace.h"
43 #include "llvm/Support/SourceMgr.h"
44 #include "llvm/Support/ToolOutputFile.h"
45 #include "llvm/Support/Host.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/system_error.h"
48 #include "Disassembler.h"
51 static cl::opt<std::string>
52 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
54 static cl::opt<std::string>
55 OutputFilename("o", cl::desc("Output filename"),
56 cl::value_desc("filename"));
59 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
62 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
65 ShowInstOperands("show-inst-operands",
66 cl::desc("Show instructions operands as parsed"));
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"),
116 static cl::opt<Reloc::Model>
117 RelocModel("relocation-model",
118 cl::desc("Choose relocation model"),
119 cl::init(Reloc::Default),
121 clEnumValN(Reloc::Default, "default",
122 "Target default relocation model"),
123 clEnumValN(Reloc::Static, "static",
124 "Non-relocatable code"),
125 clEnumValN(Reloc::PIC_, "pic",
126 "Fully relocatable, position independent code"),
127 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
128 "Relocatable external references, non-relocatable code"),
132 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
133 "in the text section"));
136 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
145 static cl::opt<ActionType>
146 Action(cl::desc("Action to perform:"),
147 cl::init(AC_Assemble),
148 cl::values(clEnumValN(AC_AsLex, "as-lex",
149 "Lex tokens from a .s file"),
150 clEnumValN(AC_Assemble, "assemble",
151 "Assemble a .s file (default)"),
152 clEnumValN(AC_Disassemble, "disassemble",
153 "Disassemble strings of hex bytes"),
154 clEnumValN(AC_EDisassemble, "edis",
155 "Enhanced disassembly of strings of hex bytes"),
158 static const Target *GetTarget(const char *ProgName) {
159 // Figure out the target triple.
160 if (TripleName.empty())
161 TripleName = sys::getHostTriple();
162 if (!ArchName.empty()) {
163 llvm::Triple TT(TripleName);
164 TT.setArchName(ArchName);
165 TripleName = TT.str();
168 // Get the target specific parser.
170 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
174 errs() << ProgName << ": error: unable to get target for '" << TripleName
175 << "', see --version and --triple.\n";
179 static tool_output_file *GetOutputStream() {
180 if (OutputFilename == "")
181 OutputFilename = "-";
184 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
185 raw_fd_ostream::F_Binary);
187 errs() << Err << '\n';
195 static int AsLexInput(const char *ProgName) {
196 OwningPtr<MemoryBuffer> BufferPtr;
197 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
198 errs() << ProgName << ": " << ec.message() << '\n';
201 MemoryBuffer *Buffer = BufferPtr.take();
205 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
206 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
208 // Record the location of the include directories so that the lexer can find
210 SrcMgr.setIncludeDirs(IncludeDirs);
212 const Target *TheTarget = GetTarget(ProgName);
216 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
217 assert(MAI && "Unable to create target asm info!");
219 AsmLexer Lexer(*MAI);
220 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
222 OwningPtr<tool_output_file> Out(GetOutputStream());
227 while (Lexer.Lex().isNot(AsmToken::Eof)) {
228 AsmToken Tok = Lexer.getTok();
230 switch (Tok.getKind()) {
232 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
235 case AsmToken::Error:
236 Error = true; // error already printed.
238 case AsmToken::Identifier:
239 Out->os() << "identifier: " << Lexer.getTok().getString();
241 case AsmToken::Integer:
242 Out->os() << "int: " << Lexer.getTok().getString();
245 Out->os() << "real: " << Lexer.getTok().getString();
247 case AsmToken::Register:
248 Out->os() << "register: " << Lexer.getTok().getRegVal();
250 case AsmToken::String:
251 Out->os() << "string: " << Lexer.getTok().getString();
254 case AsmToken::Amp: Out->os() << "Amp"; break;
255 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
256 case AsmToken::At: Out->os() << "At"; break;
257 case AsmToken::Caret: Out->os() << "Caret"; break;
258 case AsmToken::Colon: Out->os() << "Colon"; break;
259 case AsmToken::Comma: Out->os() << "Comma"; break;
260 case AsmToken::Dollar: Out->os() << "Dollar"; break;
261 case AsmToken::Dot: Out->os() << "Dot"; break;
262 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
263 case AsmToken::Eof: Out->os() << "Eof"; break;
264 case AsmToken::Equal: Out->os() << "Equal"; break;
265 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
266 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
267 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
268 case AsmToken::Greater: Out->os() << "Greater"; break;
269 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
270 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
271 case AsmToken::Hash: Out->os() << "Hash"; break;
272 case AsmToken::LBrac: Out->os() << "LBrac"; break;
273 case AsmToken::LCurly: Out->os() << "LCurly"; break;
274 case AsmToken::LParen: Out->os() << "LParen"; break;
275 case AsmToken::Less: Out->os() << "Less"; break;
276 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
277 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
278 case AsmToken::LessLess: Out->os() << "LessLess"; break;
279 case AsmToken::Minus: Out->os() << "Minus"; break;
280 case AsmToken::Percent: Out->os() << "Percent"; break;
281 case AsmToken::Pipe: Out->os() << "Pipe"; break;
282 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
283 case AsmToken::Plus: Out->os() << "Plus"; break;
284 case AsmToken::RBrac: Out->os() << "RBrac"; break;
285 case AsmToken::RCurly: Out->os() << "RCurly"; break;
286 case AsmToken::RParen: Out->os() << "RParen"; break;
287 case AsmToken::Slash: Out->os() << "Slash"; break;
288 case AsmToken::Star: Out->os() << "Star"; break;
289 case AsmToken::Tilde: Out->os() << "Tilde"; break;
292 // Print the token string.
294 Out->os().write_escaped(Tok.getString());
295 Out->os() << "\")\n";
298 // Keep output if no errors.
299 if (Error == 0) Out->keep();
304 static int AssembleInput(const char *ProgName) {
305 const Target *TheTarget = GetTarget(ProgName);
309 OwningPtr<MemoryBuffer> BufferPtr;
310 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
311 errs() << ProgName << ": " << ec.message() << '\n';
314 MemoryBuffer *Buffer = BufferPtr.take();
318 // Tell SrcMgr about this buffer, which is what the parser will pick up.
319 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
321 // Record the location of the include directories so that the lexer can find
323 SrcMgr.setIncludeDirs(IncludeDirs);
326 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
327 assert(MAI && "Unable to create target asm info!");
329 llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
330 assert(MRI && "Unable to create target register info!");
332 // Package up features to be passed to target/subtarget
333 std::string FeaturesStr;
335 // FIXME: We shouldn't need to do this (and link in codegen).
336 // When we split this out, we should do it in a way that makes
337 // it straightforward to switch subtargets on the fly (.e.g,
338 // the .cpu and .code16 directives).
339 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
345 errs() << ProgName << ": error: could not create target for triple '"
346 << TripleName << "'.\n";
350 const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
351 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
352 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
353 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
354 MCContext Ctx(*MAI, *MRI, MOFI.get(), tai);
355 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, Ctx);
358 Ctx.setAllowTemporaryLabels(false);
360 OwningPtr<tool_output_file> Out(GetOutputStream());
364 formatted_raw_ostream FOS(Out->os());
365 OwningPtr<MCStreamer> Str;
367 const TargetLoweringObjectFile &TLOF =
368 TM->getTargetLowering()->getObjFileLowering();
369 const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
371 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
372 OwningPtr<MCSubtargetInfo>
373 STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
375 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
376 if (FileType == OFT_AssemblyFile) {
378 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
379 MCCodeEmitter *CE = 0;
380 TargetAsmBackend *TAB = 0;
382 CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
383 TAB = TheTarget->createAsmBackend(TripleName);
385 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
387 /*useCFI*/ true, IP, CE, TAB,
389 } else if (FileType == OFT_Null) {
390 Str.reset(createNullStreamer(Ctx));
392 assert(FileType == OFT_ObjectFile && "Invalid file type!");
393 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
394 TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
395 Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
401 Str.reset(createLoggingStreamer(Str.take(), errs()));
404 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
406 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*STI, *Parser));
409 << ": error: this target does not support assembly parsing.\n";
413 Parser->setShowParsedOperands(ShowInstOperands);
414 Parser->setTargetParser(*TAP.get());
416 int Res = Parser->Run(NoInitialTextSection);
418 // Keep output if no errors.
419 if (Res == 0) Out->keep();
424 static int DisassembleInput(const char *ProgName, bool Enhanced) {
425 const Target *TheTarget = GetTarget(ProgName);
429 OwningPtr<MemoryBuffer> Buffer;
430 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
431 errs() << ProgName << ": " << ec.message() << '\n';
435 OwningPtr<tool_output_file> Out(GetOutputStream());
442 Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
444 Res = Disassembler::disassemble(*TheTarget, TripleName,
445 *Buffer.take(), Out->os());
448 // Keep output if no errors.
449 if (Res == 0) Out->keep();
455 int main(int argc, char **argv) {
456 // Print a stack trace if we signal out.
457 sys::PrintStackTraceOnErrorSignal();
458 PrettyStackTraceProgram X(argc, argv);
459 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
461 // Initialize targets and assembly printers/parsers.
462 llvm::InitializeAllTargetInfos();
463 // FIXME: We shouldn't need to initialize the Target(Machine)s.
464 llvm::InitializeAllTargets();
465 llvm::InitializeAllMCAsmInfos();
466 llvm::InitializeAllMCCodeGenInfos();
467 llvm::InitializeAllMCInstrInfos();
468 llvm::InitializeAllMCRegisterInfos();
469 llvm::InitializeAllMCSubtargetInfos();
470 llvm::InitializeAllAsmPrinters();
471 llvm::InitializeAllAsmParsers();
472 llvm::InitializeAllDisassemblers();
474 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
475 TripleName = Triple::normalize(TripleName);
480 return AsLexInput(argv[0]);
482 return AssembleInput(argv[0]);
484 return DisassembleInput(argv[0], false);
485 case AC_EDisassemble:
486 return DisassembleInput(argv[0], true);