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/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/MCParser/MCTargetAsmParser.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/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"
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));
134 static cl::opt<llvm::CodeModel::Model>
135 CMModel("code-model",
136 cl::desc("Choose code model"),
137 cl::init(CodeModel::Default),
138 cl::values(clEnumValN(CodeModel::Default, "default",
139 "Target default code model"),
140 clEnumValN(CodeModel::Small, "small",
142 clEnumValN(CodeModel::Kernel, "kernel",
143 "Kernel code model"),
144 clEnumValN(CodeModel::Medium, "medium",
145 "Medium code model"),
146 clEnumValN(CodeModel::Large, "large",
147 "Large code model")));
150 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
151 "in the text section"));
154 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
157 static cl::opt<std::string>
158 DebugCompilationDir("fdebug-compilation-dir",
159 cl::desc("Specifies the debug info's compilation dir"));
161 static cl::opt<std::string>
162 MainFileName("main-file-name",
163 cl::desc("Specifies the name we should consider the input file"));
165 static cl::opt<bool> SaveTempLabels("save-temp-labels",
166 cl::desc("Don't discard temporary labels"));
168 static cl::opt<bool> NoExecStack("no-exec-stack",
169 cl::desc("File doesn't need an exec stack"));
178 static cl::opt<ActionType>
179 Action(cl::desc("Action to perform:"),
180 cl::init(AC_Assemble),
181 cl::values(clEnumValN(AC_AsLex, "as-lex",
182 "Lex tokens from a .s file"),
183 clEnumValN(AC_Assemble, "assemble",
184 "Assemble a .s file (default)"),
185 clEnumValN(AC_Disassemble, "disassemble",
186 "Disassemble strings of hex bytes"),
187 clEnumValN(AC_MDisassemble, "mdis",
188 "Marked up disassembly of strings of hex bytes")));
190 static const Target *GetTarget(const char *ProgName) {
191 // Figure out the target triple.
192 if (TripleName.empty())
193 TripleName = sys::getDefaultTargetTriple();
194 Triple TheTriple(Triple::normalize(TripleName));
196 // Get the target specific parser.
198 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
201 errs() << ProgName << ": " << Error;
205 // Update the triple name and return the found target.
206 TripleName = TheTriple.getTriple();
210 static std::unique_ptr<tool_output_file> GetOutputStream() {
211 if (OutputFilename == "")
212 OutputFilename = "-";
215 auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
218 errs() << EC.message() << '\n';
225 static std::string DwarfDebugFlags;
226 static void setDwarfDebugFlags(int argc, char **argv) {
227 if (!getenv("RC_DEBUG_OPTIONS"))
229 for (int i = 0; i < argc; i++) {
230 DwarfDebugFlags += argv[i];
232 DwarfDebugFlags += " ";
236 static std::string DwarfDebugProducer;
237 static void setDwarfDebugProducer() {
238 if(!getenv("DEBUG_PRODUCER"))
240 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
243 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
247 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
250 while (Lexer.Lex().isNot(AsmToken::Eof)) {
251 const AsmToken &Tok = Lexer.getTok();
253 switch (Tok.getKind()) {
255 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
259 case AsmToken::Error:
260 Error = true; // error already printed.
262 case AsmToken::Identifier:
263 OS << "identifier: " << Lexer.getTok().getString();
265 case AsmToken::Integer:
266 OS << "int: " << Lexer.getTok().getString();
269 OS << "real: " << Lexer.getTok().getString();
271 case AsmToken::String:
272 OS << "string: " << Lexer.getTok().getString();
275 case AsmToken::Amp: OS << "Amp"; break;
276 case AsmToken::AmpAmp: OS << "AmpAmp"; break;
277 case AsmToken::At: OS << "At"; break;
278 case AsmToken::Caret: OS << "Caret"; break;
279 case AsmToken::Colon: OS << "Colon"; break;
280 case AsmToken::Comma: OS << "Comma"; break;
281 case AsmToken::Dollar: OS << "Dollar"; break;
282 case AsmToken::Dot: OS << "Dot"; break;
283 case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
284 case AsmToken::Eof: OS << "Eof"; break;
285 case AsmToken::Equal: OS << "Equal"; break;
286 case AsmToken::EqualEqual: OS << "EqualEqual"; break;
287 case AsmToken::Exclaim: OS << "Exclaim"; break;
288 case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break;
289 case AsmToken::Greater: OS << "Greater"; break;
290 case AsmToken::GreaterEqual: OS << "GreaterEqual"; break;
291 case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
292 case AsmToken::Hash: OS << "Hash"; break;
293 case AsmToken::LBrac: OS << "LBrac"; break;
294 case AsmToken::LCurly: OS << "LCurly"; break;
295 case AsmToken::LParen: OS << "LParen"; break;
296 case AsmToken::Less: OS << "Less"; break;
297 case AsmToken::LessEqual: OS << "LessEqual"; break;
298 case AsmToken::LessGreater: OS << "LessGreater"; break;
299 case AsmToken::LessLess: OS << "LessLess"; break;
300 case AsmToken::Minus: OS << "Minus"; break;
301 case AsmToken::Percent: OS << "Percent"; break;
302 case AsmToken::Pipe: OS << "Pipe"; break;
303 case AsmToken::PipePipe: OS << "PipePipe"; break;
304 case AsmToken::Plus: OS << "Plus"; break;
305 case AsmToken::RBrac: OS << "RBrac"; break;
306 case AsmToken::RCurly: OS << "RCurly"; break;
307 case AsmToken::RParen: OS << "RParen"; break;
308 case AsmToken::Slash: OS << "Slash"; break;
309 case AsmToken::Star: OS << "Star"; break;
310 case AsmToken::Tilde: OS << "Tilde"; break;
311 case AsmToken::PercentCall16:
312 OS << "PercentCall16";
314 case AsmToken::PercentCall_Hi:
315 OS << "PercentCall_Hi";
317 case AsmToken::PercentCall_Lo:
318 OS << "PercentCall_Lo";
320 case AsmToken::PercentDtprel_Hi:
321 OS << "PercentDtprel_Hi";
323 case AsmToken::PercentDtprel_Lo:
324 OS << "PercentDtprel_Lo";
326 case AsmToken::PercentGot:
329 case AsmToken::PercentGot_Disp:
330 OS << "PercentGot_Disp";
332 case AsmToken::PercentGot_Hi:
333 OS << "PercentGot_Hi";
335 case AsmToken::PercentGot_Lo:
336 OS << "PercentGot_Lo";
338 case AsmToken::PercentGot_Ofst:
339 OS << "PercentGot_Ofst";
341 case AsmToken::PercentGot_Page:
342 OS << "PercentGot_Page";
344 case AsmToken::PercentGottprel:
345 OS << "PercentGottprel";
347 case AsmToken::PercentGp_Rel:
348 OS << "PercentGp_Rel";
350 case AsmToken::PercentHi:
353 case AsmToken::PercentHigher:
354 OS << "PercentHigher";
356 case AsmToken::PercentHighest:
357 OS << "PercentHighest";
359 case AsmToken::PercentLo:
362 case AsmToken::PercentNeg:
365 case AsmToken::PercentPcrel_Hi:
366 OS << "PercentPcrel_Hi";
368 case AsmToken::PercentPcrel_Lo:
369 OS << "PercentPcrel_Lo";
371 case AsmToken::PercentTlsgd:
372 OS << "PercentTlsgd";
374 case AsmToken::PercentTlsldm:
375 OS << "PercentTlsldm";
377 case AsmToken::PercentTprel_Hi:
378 OS << "PercentTprel_Hi";
380 case AsmToken::PercentTprel_Lo:
381 OS << "PercentTprel_Lo";
385 // Print the token string.
387 OS.write_escaped(Tok.getString());
394 static int fillCommandLineSymbols(MCAsmParser &Parser) {
395 for (auto &I: DefineSymbol) {
396 auto Pair = StringRef(I).split('=');
397 auto Sym = Pair.first;
398 auto Val = Pair.second;
400 if (Sym.empty() || Val.empty()) {
401 errs() << "error: defsym must be of the form: sym=value: " << I << "\n";
405 if (Val.getAsInteger(0, Value)) {
406 errs() << "error: Value is not an integer: " << Val << "\n";
409 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
414 static int AssembleInput(const char *ProgName, const Target *TheTarget,
415 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
416 MCAsmInfo &MAI, MCSubtargetInfo &STI,
417 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
418 std::unique_ptr<MCAsmParser> Parser(
419 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
420 std::unique_ptr<MCTargetAsmParser> TAP(
421 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
425 << ": error: this target does not support assembly parsing.\n";
429 int SymbolResult = fillCommandLineSymbols(*Parser);
432 Parser->setShowParsedOperands(ShowInstOperands);
433 Parser->setTargetParser(*TAP);
435 int Res = Parser->Run(NoInitialTextSection);
440 int main(int argc, char **argv) {
441 // Print a stack trace if we signal out.
442 sys::PrintStackTraceOnErrorSignal(argv[0]);
443 PrettyStackTraceProgram X(argc, argv);
444 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
446 // Initialize targets and assembly printers/parsers.
447 llvm::InitializeAllTargetInfos();
448 llvm::InitializeAllTargetMCs();
449 llvm::InitializeAllAsmParsers();
450 llvm::InitializeAllDisassemblers();
452 // Register the target printer for --version.
453 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
455 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
456 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
457 TripleName = Triple::normalize(TripleName);
458 setDwarfDebugFlags(argc, argv);
460 setDwarfDebugProducer();
462 const char *ProgName = argv[0];
463 const Target *TheTarget = GetTarget(ProgName);
466 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
467 // construct the Triple object.
468 Triple TheTriple(TripleName);
470 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
471 MemoryBuffer::getFileOrSTDIN(InputFilename);
472 if (std::error_code EC = BufferPtr.getError()) {
473 errs() << InputFilename << ": " << EC.message() << '\n';
476 MemoryBuffer *Buffer = BufferPtr->get();
480 // Tell SrcMgr about this buffer, which is what the parser will pick up.
481 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
483 // Record the location of the include directories so that the lexer can find
485 SrcMgr.setIncludeDirs(IncludeDirs);
487 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
488 assert(MRI && "Unable to create target register info!");
490 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
491 assert(MAI && "Unable to create target asm info!");
493 MAI->setRelaxELFRelocations(RelaxELFRel);
495 if (CompressDebugSections != DebugCompressionType::None) {
496 if (!zlib::isAvailable()) {
498 << ": build tools with zlib to enable -compress-debug-sections";
501 MAI->setCompressDebugSections(CompressDebugSections);
503 MAI->setPreserveAsmComments(PreserveComments);
505 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
506 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
507 MCObjectFileInfo MOFI;
508 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
509 MOFI.InitMCObjectFileInfo(TheTriple, PIC, CMModel, Ctx);
512 Ctx.setAllowTemporaryLabels(false);
514 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
515 // Default to 4 for dwarf version.
516 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
517 if (DwarfVersion < 2 || DwarfVersion > 5) {
518 errs() << ProgName << ": Dwarf version " << DwarfVersion
519 << " is not supported." << '\n';
522 Ctx.setDwarfVersion(DwarfVersion);
523 if (!DwarfDebugFlags.empty())
524 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
525 if (!DwarfDebugProducer.empty())
526 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
527 if (!DebugCompilationDir.empty())
528 Ctx.setCompilationDir(DebugCompilationDir);
530 // If no compilation dir is set, try to use the current directory.
531 SmallString<128> CWD;
532 if (!sys::fs::current_path(CWD))
533 Ctx.setCompilationDir(CWD);
535 if (!MainFileName.empty())
536 Ctx.setMainFileName(MainFileName);
538 // Package up features to be passed to target/subtarget
539 std::string FeaturesStr;
541 SubtargetFeatures Features;
542 for (unsigned i = 0; i != MAttrs.size(); ++i)
543 Features.AddFeature(MAttrs[i]);
544 FeaturesStr = Features.getString();
547 std::unique_ptr<tool_output_file> Out = GetOutputStream();
551 std::unique_ptr<buffer_ostream> BOS;
552 raw_pwrite_stream *OS = &Out->os();
553 std::unique_ptr<MCStreamer> Str;
555 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
556 std::unique_ptr<MCSubtargetInfo> STI(
557 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
559 MCInstPrinter *IP = nullptr;
560 if (FileType == OFT_AssemblyFile) {
561 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
566 << "error: unable to create instruction printer for target triple '"
567 << TheTriple.normalize() << "' with assembly variant "
568 << OutputAsmVariant << ".\n";
572 // Set the display preference for hex vs. decimal immediates.
573 IP->setPrintImmHex(PrintImmHex);
575 // Set up the AsmStreamer.
576 MCCodeEmitter *CE = nullptr;
577 MCAsmBackend *MAB = nullptr;
579 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
580 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU, MCOptions);
582 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
583 Str.reset(TheTarget->createAsmStreamer(
584 Ctx, std::move(FOut), /*asmverbose*/ true,
585 /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
587 } else if (FileType == OFT_Null) {
588 Str.reset(TheTarget->createNullStreamer(Ctx));
590 assert(FileType == OFT_ObjectFile && "Invalid file type!");
592 // Don't waste memory on names of temp labels.
593 Ctx.setUseNamesOnTempLabels(false);
595 if (!Out->os().supportsSeeking()) {
596 BOS = make_unique<buffer_ostream>(Out->os());
600 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
601 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU,
603 Str.reset(TheTarget->createMCObjectStreamer(
604 TheTriple, Ctx, *MAB, *OS, CE, *STI, MCOptions.MCRelaxAll,
605 MCOptions.MCIncrementalLinkerCompatible,
606 /*DWARFMustBeAtTheEnd*/ false));
608 Str->InitSections(true);
612 bool disassemble = false;
615 Res = AsLexInput(SrcMgr, *MAI, Out->os());
618 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
621 case AC_MDisassemble:
622 assert(IP && "Expected assembly output");
631 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
632 *Buffer, SrcMgr, Out->os());
634 // Keep output if no errors.
635 if (Res == 0) Out->keep();