1 //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
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/MCCodeEmitter.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCInstPrinter.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
25 #include "llvm/MC/MCRegisterInfo.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCTargetOptionsCommandFlags.def"
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"
45 static cl::opt<std::string>
46 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
48 static cl::opt<std::string>
49 OutputFilename("o", cl::desc("Output filename"),
50 cl::value_desc("filename"));
53 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
55 static cl::opt<bool> RelaxELFRel(
56 "relax-relocations", cl::init(true),
57 cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
59 static cl::opt<DebugCompressionType> CompressDebugSections(
60 "compress-debug-sections", cl::ValueOptional,
61 cl::init(DebugCompressionType::None),
62 cl::desc("Choose DWARF debug sections compression:"),
63 cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
64 clEnumValN(DebugCompressionType::Z, "zlib",
65 "Use zlib compression"),
66 clEnumValN(DebugCompressionType::GNU, "zlib-gnu",
67 "Use zlib-gnu compression (deprecated)")));
70 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
73 ShowInstOperands("show-inst-operands",
74 cl::desc("Show instructions operands as parsed"));
76 static cl::opt<unsigned>
77 OutputAsmVariant("output-asm-variant",
78 cl::desc("Syntax variant to use for output printing"));
81 PrintImmHex("print-imm-hex", cl::init(false),
82 cl::desc("Prefer hex format for immediate values"));
84 static cl::list<std::string>
85 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
88 PreserveComments("preserve-comments",
89 cl::desc("Preserve Comments in outputted assembly"));
96 static cl::opt<OutputFileType>
97 FileType("filetype", cl::init(OFT_AssemblyFile),
98 cl::desc("Choose an output file type:"),
100 clEnumValN(OFT_AssemblyFile, "asm",
101 "Emit an assembly ('.s') file"),
102 clEnumValN(OFT_Null, "null",
103 "Don't emit anything (for timing purposes)"),
104 clEnumValN(OFT_ObjectFile, "obj",
105 "Emit a native object ('.o') file")));
107 static cl::list<std::string>
108 IncludeDirs("I", cl::desc("Directory of include files"),
109 cl::value_desc("directory"), cl::Prefix);
111 static cl::opt<std::string>
112 ArchName("arch", cl::desc("Target arch to assemble for, "
113 "see -version for available targets"));
115 static cl::opt<std::string>
116 TripleName("triple", cl::desc("Target triple to assemble for, "
117 "see -version for available targets"));
119 static cl::opt<std::string>
121 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
122 cl::value_desc("cpu-name"),
125 static cl::list<std::string>
128 cl::desc("Target specific attributes (-mattr=help for details)"),
129 cl::value_desc("a1,+a2,-a3,..."));
131 static cl::opt<bool> PIC("position-independent",
132 cl::desc("Position independent"), cl::init(false));
135 LargeCodeModel("large-code-model",
136 cl::desc("Create cfi directives that assume the code might "
137 "be more than 2gb away"));
140 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
141 "in the text section"));
144 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
147 static cl::opt<std::string>
148 DebugCompilationDir("fdebug-compilation-dir",
149 cl::desc("Specifies the debug info's compilation dir"));
151 static cl::opt<std::string>
152 MainFileName("main-file-name",
153 cl::desc("Specifies the name we should consider the input file"));
155 static cl::opt<bool> SaveTempLabels("save-temp-labels",
156 cl::desc("Don't discard temporary labels"));
158 static cl::opt<bool> NoExecStack("no-exec-stack",
159 cl::desc("File doesn't need an exec stack"));
168 static cl::opt<ActionType>
169 Action(cl::desc("Action to perform:"),
170 cl::init(AC_Assemble),
171 cl::values(clEnumValN(AC_AsLex, "as-lex",
172 "Lex tokens from a .s file"),
173 clEnumValN(AC_Assemble, "assemble",
174 "Assemble a .s file (default)"),
175 clEnumValN(AC_Disassemble, "disassemble",
176 "Disassemble strings of hex bytes"),
177 clEnumValN(AC_MDisassemble, "mdis",
178 "Marked up disassembly of strings of hex bytes")));
180 static const Target *GetTarget(const char *ProgName) {
181 // Figure out the target triple.
182 if (TripleName.empty())
183 TripleName = sys::getDefaultTargetTriple();
184 Triple TheTriple(Triple::normalize(TripleName));
186 // Get the target specific parser.
188 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
191 errs() << ProgName << ": " << Error;
195 // Update the triple name and return the found target.
196 TripleName = TheTriple.getTriple();
200 static std::unique_ptr<ToolOutputFile> GetOutputStream() {
201 if (OutputFilename == "")
202 OutputFilename = "-";
206 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
208 errs() << EC.message() << '\n';
215 static std::string DwarfDebugFlags;
216 static void setDwarfDebugFlags(int argc, char **argv) {
217 if (!getenv("RC_DEBUG_OPTIONS"))
219 for (int i = 0; i < argc; i++) {
220 DwarfDebugFlags += argv[i];
222 DwarfDebugFlags += " ";
226 static std::string DwarfDebugProducer;
227 static void setDwarfDebugProducer() {
228 if(!getenv("DEBUG_PRODUCER"))
230 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
233 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
237 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
240 while (Lexer.Lex().isNot(AsmToken::Eof)) {
241 const AsmToken &Tok = Lexer.getTok();
243 switch (Tok.getKind()) {
245 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
249 case AsmToken::Error:
250 Error = true; // error already printed.
252 case AsmToken::Identifier:
253 OS << "identifier: " << Lexer.getTok().getString();
255 case AsmToken::Integer:
256 OS << "int: " << Lexer.getTok().getString();
259 OS << "real: " << Lexer.getTok().getString();
261 case AsmToken::String:
262 OS << "string: " << Lexer.getTok().getString();
265 case AsmToken::Amp: OS << "Amp"; break;
266 case AsmToken::AmpAmp: OS << "AmpAmp"; break;
267 case AsmToken::At: OS << "At"; break;
268 case AsmToken::Caret: OS << "Caret"; break;
269 case AsmToken::Colon: OS << "Colon"; break;
270 case AsmToken::Comma: OS << "Comma"; break;
271 case AsmToken::Dollar: OS << "Dollar"; break;
272 case AsmToken::Dot: OS << "Dot"; break;
273 case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
274 case AsmToken::Eof: OS << "Eof"; break;
275 case AsmToken::Equal: OS << "Equal"; break;
276 case AsmToken::EqualEqual: OS << "EqualEqual"; break;
277 case AsmToken::Exclaim: OS << "Exclaim"; break;
278 case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break;
279 case AsmToken::Greater: OS << "Greater"; break;
280 case AsmToken::GreaterEqual: OS << "GreaterEqual"; break;
281 case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
282 case AsmToken::Hash: OS << "Hash"; break;
283 case AsmToken::LBrac: OS << "LBrac"; break;
284 case AsmToken::LCurly: OS << "LCurly"; break;
285 case AsmToken::LParen: OS << "LParen"; break;
286 case AsmToken::Less: OS << "Less"; break;
287 case AsmToken::LessEqual: OS << "LessEqual"; break;
288 case AsmToken::LessGreater: OS << "LessGreater"; break;
289 case AsmToken::LessLess: OS << "LessLess"; break;
290 case AsmToken::Minus: OS << "Minus"; break;
291 case AsmToken::Percent: OS << "Percent"; break;
292 case AsmToken::Pipe: OS << "Pipe"; break;
293 case AsmToken::PipePipe: OS << "PipePipe"; break;
294 case AsmToken::Plus: OS << "Plus"; break;
295 case AsmToken::RBrac: OS << "RBrac"; break;
296 case AsmToken::RCurly: OS << "RCurly"; break;
297 case AsmToken::RParen: OS << "RParen"; break;
298 case AsmToken::Slash: OS << "Slash"; break;
299 case AsmToken::Star: OS << "Star"; break;
300 case AsmToken::Tilde: OS << "Tilde"; break;
301 case AsmToken::PercentCall16:
302 OS << "PercentCall16";
304 case AsmToken::PercentCall_Hi:
305 OS << "PercentCall_Hi";
307 case AsmToken::PercentCall_Lo:
308 OS << "PercentCall_Lo";
310 case AsmToken::PercentDtprel_Hi:
311 OS << "PercentDtprel_Hi";
313 case AsmToken::PercentDtprel_Lo:
314 OS << "PercentDtprel_Lo";
316 case AsmToken::PercentGot:
319 case AsmToken::PercentGot_Disp:
320 OS << "PercentGot_Disp";
322 case AsmToken::PercentGot_Hi:
323 OS << "PercentGot_Hi";
325 case AsmToken::PercentGot_Lo:
326 OS << "PercentGot_Lo";
328 case AsmToken::PercentGot_Ofst:
329 OS << "PercentGot_Ofst";
331 case AsmToken::PercentGot_Page:
332 OS << "PercentGot_Page";
334 case AsmToken::PercentGottprel:
335 OS << "PercentGottprel";
337 case AsmToken::PercentGp_Rel:
338 OS << "PercentGp_Rel";
340 case AsmToken::PercentHi:
343 case AsmToken::PercentHigher:
344 OS << "PercentHigher";
346 case AsmToken::PercentHighest:
347 OS << "PercentHighest";
349 case AsmToken::PercentLo:
352 case AsmToken::PercentNeg:
355 case AsmToken::PercentPcrel_Hi:
356 OS << "PercentPcrel_Hi";
358 case AsmToken::PercentPcrel_Lo:
359 OS << "PercentPcrel_Lo";
361 case AsmToken::PercentTlsgd:
362 OS << "PercentTlsgd";
364 case AsmToken::PercentTlsldm:
365 OS << "PercentTlsldm";
367 case AsmToken::PercentTprel_Hi:
368 OS << "PercentTprel_Hi";
370 case AsmToken::PercentTprel_Lo:
371 OS << "PercentTprel_Lo";
375 // Print the token string.
377 OS.write_escaped(Tok.getString());
384 static int fillCommandLineSymbols(MCAsmParser &Parser) {
385 for (auto &I: DefineSymbol) {
386 auto Pair = StringRef(I).split('=');
387 auto Sym = Pair.first;
388 auto Val = Pair.second;
390 if (Sym.empty() || Val.empty()) {
391 errs() << "error: defsym must be of the form: sym=value: " << I << "\n";
395 if (Val.getAsInteger(0, Value)) {
396 errs() << "error: Value is not an integer: " << Val << "\n";
399 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
404 static int AssembleInput(const char *ProgName, const Target *TheTarget,
405 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
406 MCAsmInfo &MAI, MCSubtargetInfo &STI,
407 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
408 std::unique_ptr<MCAsmParser> Parser(
409 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
410 std::unique_ptr<MCTargetAsmParser> TAP(
411 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
415 << ": error: this target does not support assembly parsing.\n";
419 int SymbolResult = fillCommandLineSymbols(*Parser);
422 Parser->setShowParsedOperands(ShowInstOperands);
423 Parser->setTargetParser(*TAP);
425 int Res = Parser->Run(NoInitialTextSection);
430 int main(int argc, char **argv) {
431 // Print a stack trace if we signal out.
432 sys::PrintStackTraceOnErrorSignal(argv[0]);
433 PrettyStackTraceProgram X(argc, argv);
434 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
436 // Initialize targets and assembly printers/parsers.
437 llvm::InitializeAllTargetInfos();
438 llvm::InitializeAllTargetMCs();
439 llvm::InitializeAllAsmParsers();
440 llvm::InitializeAllDisassemblers();
442 // Register the target printer for --version.
443 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
445 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
446 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
447 TripleName = Triple::normalize(TripleName);
448 setDwarfDebugFlags(argc, argv);
450 setDwarfDebugProducer();
452 const char *ProgName = argv[0];
453 const Target *TheTarget = GetTarget(ProgName);
456 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
457 // construct the Triple object.
458 Triple TheTriple(TripleName);
460 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
461 MemoryBuffer::getFileOrSTDIN(InputFilename);
462 if (std::error_code EC = BufferPtr.getError()) {
463 errs() << InputFilename << ": " << EC.message() << '\n';
466 MemoryBuffer *Buffer = BufferPtr->get();
470 // Tell SrcMgr about this buffer, which is what the parser will pick up.
471 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
473 // Record the location of the include directories so that the lexer can find
475 SrcMgr.setIncludeDirs(IncludeDirs);
477 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
478 assert(MRI && "Unable to create target register info!");
480 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
481 assert(MAI && "Unable to create target asm info!");
483 MAI->setRelaxELFRelocations(RelaxELFRel);
485 if (CompressDebugSections != DebugCompressionType::None) {
486 if (!zlib::isAvailable()) {
488 << ": build tools with zlib to enable -compress-debug-sections";
491 MAI->setCompressDebugSections(CompressDebugSections);
493 MAI->setPreserveAsmComments(PreserveComments);
495 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
496 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
497 MCObjectFileInfo MOFI;
498 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
499 MOFI.InitMCObjectFileInfo(TheTriple, PIC, Ctx, LargeCodeModel);
502 Ctx.setAllowTemporaryLabels(false);
504 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
505 // Default to 4 for dwarf version.
506 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
507 if (DwarfVersion < 2 || DwarfVersion > 5) {
508 errs() << ProgName << ": Dwarf version " << DwarfVersion
509 << " is not supported." << '\n';
512 Ctx.setDwarfVersion(DwarfVersion);
513 if (!DwarfDebugFlags.empty())
514 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
515 if (!DwarfDebugProducer.empty())
516 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
517 if (!DebugCompilationDir.empty())
518 Ctx.setCompilationDir(DebugCompilationDir);
520 // If no compilation dir is set, try to use the current directory.
521 SmallString<128> CWD;
522 if (!sys::fs::current_path(CWD))
523 Ctx.setCompilationDir(CWD);
525 if (!MainFileName.empty())
526 Ctx.setMainFileName(MainFileName);
528 // Package up features to be passed to target/subtarget
529 std::string FeaturesStr;
531 SubtargetFeatures Features;
532 for (unsigned i = 0; i != MAttrs.size(); ++i)
533 Features.AddFeature(MAttrs[i]);
534 FeaturesStr = Features.getString();
537 std::unique_ptr<ToolOutputFile> Out = GetOutputStream();
541 std::unique_ptr<buffer_ostream> BOS;
542 raw_pwrite_stream *OS = &Out->os();
543 std::unique_ptr<MCStreamer> Str;
545 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
546 std::unique_ptr<MCSubtargetInfo> STI(
547 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
549 MCInstPrinter *IP = nullptr;
550 if (FileType == OFT_AssemblyFile) {
551 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
556 << "error: unable to create instruction printer for target triple '"
557 << TheTriple.normalize() << "' with assembly variant "
558 << OutputAsmVariant << ".\n";
562 // Set the display preference for hex vs. decimal immediates.
563 IP->setPrintImmHex(PrintImmHex);
565 // Set up the AsmStreamer.
566 MCCodeEmitter *CE = nullptr;
567 MCAsmBackend *MAB = nullptr;
569 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
570 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU, MCOptions);
572 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
573 Str.reset(TheTarget->createAsmStreamer(
574 Ctx, std::move(FOut), /*asmverbose*/ true,
575 /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
577 } else if (FileType == OFT_Null) {
578 Str.reset(TheTarget->createNullStreamer(Ctx));
580 assert(FileType == OFT_ObjectFile && "Invalid file type!");
582 // Don't waste memory on names of temp labels.
583 Ctx.setUseNamesOnTempLabels(false);
585 if (!Out->os().supportsSeeking()) {
586 BOS = make_unique<buffer_ostream>(Out->os());
590 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
591 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU,
593 Str.reset(TheTarget->createMCObjectStreamer(
594 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB), *OS,
595 std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
596 MCOptions.MCIncrementalLinkerCompatible,
597 /*DWARFMustBeAtTheEnd*/ false));
599 Str->InitSections(true);
603 bool disassemble = false;
606 Res = AsLexInput(SrcMgr, *MAI, Out->os());
609 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
612 case AC_MDisassemble:
613 assert(IP && "Expected assembly output");
622 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
623 *Buffer, SrcMgr, Out->os());
625 // Keep output if no errors.
626 if (Res == 0) Out->keep();