Home | History | Annotate | Download | only in llvm-mc
      1 //===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This utility is a simple driver that allows command line hacking on machine
     11 // code.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "Disassembler.h"
     16 #include "llvm/ADT/OwningPtr.h"
     17 #include "llvm/MC/MCAsmBackend.h"
     18 #include "llvm/MC/MCAsmInfo.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/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/Support/CommandLine.h"
     30 #include "llvm/Support/FileUtilities.h"
     31 #include "llvm/Support/FormattedStream.h"
     32 #include "llvm/Support/Host.h"
     33 #include "llvm/Support/ManagedStatic.h"
     34 #include "llvm/Support/MemoryBuffer.h"
     35 #include "llvm/Support/PrettyStackTrace.h"
     36 #include "llvm/Support/Signals.h"
     37 #include "llvm/Support/SourceMgr.h"
     38 #include "llvm/Support/TargetRegistry.h"
     39 #include "llvm/Support/TargetSelect.h"
     40 #include "llvm/Support/ToolOutputFile.h"
     41 using namespace llvm;
     42 
     43 static cl::opt<std::string>
     44 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
     45 
     46 static cl::opt<std::string>
     47 OutputFilename("o", cl::desc("Output filename"),
     48                cl::value_desc("filename"));
     49 
     50 static cl::opt<bool>
     51 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
     52 
     53 static cl::opt<bool>
     54 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
     55 
     56 static cl::opt<bool>
     57 ShowInstOperands("show-inst-operands",
     58                  cl::desc("Show instructions operands as parsed"));
     59 
     60 static cl::opt<unsigned>
     61 OutputAsmVariant("output-asm-variant",
     62                  cl::desc("Syntax variant to use for output printing"));
     63 
     64 static cl::opt<bool>
     65 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
     66 
     67 static cl::opt<bool>
     68 DisableCFI("disable-cfi", cl::desc("Do not use .cfi_* directives"));
     69 
     70 static cl::opt<bool>
     71 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
     72 
     73 enum OutputFileType {
     74   OFT_Null,
     75   OFT_AssemblyFile,
     76   OFT_ObjectFile
     77 };
     78 static cl::opt<OutputFileType>
     79 FileType("filetype", cl::init(OFT_AssemblyFile),
     80   cl::desc("Choose an output file type:"),
     81   cl::values(
     82        clEnumValN(OFT_AssemblyFile, "asm",
     83                   "Emit an assembly ('.s') file"),
     84        clEnumValN(OFT_Null, "null",
     85                   "Don't emit anything (for timing purposes)"),
     86        clEnumValN(OFT_ObjectFile, "obj",
     87                   "Emit a native object ('.o') file"),
     88        clEnumValEnd));
     89 
     90 static cl::list<std::string>
     91 IncludeDirs("I", cl::desc("Directory of include files"),
     92             cl::value_desc("directory"), cl::Prefix);
     93 
     94 static cl::opt<std::string>
     95 ArchName("arch", cl::desc("Target arch to assemble for, "
     96                           "see -version for available targets"));
     97 
     98 static cl::opt<std::string>
     99 TripleName("triple", cl::desc("Target triple to assemble for, "
    100                               "see -version for available targets"));
    101 
    102 static cl::opt<std::string>
    103 MCPU("mcpu",
    104      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
    105      cl::value_desc("cpu-name"),
    106      cl::init(""));
    107 
    108 static cl::list<std::string>
    109 MAttrs("mattr",
    110   cl::CommaSeparated,
    111   cl::desc("Target specific attributes (-mattr=help for details)"),
    112   cl::value_desc("a1,+a2,-a3,..."));
    113 
    114 static cl::opt<Reloc::Model>
    115 RelocModel("relocation-model",
    116              cl::desc("Choose relocation model"),
    117              cl::init(Reloc::Default),
    118              cl::values(
    119             clEnumValN(Reloc::Default, "default",
    120                        "Target default relocation model"),
    121             clEnumValN(Reloc::Static, "static",
    122                        "Non-relocatable code"),
    123             clEnumValN(Reloc::PIC_, "pic",
    124                        "Fully relocatable, position independent code"),
    125             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
    126                        "Relocatable external references, non-relocatable code"),
    127             clEnumValEnd));
    128 
    129 static cl::opt<llvm::CodeModel::Model>
    130 CMModel("code-model",
    131         cl::desc("Choose code model"),
    132         cl::init(CodeModel::Default),
    133         cl::values(clEnumValN(CodeModel::Default, "default",
    134                               "Target default code model"),
    135                    clEnumValN(CodeModel::Small, "small",
    136                               "Small code model"),
    137                    clEnumValN(CodeModel::Kernel, "kernel",
    138                               "Kernel code model"),
    139                    clEnumValN(CodeModel::Medium, "medium",
    140                               "Medium code model"),
    141                    clEnumValN(CodeModel::Large, "large",
    142                               "Large code model"),
    143                    clEnumValEnd));
    144 
    145 static cl::opt<bool>
    146 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
    147                                    "in the text section"));
    148 
    149 static cl::opt<bool>
    150 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
    151 
    152 static cl::opt<bool>
    153 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
    154                                   "source files"));
    155 
    156 static cl::opt<std::string>
    157 DebugCompilationDir("fdebug-compilation-dir",
    158                     cl::desc("Specifies the debug info's compilation dir"));
    159 
    160 static cl::opt<std::string>
    161 MainFileName("main-file-name",
    162              cl::desc("Specifies the name we should consider the input file"));
    163 
    164 enum ActionType {
    165   AC_AsLex,
    166   AC_Assemble,
    167   AC_Disassemble,
    168   AC_MDisassemble,
    169   AC_HDisassemble
    170 };
    171 
    172 static cl::opt<ActionType>
    173 Action(cl::desc("Action to perform:"),
    174        cl::init(AC_Assemble),
    175        cl::values(clEnumValN(AC_AsLex, "as-lex",
    176                              "Lex tokens from a .s file"),
    177                   clEnumValN(AC_Assemble, "assemble",
    178                              "Assemble a .s file (default)"),
    179                   clEnumValN(AC_Disassemble, "disassemble",
    180                              "Disassemble strings of hex bytes"),
    181                   clEnumValN(AC_MDisassemble, "mdis",
    182                              "Marked up disassembly of strings of hex bytes"),
    183                   clEnumValN(AC_HDisassemble, "hdis",
    184                              "Disassemble strings of hex bytes printing "
    185                              "immediates as hex"),
    186                   clEnumValEnd));
    187 
    188 static const Target *GetTarget(const char *ProgName) {
    189   // Figure out the target triple.
    190   if (TripleName.empty())
    191     TripleName = sys::getDefaultTargetTriple();
    192   Triple TheTriple(Triple::normalize(TripleName));
    193 
    194   // Get the target specific parser.
    195   std::string Error;
    196   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
    197                                                          Error);
    198   if (!TheTarget) {
    199     errs() << ProgName << ": " << Error;
    200     return 0;
    201   }
    202 
    203   // Update the triple name and return the found target.
    204   TripleName = TheTriple.getTriple();
    205   return TheTarget;
    206 }
    207 
    208 static tool_output_file *GetOutputStream() {
    209   if (OutputFilename == "")
    210     OutputFilename = "-";
    211 
    212   std::string Err;
    213   tool_output_file *Out =
    214       new tool_output_file(OutputFilename.c_str(), Err, sys::fs::F_Binary);
    215   if (!Err.empty()) {
    216     errs() << Err << '\n';
    217     delete Out;
    218     return 0;
    219   }
    220 
    221   return Out;
    222 }
    223 
    224 static std::string DwarfDebugFlags;
    225 static void setDwarfDebugFlags(int argc, char **argv) {
    226   if (!getenv("RC_DEBUG_OPTIONS"))
    227     return;
    228   for (int i = 0; i < argc; i++) {
    229     DwarfDebugFlags += argv[i];
    230     if (i + 1 < argc)
    231       DwarfDebugFlags += " ";
    232   }
    233 }
    234 
    235 static std::string DwarfDebugProducer;
    236 static void setDwarfDebugProducer(void) {
    237   if(!getenv("DEBUG_PRODUCER"))
    238     return;
    239   DwarfDebugProducer += getenv("DEBUG_PRODUCER");
    240 }
    241 
    242 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, tool_output_file *Out) {
    243 
    244   AsmLexer Lexer(MAI);
    245   Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
    246 
    247   bool Error = false;
    248   while (Lexer.Lex().isNot(AsmToken::Eof)) {
    249     AsmToken Tok = Lexer.getTok();
    250 
    251     switch (Tok.getKind()) {
    252     default:
    253       SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
    254                           "unknown token");
    255       Error = true;
    256       break;
    257     case AsmToken::Error:
    258       Error = true; // error already printed.
    259       break;
    260     case AsmToken::Identifier:
    261       Out->os() << "identifier: " << Lexer.getTok().getString();
    262       break;
    263     case AsmToken::Integer:
    264       Out->os() << "int: " << Lexer.getTok().getString();
    265       break;
    266     case AsmToken::Real:
    267       Out->os() << "real: " << Lexer.getTok().getString();
    268       break;
    269     case AsmToken::String:
    270       Out->os() << "string: " << Lexer.getTok().getString();
    271       break;
    272 
    273     case AsmToken::Amp:            Out->os() << "Amp"; break;
    274     case AsmToken::AmpAmp:         Out->os() << "AmpAmp"; break;
    275     case AsmToken::At:             Out->os() << "At"; break;
    276     case AsmToken::Caret:          Out->os() << "Caret"; break;
    277     case AsmToken::Colon:          Out->os() << "Colon"; break;
    278     case AsmToken::Comma:          Out->os() << "Comma"; break;
    279     case AsmToken::Dollar:         Out->os() << "Dollar"; break;
    280     case AsmToken::Dot:            Out->os() << "Dot"; break;
    281     case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
    282     case AsmToken::Eof:            Out->os() << "Eof"; break;
    283     case AsmToken::Equal:          Out->os() << "Equal"; break;
    284     case AsmToken::EqualEqual:     Out->os() << "EqualEqual"; break;
    285     case AsmToken::Exclaim:        Out->os() << "Exclaim"; break;
    286     case AsmToken::ExclaimEqual:   Out->os() << "ExclaimEqual"; break;
    287     case AsmToken::Greater:        Out->os() << "Greater"; break;
    288     case AsmToken::GreaterEqual:   Out->os() << "GreaterEqual"; break;
    289     case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
    290     case AsmToken::Hash:           Out->os() << "Hash"; break;
    291     case AsmToken::LBrac:          Out->os() << "LBrac"; break;
    292     case AsmToken::LCurly:         Out->os() << "LCurly"; break;
    293     case AsmToken::LParen:         Out->os() << "LParen"; break;
    294     case AsmToken::Less:           Out->os() << "Less"; break;
    295     case AsmToken::LessEqual:      Out->os() << "LessEqual"; break;
    296     case AsmToken::LessGreater:    Out->os() << "LessGreater"; break;
    297     case AsmToken::LessLess:       Out->os() << "LessLess"; break;
    298     case AsmToken::Minus:          Out->os() << "Minus"; break;
    299     case AsmToken::Percent:        Out->os() << "Percent"; break;
    300     case AsmToken::Pipe:           Out->os() << "Pipe"; break;
    301     case AsmToken::PipePipe:       Out->os() << "PipePipe"; break;
    302     case AsmToken::Plus:           Out->os() << "Plus"; break;
    303     case AsmToken::RBrac:          Out->os() << "RBrac"; break;
    304     case AsmToken::RCurly:         Out->os() << "RCurly"; break;
    305     case AsmToken::RParen:         Out->os() << "RParen"; break;
    306     case AsmToken::Slash:          Out->os() << "Slash"; break;
    307     case AsmToken::Star:           Out->os() << "Star"; break;
    308     case AsmToken::Tilde:          Out->os() << "Tilde"; break;
    309     }
    310 
    311     // Print the token string.
    312     Out->os() << " (\"";
    313     Out->os().write_escaped(Tok.getString());
    314     Out->os() << "\")\n";
    315   }
    316 
    317   return Error;
    318 }
    319 
    320 static int AssembleInput(const char *ProgName, const Target *TheTarget,
    321                          SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
    322                          MCAsmInfo &MAI, MCSubtargetInfo &STI) {
    323   OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
    324                                                   Str, MAI));
    325   OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(STI, *Parser));
    326   if (!TAP) {
    327     errs() << ProgName
    328            << ": error: this target does not support assembly parsing.\n";
    329     return 1;
    330   }
    331 
    332   Parser->setShowParsedOperands(ShowInstOperands);
    333   Parser->setTargetParser(*TAP.get());
    334 
    335   int Res = Parser->Run(NoInitialTextSection);
    336 
    337   return Res;
    338 }
    339 
    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.
    345 
    346   // Initialize targets and assembly printers/parsers.
    347   llvm::InitializeAllTargetInfos();
    348   llvm::InitializeAllTargetMCs();
    349   llvm::InitializeAllAsmParsers();
    350   llvm::InitializeAllDisassemblers();
    351 
    352   // Register the target printer for --version.
    353   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
    354 
    355   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
    356   TripleName = Triple::normalize(TripleName);
    357   setDwarfDebugFlags(argc, argv);
    358 
    359   setDwarfDebugProducer();
    360 
    361   const char *ProgName = argv[0];
    362   const Target *TheTarget = GetTarget(ProgName);
    363   if (!TheTarget)
    364     return 1;
    365 
    366   OwningPtr<MemoryBuffer> BufferPtr;
    367   if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
    368     errs() << ProgName << ": " << ec.message() << '\n';
    369     return 1;
    370   }
    371   MemoryBuffer *Buffer = BufferPtr.take();
    372 
    373   SourceMgr SrcMgr;
    374 
    375   // Tell SrcMgr about this buffer, which is what the parser will pick up.
    376   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
    377 
    378   // Record the location of the include directories so that the lexer can find
    379   // it later.
    380   SrcMgr.setIncludeDirs(IncludeDirs);
    381 
    382   llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
    383   assert(MRI && "Unable to create target register info!");
    384 
    385   llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
    386   assert(MAI && "Unable to create target asm info!");
    387 
    388   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
    389   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
    390   OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
    391   MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
    392   MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
    393 
    394   if (SaveTempLabels)
    395     Ctx.setAllowTemporaryLabels(false);
    396 
    397   Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
    398   if (!DwarfDebugFlags.empty())
    399     Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
    400   if (!DwarfDebugProducer.empty())
    401     Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
    402   if (!DebugCompilationDir.empty())
    403     Ctx.setCompilationDir(DebugCompilationDir);
    404   if (!MainFileName.empty())
    405     Ctx.setMainFileName(MainFileName);
    406 
    407   // Package up features to be passed to target/subtarget
    408   std::string FeaturesStr;
    409   if (MAttrs.size()) {
    410     SubtargetFeatures Features;
    411     for (unsigned i = 0; i != MAttrs.size(); ++i)
    412       Features.AddFeature(MAttrs[i]);
    413     FeaturesStr = Features.getString();
    414   }
    415 
    416   OwningPtr<tool_output_file> Out(GetOutputStream());
    417   if (!Out)
    418     return 1;
    419 
    420   formatted_raw_ostream FOS(Out->os());
    421   OwningPtr<MCStreamer> Str;
    422 
    423   OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
    424   OwningPtr<MCSubtargetInfo>
    425     STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
    426 
    427   MCInstPrinter *IP = NULL;
    428   if (FileType == OFT_AssemblyFile) {
    429     IP =
    430       TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
    431     MCCodeEmitter *CE = 0;
    432     MCAsmBackend *MAB = 0;
    433     if (ShowEncoding) {
    434       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
    435       MAB = TheTarget->createMCAsmBackend(TripleName, MCPU);
    436     }
    437     bool UseCFI = !DisableCFI;
    438     Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
    439                                            /*useLoc*/ true,
    440                                            UseCFI,
    441                                            /*useDwarfDirectory*/ true,
    442                                            IP, CE, MAB, ShowInst));
    443 
    444   } else if (FileType == OFT_Null) {
    445     Str.reset(createNullStreamer(Ctx));
    446   } else {
    447     assert(FileType == OFT_ObjectFile && "Invalid file type!");
    448     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
    449     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(TripleName, MCPU);
    450     Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
    451                                                 FOS, CE, RelaxAll,
    452                                                 NoExecStack));
    453   }
    454 
    455   int Res = 1;
    456   bool disassemble = false;
    457   switch (Action) {
    458   case AC_AsLex:
    459     Res = AsLexInput(SrcMgr, *MAI, Out.get());
    460     break;
    461   case AC_Assemble:
    462     Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI);
    463     break;
    464   case AC_MDisassemble:
    465     assert(IP && "Expected assembly output");
    466     IP->setUseMarkup(1);
    467     disassemble = true;
    468     break;
    469   case AC_HDisassemble:
    470     assert(IP && "Expected assembly output");
    471     IP->setPrintImmHex(1);
    472     disassemble = true;
    473     break;
    474   case AC_Disassemble:
    475     disassemble = true;
    476     break;
    477   }
    478   if (disassemble)
    479     Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
    480                                     *Buffer, SrcMgr, Out->os());
    481 
    482   // Keep output if no errors.
    483   if (Res == 0) Out->keep();
    484   return Res;
    485 }
    486