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/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCCodeEmitter.h"
21 #include "llvm/MC/MCInstPrinter.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/MC/MCObjectFileInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCTargetAsmParser.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/FileUtilities.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/ToolOutputFile.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.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"));
64 static cl::opt<unsigned>
65 OutputAsmVariant("output-asm-variant",
66 cl::desc("Syntax variant to use for output printing"));
69 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
72 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
79 static cl::opt<OutputFileType>
80 FileType("filetype", cl::init(OFT_AssemblyFile),
81 cl::desc("Choose an output file type:"),
83 clEnumValN(OFT_AssemblyFile, "asm",
84 "Emit an assembly ('.s') file"),
85 clEnumValN(OFT_Null, "null",
86 "Don't emit anything (for timing purposes)"),
87 clEnumValN(OFT_ObjectFile, "obj",
88 "Emit a native object ('.o') file"),
91 static cl::list<std::string>
92 IncludeDirs("I", cl::desc("Directory of include files"),
93 cl::value_desc("directory"), cl::Prefix);
95 static cl::opt<std::string>
96 ArchName("arch", cl::desc("Target arch to assemble for, "
97 "see -version for available targets"));
99 static cl::opt<std::string>
100 TripleName("triple", cl::desc("Target triple to assemble for, "
101 "see -version for available targets"));
103 static cl::opt<std::string>
105 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
106 cl::value_desc("cpu-name"),
109 static cl::list<std::string>
112 cl::desc("Target specific attributes (-mattr=help for details)"),
113 cl::value_desc("a1,+a2,-a3,..."));
115 static cl::opt<Reloc::Model>
116 RelocModel("relocation-model",
117 cl::desc("Choose relocation model"),
118 cl::init(Reloc::Default),
120 clEnumValN(Reloc::Default, "default",
121 "Target default relocation model"),
122 clEnumValN(Reloc::Static, "static",
123 "Non-relocatable code"),
124 clEnumValN(Reloc::PIC_, "pic",
125 "Fully relocatable, position independent code"),
126 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
127 "Relocatable external references, non-relocatable code"),
130 static cl::opt<llvm::CodeModel::Model>
131 CMModel("code-model",
132 cl::desc("Choose code model"),
133 cl::init(CodeModel::Default),
134 cl::values(clEnumValN(CodeModel::Default, "default",
135 "Target default code model"),
136 clEnumValN(CodeModel::Small, "small",
138 clEnumValN(CodeModel::Kernel, "kernel",
139 "Kernel code model"),
140 clEnumValN(CodeModel::Medium, "medium",
141 "Medium code model"),
142 clEnumValN(CodeModel::Large, "large",
147 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
148 "in the text section"));
151 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
154 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
164 static cl::opt<ActionType>
165 Action(cl::desc("Action to perform:"),
166 cl::init(AC_Assemble),
167 cl::values(clEnumValN(AC_AsLex, "as-lex",
168 "Lex tokens from a .s file"),
169 clEnumValN(AC_Assemble, "assemble",
170 "Assemble a .s file (default)"),
171 clEnumValN(AC_Disassemble, "disassemble",
172 "Disassemble strings of hex bytes"),
173 clEnumValN(AC_EDisassemble, "edis",
174 "Enhanced disassembly of strings of hex bytes"),
177 static const Target *GetTarget(const char *ProgName) {
178 // Figure out the target triple.
179 if (TripleName.empty())
180 TripleName = sys::getDefaultTargetTriple();
181 Triple TheTriple(Triple::normalize(TripleName));
183 // Get the target specific parser.
185 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
188 errs() << ProgName << ": " << Error;
192 // Update the triple name and return the found target.
193 TripleName = TheTriple.getTriple();
197 static tool_output_file *GetOutputStream() {
198 if (OutputFilename == "")
199 OutputFilename = "-";
202 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
203 raw_fd_ostream::F_Binary);
205 errs() << Err << '\n';
213 static std::string DwarfDebugFlags;
214 static void setDwarfDebugFlags(int argc, char **argv) {
215 if (!getenv("RC_DEBUG_OPTIONS"))
217 for (int i = 0; i < argc; i++) {
218 DwarfDebugFlags += argv[i];
220 DwarfDebugFlags += " ";
224 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, tool_output_file *Out) {
227 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
230 while (Lexer.Lex().isNot(AsmToken::Eof)) {
231 AsmToken Tok = Lexer.getTok();
233 switch (Tok.getKind()) {
235 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
239 case AsmToken::Error:
240 Error = true; // error already printed.
242 case AsmToken::Identifier:
243 Out->os() << "identifier: " << Lexer.getTok().getString();
245 case AsmToken::Integer:
246 Out->os() << "int: " << Lexer.getTok().getString();
249 Out->os() << "real: " << Lexer.getTok().getString();
251 case AsmToken::Register:
252 Out->os() << "register: " << Lexer.getTok().getRegVal();
254 case AsmToken::String:
255 Out->os() << "string: " << Lexer.getTok().getString();
258 case AsmToken::Amp: Out->os() << "Amp"; break;
259 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
260 case AsmToken::At: Out->os() << "At"; break;
261 case AsmToken::Caret: Out->os() << "Caret"; break;
262 case AsmToken::Colon: Out->os() << "Colon"; break;
263 case AsmToken::Comma: Out->os() << "Comma"; break;
264 case AsmToken::Dollar: Out->os() << "Dollar"; break;
265 case AsmToken::Dot: Out->os() << "Dot"; break;
266 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
267 case AsmToken::Eof: Out->os() << "Eof"; break;
268 case AsmToken::Equal: Out->os() << "Equal"; break;
269 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
270 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
271 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
272 case AsmToken::Greater: Out->os() << "Greater"; break;
273 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
274 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
275 case AsmToken::Hash: Out->os() << "Hash"; break;
276 case AsmToken::LBrac: Out->os() << "LBrac"; break;
277 case AsmToken::LCurly: Out->os() << "LCurly"; break;
278 case AsmToken::LParen: Out->os() << "LParen"; break;
279 case AsmToken::Less: Out->os() << "Less"; break;
280 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
281 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
282 case AsmToken::LessLess: Out->os() << "LessLess"; break;
283 case AsmToken::Minus: Out->os() << "Minus"; break;
284 case AsmToken::Percent: Out->os() << "Percent"; break;
285 case AsmToken::Pipe: Out->os() << "Pipe"; break;
286 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
287 case AsmToken::Plus: Out->os() << "Plus"; break;
288 case AsmToken::RBrac: Out->os() << "RBrac"; break;
289 case AsmToken::RCurly: Out->os() << "RCurly"; break;
290 case AsmToken::RParen: Out->os() << "RParen"; break;
291 case AsmToken::Slash: Out->os() << "Slash"; break;
292 case AsmToken::Star: Out->os() << "Star"; break;
293 case AsmToken::Tilde: Out->os() << "Tilde"; break;
296 // Print the token string.
298 Out->os().write_escaped(Tok.getString());
299 Out->os() << "\")\n";
305 static int AssembleInput(const char *ProgName, const Target *TheTarget,
306 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
307 MCAsmInfo &MAI, MCSubtargetInfo &STI) {
308 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
310 OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(STI, *Parser));
313 << ": error: this target does not support assembly parsing.\n";
317 Parser->setShowParsedOperands(ShowInstOperands);
318 Parser->setTargetParser(*TAP.get());
320 int Res = Parser->Run(NoInitialTextSection);
325 int main(int argc, char **argv) {
326 // Print a stack trace if we signal out.
327 sys::PrintStackTraceOnErrorSignal();
328 PrettyStackTraceProgram X(argc, argv);
329 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
331 // Initialize targets and assembly printers/parsers.
332 llvm::InitializeAllTargetInfos();
333 llvm::InitializeAllTargetMCs();
334 llvm::InitializeAllAsmParsers();
335 llvm::InitializeAllDisassemblers();
337 // Register the target printer for --version.
338 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
340 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
341 TripleName = Triple::normalize(TripleName);
342 setDwarfDebugFlags(argc, argv);
344 const char *ProgName = argv[0];
345 const Target *TheTarget = GetTarget(ProgName);
349 OwningPtr<MemoryBuffer> BufferPtr;
350 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
351 errs() << ProgName << ": " << ec.message() << '\n';
354 MemoryBuffer *Buffer = BufferPtr.take();
358 // Tell SrcMgr about this buffer, which is what the parser will pick up.
359 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
361 // Record the location of the include directories so that the lexer can find
363 SrcMgr.setIncludeDirs(IncludeDirs);
366 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
367 assert(MAI && "Unable to create target asm info!");
369 llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
370 assert(MRI && "Unable to create target register info!");
372 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
373 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
374 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
375 MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
376 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
379 Ctx.setAllowTemporaryLabels(false);
381 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
382 if (!DwarfDebugFlags.empty())
383 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
385 // Package up features to be passed to target/subtarget
386 std::string FeaturesStr;
388 SubtargetFeatures Features;
389 for (unsigned i = 0; i != MAttrs.size(); ++i)
390 Features.AddFeature(MAttrs[i]);
391 FeaturesStr = Features.getString();
394 OwningPtr<tool_output_file> Out(GetOutputStream());
398 formatted_raw_ostream FOS(Out->os());
399 OwningPtr<MCStreamer> Str;
401 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
402 OwningPtr<MCSubtargetInfo>
403 STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
405 if (FileType == OFT_AssemblyFile) {
407 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
408 MCCodeEmitter *CE = 0;
409 MCAsmBackend *MAB = 0;
411 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
412 MAB = TheTarget->createMCAsmBackend(TripleName, MCPU);
414 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
417 /*useDwarfDirectory*/ true,
418 IP, CE, MAB, ShowInst));
420 } else if (FileType == OFT_Null) {
421 Str.reset(createNullStreamer(Ctx));
423 assert(FileType == OFT_ObjectFile && "Invalid file type!");
424 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
425 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(TripleName, MCPU);
426 Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
434 Res = AsLexInput(SrcMgr, *MAI, Out.get());
437 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI);
440 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
441 *Buffer, SrcMgr, Out->os());
443 case AC_EDisassemble:
444 Res = Disassembler::disassembleEnhanced(TripleName, *Buffer, SrcMgr, Out->os());
448 // Keep output if no errors.
449 if (Res == 0) Out->keep();