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 "Disassembler.h"
16 #include "llvm/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCInstrInfo.h"
21 #include "llvm/MC/MCObjectFileInfo.h"
22 #include "llvm/MC/MCParser/AsmLexer.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/MCTargetOptionsCommandFlags.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Compression.h"
31 #include "llvm/Support/FileUtilities.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
44 static cl::opt<std::string>
45 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
47 static cl::opt<std::string>
48 OutputFilename("o", cl::desc("Output filename"),
49 cl::value_desc("filename"));
52 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
55 CompressDebugSections("compress-debug-sections", cl::desc("Compress DWARF debug sections"));
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"));
73 static cl::opt<OutputFileType>
74 FileType("filetype", cl::init(OFT_AssemblyFile),
75 cl::desc("Choose an output file type:"),
77 clEnumValN(OFT_AssemblyFile, "asm",
78 "Emit an assembly ('.s') file"),
79 clEnumValN(OFT_Null, "null",
80 "Don't emit anything (for timing purposes)"),
81 clEnumValN(OFT_ObjectFile, "obj",
82 "Emit a native object ('.o') file"),
85 static cl::list<std::string>
86 IncludeDirs("I", cl::desc("Directory of include files"),
87 cl::value_desc("directory"), cl::Prefix);
89 static cl::opt<std::string>
90 ArchName("arch", cl::desc("Target arch to assemble for, "
91 "see -version for available targets"));
93 static cl::opt<std::string>
94 TripleName("triple", cl::desc("Target triple to assemble for, "
95 "see -version for available targets"));
97 static cl::opt<std::string>
99 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
100 cl::value_desc("cpu-name"),
103 static cl::list<std::string>
106 cl::desc("Target specific attributes (-mattr=help for details)"),
107 cl::value_desc("a1,+a2,-a3,..."));
109 static cl::opt<Reloc::Model>
110 RelocModel("relocation-model",
111 cl::desc("Choose relocation model"),
112 cl::init(Reloc::Default),
114 clEnumValN(Reloc::Default, "default",
115 "Target default relocation model"),
116 clEnumValN(Reloc::Static, "static",
117 "Non-relocatable code"),
118 clEnumValN(Reloc::PIC_, "pic",
119 "Fully relocatable, position independent code"),
120 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
121 "Relocatable external references, non-relocatable code"),
124 static cl::opt<llvm::CodeModel::Model>
125 CMModel("code-model",
126 cl::desc("Choose code model"),
127 cl::init(CodeModel::Default),
128 cl::values(clEnumValN(CodeModel::Default, "default",
129 "Target default code model"),
130 clEnumValN(CodeModel::Small, "small",
132 clEnumValN(CodeModel::Kernel, "kernel",
133 "Kernel code model"),
134 clEnumValN(CodeModel::Medium, "medium",
135 "Medium code model"),
136 clEnumValN(CodeModel::Large, "large",
141 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
142 "in the text section"));
145 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
149 DwarfVersion("dwarf-version", cl::desc("Dwarf version"), cl::init(4));
151 static cl::opt<std::string>
152 DebugCompilationDir("fdebug-compilation-dir",
153 cl::desc("Specifies the debug info's compilation dir"));
155 static cl::opt<std::string>
156 MainFileName("main-file-name",
157 cl::desc("Specifies the name we should consider the input file"));
159 static cl::opt<bool> SaveTempLabels("save-temp-labels",
160 cl::desc("Don't discard temporary labels"));
170 static cl::opt<ActionType>
171 Action(cl::desc("Action to perform:"),
172 cl::init(AC_Assemble),
173 cl::values(clEnumValN(AC_AsLex, "as-lex",
174 "Lex tokens from a .s file"),
175 clEnumValN(AC_Assemble, "assemble",
176 "Assemble a .s file (default)"),
177 clEnumValN(AC_Disassemble, "disassemble",
178 "Disassemble strings of hex bytes"),
179 clEnumValN(AC_MDisassemble, "mdis",
180 "Marked up disassembly of strings of hex bytes"),
181 clEnumValN(AC_HDisassemble, "hdis",
182 "Disassemble strings of hex bytes printing "
183 "immediates as hex"),
186 static const Target *GetTarget(const char *ProgName) {
187 // Figure out the target triple.
188 if (TripleName.empty())
189 TripleName = sys::getDefaultTargetTriple();
190 Triple TheTriple(Triple::normalize(TripleName));
192 // Get the target specific parser.
194 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
197 errs() << ProgName << ": " << Error;
201 // Update the triple name and return the found target.
202 TripleName = TheTriple.getTriple();
206 static tool_output_file *GetOutputStream() {
207 if (OutputFilename == "")
208 OutputFilename = "-";
211 tool_output_file *Out =
212 new tool_output_file(OutputFilename.c_str(), Err, sys::fs::F_None);
214 errs() << Err << '\n';
222 static std::string DwarfDebugFlags;
223 static void setDwarfDebugFlags(int argc, char **argv) {
224 if (!getenv("RC_DEBUG_OPTIONS"))
226 for (int i = 0; i < argc; i++) {
227 DwarfDebugFlags += argv[i];
229 DwarfDebugFlags += " ";
233 static std::string DwarfDebugProducer;
234 static void setDwarfDebugProducer(void) {
235 if(!getenv("DEBUG_PRODUCER"))
237 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
240 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, tool_output_file *Out) {
243 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
246 while (Lexer.Lex().isNot(AsmToken::Eof)) {
247 AsmToken Tok = Lexer.getTok();
249 switch (Tok.getKind()) {
251 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
255 case AsmToken::Error:
256 Error = true; // error already printed.
258 case AsmToken::Identifier:
259 Out->os() << "identifier: " << Lexer.getTok().getString();
261 case AsmToken::Integer:
262 Out->os() << "int: " << Lexer.getTok().getString();
265 Out->os() << "real: " << Lexer.getTok().getString();
267 case AsmToken::String:
268 Out->os() << "string: " << Lexer.getTok().getString();
271 case AsmToken::Amp: Out->os() << "Amp"; break;
272 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
273 case AsmToken::At: Out->os() << "At"; break;
274 case AsmToken::Caret: Out->os() << "Caret"; break;
275 case AsmToken::Colon: Out->os() << "Colon"; break;
276 case AsmToken::Comma: Out->os() << "Comma"; break;
277 case AsmToken::Dollar: Out->os() << "Dollar"; break;
278 case AsmToken::Dot: Out->os() << "Dot"; break;
279 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
280 case AsmToken::Eof: Out->os() << "Eof"; break;
281 case AsmToken::Equal: Out->os() << "Equal"; break;
282 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
283 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
284 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
285 case AsmToken::Greater: Out->os() << "Greater"; break;
286 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
287 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
288 case AsmToken::Hash: Out->os() << "Hash"; break;
289 case AsmToken::LBrac: Out->os() << "LBrac"; break;
290 case AsmToken::LCurly: Out->os() << "LCurly"; break;
291 case AsmToken::LParen: Out->os() << "LParen"; break;
292 case AsmToken::Less: Out->os() << "Less"; break;
293 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
294 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
295 case AsmToken::LessLess: Out->os() << "LessLess"; break;
296 case AsmToken::Minus: Out->os() << "Minus"; break;
297 case AsmToken::Percent: Out->os() << "Percent"; break;
298 case AsmToken::Pipe: Out->os() << "Pipe"; break;
299 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
300 case AsmToken::Plus: Out->os() << "Plus"; break;
301 case AsmToken::RBrac: Out->os() << "RBrac"; break;
302 case AsmToken::RCurly: Out->os() << "RCurly"; break;
303 case AsmToken::RParen: Out->os() << "RParen"; break;
304 case AsmToken::Slash: Out->os() << "Slash"; break;
305 case AsmToken::Star: Out->os() << "Star"; break;
306 case AsmToken::Tilde: Out->os() << "Tilde"; break;
309 // Print the token string.
311 Out->os().write_escaped(Tok.getString());
312 Out->os() << "\")\n";
318 static int AssembleInput(const char *ProgName, const Target *TheTarget,
319 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
320 MCAsmInfo &MAI, MCSubtargetInfo &STI, MCInstrInfo &MCII) {
321 std::unique_ptr<MCAsmParser> Parser(
322 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
323 std::unique_ptr<MCTargetAsmParser> TAP(
324 TheTarget->createMCAsmParser(STI, *Parser, MCII,
325 InitMCTargetOptionsFromFlags()));
328 << ": error: this target does not support assembly parsing.\n";
332 Parser->setShowParsedOperands(ShowInstOperands);
333 Parser->setTargetParser(*TAP.get());
335 int Res = Parser->Run(NoInitialTextSection);
340 int main(int argc, char **argv) {
341 // Print a stack trace if we signal out.
342 sys::PrintStackTraceOnErrorSignal();
343 PrettyStackTraceProgram X(argc, argv);
344 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
346 // Initialize targets and assembly printers/parsers.
347 llvm::InitializeAllTargetInfos();
348 llvm::InitializeAllTargetMCs();
349 llvm::InitializeAllAsmParsers();
350 llvm::InitializeAllDisassemblers();
352 // Register the target printer for --version.
353 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
355 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
356 TripleName = Triple::normalize(TripleName);
357 setDwarfDebugFlags(argc, argv);
359 setDwarfDebugProducer();
361 const char *ProgName = argv[0];
362 const Target *TheTarget = GetTarget(ProgName);
366 std::unique_ptr<MemoryBuffer> BufferPtr;
367 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
368 errs() << ProgName << ": " << ec.message() << '\n';
371 MemoryBuffer *Buffer = BufferPtr.release();
375 // Tell SrcMgr about this buffer, which is what the parser will pick up.
376 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
378 // Record the location of the include directories so that the lexer can find
380 SrcMgr.setIncludeDirs(IncludeDirs);
382 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
383 assert(MRI && "Unable to create target register info!");
385 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
386 assert(MAI && "Unable to create target asm info!");
388 if (CompressDebugSections) {
389 if (!zlib::isAvailable()) {
390 errs() << ProgName << ": build tools with zlib to enable -compress-debug-sections";
393 MAI->setCompressDebugSections(true);
396 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
397 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
398 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
399 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
400 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
403 Ctx.setAllowTemporaryLabels(false);
405 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
406 if (DwarfVersion < 2 || DwarfVersion > 4) {
407 errs() << ProgName << ": Dwarf version " << DwarfVersion
408 << " is not supported." << '\n';
411 Ctx.setDwarfVersion(DwarfVersion);
412 if (!DwarfDebugFlags.empty())
413 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
414 if (!DwarfDebugProducer.empty())
415 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
416 if (!DebugCompilationDir.empty())
417 Ctx.setCompilationDir(DebugCompilationDir);
418 if (!MainFileName.empty())
419 Ctx.setMainFileName(MainFileName);
421 // Package up features to be passed to target/subtarget
422 std::string FeaturesStr;
424 SubtargetFeatures Features;
425 for (unsigned i = 0; i != MAttrs.size(); ++i)
426 Features.AddFeature(MAttrs[i]);
427 FeaturesStr = Features.getString();
430 std::unique_ptr<tool_output_file> Out(GetOutputStream());
434 formatted_raw_ostream FOS(Out->os());
435 std::unique_ptr<MCStreamer> Str;
437 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
438 std::unique_ptr<MCSubtargetInfo> STI(
439 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
441 MCInstPrinter *IP = nullptr;
442 if (FileType == OFT_AssemblyFile) {
444 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
445 MCCodeEmitter *CE = nullptr;
446 MCAsmBackend *MAB = nullptr;
448 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
449 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
451 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/ true,
452 /*useDwarfDirectory*/ true, IP, CE,
455 } else if (FileType == OFT_Null) {
456 Str.reset(createNullStreamer(Ctx));
458 assert(FileType == OFT_ObjectFile && "Invalid file type!");
459 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
460 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
461 Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
462 FOS, CE, *STI, RelaxAll,
467 bool disassemble = false;
470 Res = AsLexInput(SrcMgr, *MAI, Out.get());
473 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI, *MCII);
475 case AC_MDisassemble:
476 assert(IP && "Expected assembly output");
480 case AC_HDisassemble:
481 assert(IP && "Expected assembly output");
482 IP->setPrintImmHex(1);
490 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
491 *Buffer, SrcMgr, Out->os());
493 // Keep output if no errors.
494 if (Res == 0) Out->keep();