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>
60 CompressDebugSections("compress-debug-sections", cl::ValueOptional,
61 cl::init(DebugCompressionType::DCT_None),
62 cl::desc("Choose DWARF debug sections compression:"),
64 clEnumValN(DebugCompressionType::DCT_None, "none",
66 clEnumValN(DebugCompressionType::DCT_Zlib, "zlib",
67 "Use zlib compression"),
68 clEnumValN(DebugCompressionType::DCT_ZlibGnu, "zlib-gnu",
69 "Use zlib-gnu compression (deprecated)")));
72 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
75 ShowInstOperands("show-inst-operands",
76 cl::desc("Show instructions operands as parsed"));
78 static cl::opt<unsigned>
79 OutputAsmVariant("output-asm-variant",
80 cl::desc("Syntax variant to use for output printing"));
83 PrintImmHex("print-imm-hex", cl::init(false),
84 cl::desc("Prefer hex format for immediate values"));
86 static cl::list<std::string>
87 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
90 PreserveComments("preserve-comments",
91 cl::desc("Preserve Comments in outputted assembly"));
98 static cl::opt<OutputFileType>
99 FileType("filetype", cl::init(OFT_AssemblyFile),
100 cl::desc("Choose an output file type:"),
102 clEnumValN(OFT_AssemblyFile, "asm",
103 "Emit an assembly ('.s') file"),
104 clEnumValN(OFT_Null, "null",
105 "Don't emit anything (for timing purposes)"),
106 clEnumValN(OFT_ObjectFile, "obj",
107 "Emit a native object ('.o') file")));
109 static cl::list<std::string>
110 IncludeDirs("I", cl::desc("Directory of include files"),
111 cl::value_desc("directory"), cl::Prefix);
113 static cl::opt<std::string>
114 ArchName("arch", cl::desc("Target arch to assemble for, "
115 "see -version for available targets"));
117 static cl::opt<std::string>
118 TripleName("triple", cl::desc("Target triple to assemble for, "
119 "see -version for available targets"));
121 static cl::opt<std::string>
123 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
124 cl::value_desc("cpu-name"),
127 static cl::list<std::string>
130 cl::desc("Target specific attributes (-mattr=help for details)"),
131 cl::value_desc("a1,+a2,-a3,..."));
133 static cl::opt<bool> PIC("position-independent",
134 cl::desc("Position independent"), cl::init(false));
136 static cl::opt<llvm::CodeModel::Model>
137 CMModel("code-model",
138 cl::desc("Choose code model"),
139 cl::init(CodeModel::Default),
140 cl::values(clEnumValN(CodeModel::Default, "default",
141 "Target default code model"),
142 clEnumValN(CodeModel::Small, "small",
144 clEnumValN(CodeModel::Kernel, "kernel",
145 "Kernel code model"),
146 clEnumValN(CodeModel::Medium, "medium",
147 "Medium code model"),
148 clEnumValN(CodeModel::Large, "large",
149 "Large code model")));
152 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
153 "in the text section"));
156 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
159 static cl::opt<std::string>
160 DebugCompilationDir("fdebug-compilation-dir",
161 cl::desc("Specifies the debug info's compilation dir"));
163 static cl::opt<std::string>
164 MainFileName("main-file-name",
165 cl::desc("Specifies the name we should consider the input file"));
167 static cl::opt<bool> SaveTempLabels("save-temp-labels",
168 cl::desc("Don't discard temporary labels"));
170 static cl::opt<bool> NoExecStack("no-exec-stack",
171 cl::desc("File doesn't need an exec stack"));
180 static cl::opt<ActionType>
181 Action(cl::desc("Action to perform:"),
182 cl::init(AC_Assemble),
183 cl::values(clEnumValN(AC_AsLex, "as-lex",
184 "Lex tokens from a .s file"),
185 clEnumValN(AC_Assemble, "assemble",
186 "Assemble a .s file (default)"),
187 clEnumValN(AC_Disassemble, "disassemble",
188 "Disassemble strings of hex bytes"),
189 clEnumValN(AC_MDisassemble, "mdis",
190 "Marked up disassembly of strings of hex bytes")));
192 static const Target *GetTarget(const char *ProgName) {
193 // Figure out the target triple.
194 if (TripleName.empty())
195 TripleName = sys::getDefaultTargetTriple();
196 Triple TheTriple(Triple::normalize(TripleName));
198 // Get the target specific parser.
200 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
203 errs() << ProgName << ": " << Error;
207 // Update the triple name and return the found target.
208 TripleName = TheTriple.getTriple();
212 static std::unique_ptr<tool_output_file> GetOutputStream() {
213 if (OutputFilename == "")
214 OutputFilename = "-";
217 auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
220 errs() << EC.message() << '\n';
227 static std::string DwarfDebugFlags;
228 static void setDwarfDebugFlags(int argc, char **argv) {
229 if (!getenv("RC_DEBUG_OPTIONS"))
231 for (int i = 0; i < argc; i++) {
232 DwarfDebugFlags += argv[i];
234 DwarfDebugFlags += " ";
238 static std::string DwarfDebugProducer;
239 static void setDwarfDebugProducer() {
240 if(!getenv("DEBUG_PRODUCER"))
242 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
245 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
249 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
252 while (Lexer.Lex().isNot(AsmToken::Eof)) {
253 const AsmToken &Tok = Lexer.getTok();
255 switch (Tok.getKind()) {
257 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
261 case AsmToken::Error:
262 Error = true; // error already printed.
264 case AsmToken::Identifier:
265 OS << "identifier: " << Lexer.getTok().getString();
267 case AsmToken::Integer:
268 OS << "int: " << Lexer.getTok().getString();
271 OS << "real: " << Lexer.getTok().getString();
273 case AsmToken::String:
274 OS << "string: " << Lexer.getTok().getString();
277 case AsmToken::Amp: OS << "Amp"; break;
278 case AsmToken::AmpAmp: OS << "AmpAmp"; break;
279 case AsmToken::At: OS << "At"; break;
280 case AsmToken::Caret: OS << "Caret"; break;
281 case AsmToken::Colon: OS << "Colon"; break;
282 case AsmToken::Comma: OS << "Comma"; break;
283 case AsmToken::Dollar: OS << "Dollar"; break;
284 case AsmToken::Dot: OS << "Dot"; break;
285 case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
286 case AsmToken::Eof: OS << "Eof"; break;
287 case AsmToken::Equal: OS << "Equal"; break;
288 case AsmToken::EqualEqual: OS << "EqualEqual"; break;
289 case AsmToken::Exclaim: OS << "Exclaim"; break;
290 case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break;
291 case AsmToken::Greater: OS << "Greater"; break;
292 case AsmToken::GreaterEqual: OS << "GreaterEqual"; break;
293 case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
294 case AsmToken::Hash: OS << "Hash"; break;
295 case AsmToken::LBrac: OS << "LBrac"; break;
296 case AsmToken::LCurly: OS << "LCurly"; break;
297 case AsmToken::LParen: OS << "LParen"; break;
298 case AsmToken::Less: OS << "Less"; break;
299 case AsmToken::LessEqual: OS << "LessEqual"; break;
300 case AsmToken::LessGreater: OS << "LessGreater"; break;
301 case AsmToken::LessLess: OS << "LessLess"; break;
302 case AsmToken::Minus: OS << "Minus"; break;
303 case AsmToken::Percent: OS << "Percent"; break;
304 case AsmToken::Pipe: OS << "Pipe"; break;
305 case AsmToken::PipePipe: OS << "PipePipe"; break;
306 case AsmToken::Plus: OS << "Plus"; break;
307 case AsmToken::RBrac: OS << "RBrac"; break;
308 case AsmToken::RCurly: OS << "RCurly"; break;
309 case AsmToken::RParen: OS << "RParen"; break;
310 case AsmToken::Slash: OS << "Slash"; break;
311 case AsmToken::Star: OS << "Star"; break;
312 case AsmToken::Tilde: OS << "Tilde"; break;
313 case AsmToken::PercentCall16:
314 OS << "PercentCall16";
316 case AsmToken::PercentCall_Hi:
317 OS << "PercentCall_Hi";
319 case AsmToken::PercentCall_Lo:
320 OS << "PercentCall_Lo";
322 case AsmToken::PercentDtprel_Hi:
323 OS << "PercentDtprel_Hi";
325 case AsmToken::PercentDtprel_Lo:
326 OS << "PercentDtprel_Lo";
328 case AsmToken::PercentGot:
331 case AsmToken::PercentGot_Disp:
332 OS << "PercentGot_Disp";
334 case AsmToken::PercentGot_Hi:
335 OS << "PercentGot_Hi";
337 case AsmToken::PercentGot_Lo:
338 OS << "PercentGot_Lo";
340 case AsmToken::PercentGot_Ofst:
341 OS << "PercentGot_Ofst";
343 case AsmToken::PercentGot_Page:
344 OS << "PercentGot_Page";
346 case AsmToken::PercentGottprel:
347 OS << "PercentGottprel";
349 case AsmToken::PercentGp_Rel:
350 OS << "PercentGp_Rel";
352 case AsmToken::PercentHi:
355 case AsmToken::PercentHigher:
356 OS << "PercentHigher";
358 case AsmToken::PercentHighest:
359 OS << "PercentHighest";
361 case AsmToken::PercentLo:
364 case AsmToken::PercentNeg:
367 case AsmToken::PercentPcrel_Hi:
368 OS << "PercentPcrel_Hi";
370 case AsmToken::PercentPcrel_Lo:
371 OS << "PercentPcrel_Lo";
373 case AsmToken::PercentTlsgd:
374 OS << "PercentTlsgd";
376 case AsmToken::PercentTlsldm:
377 OS << "PercentTlsldm";
379 case AsmToken::PercentTprel_Hi:
380 OS << "PercentTprel_Hi";
382 case AsmToken::PercentTprel_Lo:
383 OS << "PercentTprel_Lo";
387 // Print the token string.
389 OS.write_escaped(Tok.getString());
396 static int fillCommandLineSymbols(MCAsmParser &Parser) {
397 for (auto &I: DefineSymbol) {
398 auto Pair = StringRef(I).split('=');
399 auto Sym = Pair.first;
400 auto Val = Pair.second;
402 if (Sym.empty() || Val.empty()) {
403 errs() << "error: defsym must be of the form: sym=value: " << I << "\n";
407 if (Val.getAsInteger(0, Value)) {
408 errs() << "error: Value is not an integer: " << Val << "\n";
411 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
416 static int AssembleInput(const char *ProgName, const Target *TheTarget,
417 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
418 MCAsmInfo &MAI, MCSubtargetInfo &STI,
419 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
420 std::unique_ptr<MCAsmParser> Parser(
421 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
422 std::unique_ptr<MCTargetAsmParser> TAP(
423 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
427 << ": error: this target does not support assembly parsing.\n";
431 int SymbolResult = fillCommandLineSymbols(*Parser);
434 Parser->setShowParsedOperands(ShowInstOperands);
435 Parser->setTargetParser(*TAP);
437 int Res = Parser->Run(NoInitialTextSection);
442 int main(int argc, char **argv) {
443 // Print a stack trace if we signal out.
444 sys::PrintStackTraceOnErrorSignal(argv[0]);
445 PrettyStackTraceProgram X(argc, argv);
446 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
448 // Initialize targets and assembly printers/parsers.
449 llvm::InitializeAllTargetInfos();
450 llvm::InitializeAllTargetMCs();
451 llvm::InitializeAllAsmParsers();
452 llvm::InitializeAllDisassemblers();
454 // Register the target printer for --version.
455 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
457 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
458 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
459 TripleName = Triple::normalize(TripleName);
460 setDwarfDebugFlags(argc, argv);
462 setDwarfDebugProducer();
464 const char *ProgName = argv[0];
465 const Target *TheTarget = GetTarget(ProgName);
468 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
469 // construct the Triple object.
470 Triple TheTriple(TripleName);
472 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
473 MemoryBuffer::getFileOrSTDIN(InputFilename);
474 if (std::error_code EC = BufferPtr.getError()) {
475 errs() << InputFilename << ": " << EC.message() << '\n';
478 MemoryBuffer *Buffer = BufferPtr->get();
482 // Tell SrcMgr about this buffer, which is what the parser will pick up.
483 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
485 // Record the location of the include directories so that the lexer can find
487 SrcMgr.setIncludeDirs(IncludeDirs);
489 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
490 assert(MRI && "Unable to create target register info!");
492 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
493 assert(MAI && "Unable to create target asm info!");
495 MAI->setRelaxELFRelocations(RelaxELFRel);
497 if (CompressDebugSections != DebugCompressionType::DCT_None) {
498 if (!zlib::isAvailable()) {
500 << ": build tools with zlib to enable -compress-debug-sections";
503 MAI->setCompressDebugSections(CompressDebugSections);
505 MAI->setPreserveAsmComments(PreserveComments);
507 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
508 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
509 MCObjectFileInfo MOFI;
510 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
511 MOFI.InitMCObjectFileInfo(TheTriple, PIC, CMModel, Ctx);
514 Ctx.setAllowTemporaryLabels(false);
516 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
517 // Default to 4 for dwarf version.
518 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
519 if (DwarfVersion < 2 || DwarfVersion > 4) {
520 errs() << ProgName << ": Dwarf version " << DwarfVersion
521 << " is not supported." << '\n';
524 Ctx.setDwarfVersion(DwarfVersion);
525 if (!DwarfDebugFlags.empty())
526 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
527 if (!DwarfDebugProducer.empty())
528 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
529 if (!DebugCompilationDir.empty())
530 Ctx.setCompilationDir(DebugCompilationDir);
532 // If no compilation dir is set, try to use the current directory.
533 SmallString<128> CWD;
534 if (!sys::fs::current_path(CWD))
535 Ctx.setCompilationDir(CWD);
537 if (!MainFileName.empty())
538 Ctx.setMainFileName(MainFileName);
540 // Package up features to be passed to target/subtarget
541 std::string FeaturesStr;
543 SubtargetFeatures Features;
544 for (unsigned i = 0; i != MAttrs.size(); ++i)
545 Features.AddFeature(MAttrs[i]);
546 FeaturesStr = Features.getString();
549 std::unique_ptr<tool_output_file> Out = GetOutputStream();
553 std::unique_ptr<buffer_ostream> BOS;
554 raw_pwrite_stream *OS = &Out->os();
555 std::unique_ptr<MCStreamer> Str;
557 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
558 std::unique_ptr<MCSubtargetInfo> STI(
559 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
561 MCInstPrinter *IP = nullptr;
562 if (FileType == OFT_AssemblyFile) {
563 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
568 << "error: unable to create instruction printer for target triple '"
569 << TheTriple.normalize() << "' with assembly variant "
570 << OutputAsmVariant << ".\n";
574 // Set the display preference for hex vs. decimal immediates.
575 IP->setPrintImmHex(PrintImmHex);
577 // Set up the AsmStreamer.
578 MCCodeEmitter *CE = nullptr;
579 MCAsmBackend *MAB = nullptr;
581 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
582 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU, MCOptions);
584 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
585 Str.reset(TheTarget->createAsmStreamer(
586 Ctx, std::move(FOut), /*asmverbose*/ true,
587 /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
589 } else if (FileType == OFT_Null) {
590 Str.reset(TheTarget->createNullStreamer(Ctx));
592 assert(FileType == OFT_ObjectFile && "Invalid file type!");
594 // Don't waste memory on names of temp labels.
595 Ctx.setUseNamesOnTempLabels(false);
597 if (!Out->os().supportsSeeking()) {
598 BOS = make_unique<buffer_ostream>(Out->os());
602 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
603 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU,
605 Str.reset(TheTarget->createMCObjectStreamer(
606 TheTriple, Ctx, *MAB, *OS, CE, *STI, MCOptions.MCRelaxAll,
607 MCOptions.MCIncrementalLinkerCompatible,
608 /*DWARFMustBeAtTheEnd*/ false));
610 Str->InitSections(true);
614 bool disassemble = false;
617 Res = AsLexInput(SrcMgr, *MAI, Out->os());
620 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
623 case AC_MDisassemble:
624 assert(IP && "Expected assembly output");
633 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
634 *Buffer, SrcMgr, Out->os());
636 // Keep output if no errors.
637 if (Res == 0) Out->keep();