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"),
131 static cl::opt<llvm::CodeModel::Model>
132 CMModel("code-model",
133 cl::desc("Choose code model"),
134 cl::init(CodeModel::Default),
135 cl::values(clEnumValN(CodeModel::Default, "default",
136 "Target default code model"),
137 clEnumValN(CodeModel::Small, "small",
139 clEnumValN(CodeModel::Kernel, "kernel",
140 "Kernel code model"),
141 clEnumValN(CodeModel::Medium, "medium",
142 "Medium code model"),
143 clEnumValN(CodeModel::Large, "large",
148 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
149 "in the text section"));
152 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
161 static cl::opt<ActionType>
162 Action(cl::desc("Action to perform:"),
163 cl::init(AC_Assemble),
164 cl::values(clEnumValN(AC_AsLex, "as-lex",
165 "Lex tokens from a .s file"),
166 clEnumValN(AC_Assemble, "assemble",
167 "Assemble a .s file (default)"),
168 clEnumValN(AC_Disassemble, "disassemble",
169 "Disassemble strings of hex bytes"),
170 clEnumValN(AC_EDisassemble, "edis",
171 "Enhanced disassembly of strings of hex bytes"),
174 static const Target *GetTarget(const char *ProgName) {
175 // Figure out the target triple.
176 if (TripleName.empty())
177 TripleName = sys::getHostTriple();
178 if (!ArchName.empty()) {
179 llvm::Triple TT(TripleName);
180 TT.setArchName(ArchName);
181 TripleName = TT.str();
184 // Get the target specific parser.
186 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
190 errs() << ProgName << ": error: unable to get target for '" << TripleName
191 << "', see --version and --triple.\n";
195 static tool_output_file *GetOutputStream() {
196 if (OutputFilename == "")
197 OutputFilename = "-";
200 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
201 raw_fd_ostream::F_Binary);
203 errs() << Err << '\n';
211 static int AsLexInput(const char *ProgName) {
212 OwningPtr<MemoryBuffer> BufferPtr;
213 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
214 errs() << ProgName << ": " << ec.message() << '\n';
217 MemoryBuffer *Buffer = BufferPtr.take();
221 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
222 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
224 // Record the location of the include directories so that the lexer can find
226 SrcMgr.setIncludeDirs(IncludeDirs);
228 const Target *TheTarget = GetTarget(ProgName);
232 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
233 assert(MAI && "Unable to create target asm info!");
235 AsmLexer Lexer(*MAI);
236 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
238 OwningPtr<tool_output_file> Out(GetOutputStream());
243 while (Lexer.Lex().isNot(AsmToken::Eof)) {
244 AsmToken Tok = Lexer.getTok();
246 switch (Tok.getKind()) {
248 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
251 case AsmToken::Error:
252 Error = true; // error already printed.
254 case AsmToken::Identifier:
255 Out->os() << "identifier: " << Lexer.getTok().getString();
257 case AsmToken::Integer:
258 Out->os() << "int: " << Lexer.getTok().getString();
261 Out->os() << "real: " << Lexer.getTok().getString();
263 case AsmToken::Register:
264 Out->os() << "register: " << Lexer.getTok().getRegVal();
266 case AsmToken::String:
267 Out->os() << "string: " << Lexer.getTok().getString();
270 case AsmToken::Amp: Out->os() << "Amp"; break;
271 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
272 case AsmToken::At: Out->os() << "At"; break;
273 case AsmToken::Caret: Out->os() << "Caret"; break;
274 case AsmToken::Colon: Out->os() << "Colon"; break;
275 case AsmToken::Comma: Out->os() << "Comma"; break;
276 case AsmToken::Dollar: Out->os() << "Dollar"; break;
277 case AsmToken::Dot: Out->os() << "Dot"; break;
278 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
279 case AsmToken::Eof: Out->os() << "Eof"; break;
280 case AsmToken::Equal: Out->os() << "Equal"; break;
281 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
282 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
283 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
284 case AsmToken::Greater: Out->os() << "Greater"; break;
285 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
286 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
287 case AsmToken::Hash: Out->os() << "Hash"; break;
288 case AsmToken::LBrac: Out->os() << "LBrac"; break;
289 case AsmToken::LCurly: Out->os() << "LCurly"; break;
290 case AsmToken::LParen: Out->os() << "LParen"; break;
291 case AsmToken::Less: Out->os() << "Less"; break;
292 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
293 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
294 case AsmToken::LessLess: Out->os() << "LessLess"; break;
295 case AsmToken::Minus: Out->os() << "Minus"; break;
296 case AsmToken::Percent: Out->os() << "Percent"; break;
297 case AsmToken::Pipe: Out->os() << "Pipe"; break;
298 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
299 case AsmToken::Plus: Out->os() << "Plus"; break;
300 case AsmToken::RBrac: Out->os() << "RBrac"; break;
301 case AsmToken::RCurly: Out->os() << "RCurly"; break;
302 case AsmToken::RParen: Out->os() << "RParen"; break;
303 case AsmToken::Slash: Out->os() << "Slash"; break;
304 case AsmToken::Star: Out->os() << "Star"; break;
305 case AsmToken::Tilde: Out->os() << "Tilde"; break;
308 // Print the token string.
310 Out->os().write_escaped(Tok.getString());
311 Out->os() << "\")\n";
314 // Keep output if no errors.
315 if (Error == 0) Out->keep();
320 static int AssembleInput(const char *ProgName) {
321 const Target *TheTarget = GetTarget(ProgName);
325 OwningPtr<MemoryBuffer> BufferPtr;
326 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
327 errs() << ProgName << ": " << ec.message() << '\n';
330 MemoryBuffer *Buffer = BufferPtr.take();
334 // Tell SrcMgr about this buffer, which is what the parser will pick up.
335 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
337 // Record the location of the include directories so that the lexer can find
339 SrcMgr.setIncludeDirs(IncludeDirs);
342 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
343 assert(MAI && "Unable to create target asm info!");
345 llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
346 assert(MRI && "Unable to create target register info!");
348 // Package up features to be passed to target/subtarget
349 std::string FeaturesStr;
351 // FIXME: We shouldn't need to do this (and link in codegen).
352 // When we split this out, we should do it in a way that makes
353 // it straightforward to switch subtargets on the fly (.e.g,
354 // the .cpu and .code16 directives).
355 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
362 errs() << ProgName << ": error: could not create target for triple '"
363 << TripleName << "'.\n";
367 const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
368 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
369 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
370 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
371 MCContext Ctx(*MAI, *MRI, MOFI.get(), tai);
372 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, Ctx);
375 Ctx.setAllowTemporaryLabels(false);
377 OwningPtr<tool_output_file> Out(GetOutputStream());
381 formatted_raw_ostream FOS(Out->os());
382 OwningPtr<MCStreamer> Str;
384 const TargetLoweringObjectFile &TLOF =
385 TM->getTargetLowering()->getObjFileLowering();
386 const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
388 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
389 OwningPtr<MCSubtargetInfo>
390 STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
392 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
393 if (FileType == OFT_AssemblyFile) {
395 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
396 MCCodeEmitter *CE = 0;
397 TargetAsmBackend *TAB = 0;
399 CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
400 TAB = TheTarget->createAsmBackend(TripleName);
402 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
404 /*useCFI*/ true, IP, CE, TAB,
406 } else if (FileType == OFT_Null) {
407 Str.reset(createNullStreamer(Ctx));
409 assert(FileType == OFT_ObjectFile && "Invalid file type!");
410 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
411 TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
412 Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
418 Str.reset(createLoggingStreamer(Str.take(), errs()));
421 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
423 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*STI, *Parser));
426 << ": error: this target does not support assembly parsing.\n";
430 Parser->setShowParsedOperands(ShowInstOperands);
431 Parser->setTargetParser(*TAP.get());
433 int Res = Parser->Run(NoInitialTextSection);
435 // Keep output if no errors.
436 if (Res == 0) Out->keep();
441 static int DisassembleInput(const char *ProgName, bool Enhanced) {
442 const Target *TheTarget = GetTarget(ProgName);
446 OwningPtr<MemoryBuffer> Buffer;
447 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
448 errs() << ProgName << ": " << ec.message() << '\n';
452 OwningPtr<tool_output_file> Out(GetOutputStream());
459 Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
461 Res = Disassembler::disassemble(*TheTarget, TripleName,
462 *Buffer.take(), Out->os());
465 // Keep output if no errors.
466 if (Res == 0) Out->keep();
472 int main(int argc, char **argv) {
473 // Print a stack trace if we signal out.
474 sys::PrintStackTraceOnErrorSignal();
475 PrettyStackTraceProgram X(argc, argv);
476 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
478 // Initialize targets and assembly printers/parsers.
479 llvm::InitializeAllTargetInfos();
480 // FIXME: We shouldn't need to initialize the Target(Machine)s.
481 llvm::InitializeAllTargets();
482 llvm::InitializeAllMCAsmInfos();
483 llvm::InitializeAllMCCodeGenInfos();
484 llvm::InitializeAllMCInstrInfos();
485 llvm::InitializeAllMCRegisterInfos();
486 llvm::InitializeAllMCSubtargetInfos();
487 llvm::InitializeAllAsmPrinters();
488 llvm::InitializeAllAsmParsers();
489 llvm::InitializeAllDisassemblers();
491 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
492 TripleName = Triple::normalize(TripleName);
497 return AsLexInput(argv[0]);
499 return AssembleInput(argv[0]);
501 return DisassembleInput(argv[0], false);
502 case AC_EDisassemble:
503 return DisassembleInput(argv[0], true);