llvm-mc.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. #include "Disassembler.h"
  15. #include "llvm/MC/MCAsmBackend.h"
  16. #include "llvm/MC/MCAsmInfo.h"
  17. #include "llvm/MC/MCContext.h"
  18. #include "llvm/MC/MCInstPrinter.h"
  19. #include "llvm/MC/MCInstrInfo.h"
  20. #include "llvm/MC/MCObjectFileInfo.h"
  21. #include "llvm/MC/MCParser/AsmLexer.h"
  22. #include "llvm/MC/MCRegisterInfo.h"
  23. #include "llvm/MC/MCSectionMachO.h"
  24. #include "llvm/MC/MCStreamer.h"
  25. #include "llvm/MC/MCSubtargetInfo.h"
  26. #include "llvm/MC/MCTargetAsmParser.h"
  27. #include "llvm/MC/MCTargetOptionsCommandFlags.h"
  28. #include "llvm/Support/CommandLine.h"
  29. #include "llvm/Support/Compression.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. static cl::opt<std::string>
  43. InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
  44. static cl::opt<std::string>
  45. OutputFilename("o", cl::desc("Output filename"),
  46. cl::value_desc("filename"));
  47. static cl::opt<bool>
  48. ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
  49. static cl::opt<bool>
  50. CompressDebugSections("compress-debug-sections",
  51. cl::desc("Compress DWARF debug sections"));
  52. static cl::opt<bool>
  53. ShowInst("show-inst", cl::desc("Show internal instruction representation"));
  54. static cl::opt<bool>
  55. ShowInstOperands("show-inst-operands",
  56. cl::desc("Show instructions operands as parsed"));
  57. static cl::opt<unsigned>
  58. OutputAsmVariant("output-asm-variant",
  59. cl::desc("Syntax variant to use for output printing"));
  60. static cl::opt<bool>
  61. PrintImmHex("print-imm-hex", cl::init(false),
  62. cl::desc("Prefer hex format for immediate values"));
  63. static cl::list<std::string>
  64. DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
  65. enum OutputFileType {
  66. OFT_Null,
  67. OFT_AssemblyFile,
  68. OFT_ObjectFile
  69. };
  70. static cl::opt<OutputFileType>
  71. FileType("filetype", cl::init(OFT_AssemblyFile),
  72. cl::desc("Choose an output file type:"),
  73. cl::values(
  74. clEnumValN(OFT_AssemblyFile, "asm",
  75. "Emit an assembly ('.s') file"),
  76. clEnumValN(OFT_Null, "null",
  77. "Don't emit anything (for timing purposes)"),
  78. clEnumValN(OFT_ObjectFile, "obj",
  79. "Emit a native object ('.o') file"),
  80. clEnumValEnd));
  81. static cl::list<std::string>
  82. IncludeDirs("I", cl::desc("Directory of include files"),
  83. cl::value_desc("directory"), cl::Prefix);
  84. static cl::opt<std::string>
  85. ArchName("arch", cl::desc("Target arch to assemble for, "
  86. "see -version for available targets"));
  87. static cl::opt<std::string>
  88. TripleName("triple", cl::desc("Target triple to assemble for, "
  89. "see -version for available targets"));
  90. static cl::opt<std::string>
  91. MCPU("mcpu",
  92. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  93. cl::value_desc("cpu-name"),
  94. cl::init(""));
  95. static cl::list<std::string>
  96. MAttrs("mattr",
  97. cl::CommaSeparated,
  98. cl::desc("Target specific attributes (-mattr=help for details)"),
  99. cl::value_desc("a1,+a2,-a3,..."));
  100. static cl::opt<Reloc::Model>
  101. RelocModel("relocation-model",
  102. cl::desc("Choose relocation model"),
  103. cl::init(Reloc::Default),
  104. cl::values(
  105. clEnumValN(Reloc::Default, "default",
  106. "Target default relocation model"),
  107. clEnumValN(Reloc::Static, "static",
  108. "Non-relocatable code"),
  109. clEnumValN(Reloc::PIC_, "pic",
  110. "Fully relocatable, position independent code"),
  111. clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
  112. "Relocatable external references, non-relocatable code"),
  113. clEnumValEnd));
  114. static cl::opt<llvm::CodeModel::Model>
  115. CMModel("code-model",
  116. cl::desc("Choose code model"),
  117. cl::init(CodeModel::Default),
  118. cl::values(clEnumValN(CodeModel::Default, "default",
  119. "Target default code model"),
  120. clEnumValN(CodeModel::Small, "small",
  121. "Small code model"),
  122. clEnumValN(CodeModel::Kernel, "kernel",
  123. "Kernel code model"),
  124. clEnumValN(CodeModel::Medium, "medium",
  125. "Medium code model"),
  126. clEnumValN(CodeModel::Large, "large",
  127. "Large code model"),
  128. clEnumValEnd));
  129. static cl::opt<bool>
  130. NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
  131. "in the text section"));
  132. static cl::opt<bool>
  133. GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
  134. "source files"));
  135. static cl::opt<std::string>
  136. DebugCompilationDir("fdebug-compilation-dir",
  137. cl::desc("Specifies the debug info's compilation dir"));
  138. static cl::opt<std::string>
  139. MainFileName("main-file-name",
  140. cl::desc("Specifies the name we should consider the input file"));
  141. static cl::opt<bool> SaveTempLabels("save-temp-labels",
  142. cl::desc("Don't discard temporary labels"));
  143. static cl::opt<bool> NoExecStack("no-exec-stack",
  144. cl::desc("File doesn't need an exec stack"));
  145. enum ActionType {
  146. AC_AsLex,
  147. AC_Assemble,
  148. AC_Disassemble,
  149. AC_MDisassemble,
  150. };
  151. static cl::opt<ActionType>
  152. Action(cl::desc("Action to perform:"),
  153. cl::init(AC_Assemble),
  154. cl::values(clEnumValN(AC_AsLex, "as-lex",
  155. "Lex tokens from a .s file"),
  156. clEnumValN(AC_Assemble, "assemble",
  157. "Assemble a .s file (default)"),
  158. clEnumValN(AC_Disassemble, "disassemble",
  159. "Disassemble strings of hex bytes"),
  160. clEnumValN(AC_MDisassemble, "mdis",
  161. "Marked up disassembly of strings of hex bytes"),
  162. clEnumValEnd));
  163. static const Target *GetTarget(const char *ProgName) {
  164. // Figure out the target triple.
  165. if (TripleName.empty())
  166. TripleName = sys::getDefaultTargetTriple();
  167. Triple TheTriple(Triple::normalize(TripleName));
  168. // Get the target specific parser.
  169. std::string Error;
  170. const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
  171. Error);
  172. if (!TheTarget) {
  173. errs() << ProgName << ": " << Error;
  174. return nullptr;
  175. }
  176. // Update the triple name and return the found target.
  177. TripleName = TheTriple.getTriple();
  178. return TheTarget;
  179. }
  180. static std::unique_ptr<tool_output_file> GetOutputStream() {
  181. if (OutputFilename == "")
  182. OutputFilename = "-";
  183. std::error_code EC;
  184. auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
  185. sys::fs::F_None);
  186. if (EC) {
  187. errs() << EC.message() << '\n';
  188. return nullptr;
  189. }
  190. return Out;
  191. }
  192. static std::string DwarfDebugFlags;
  193. static void setDwarfDebugFlags(int argc, char **argv) {
  194. if (!getenv("RC_DEBUG_OPTIONS"))
  195. return;
  196. for (int i = 0; i < argc; i++) {
  197. DwarfDebugFlags += argv[i];
  198. if (i + 1 < argc)
  199. DwarfDebugFlags += " ";
  200. }
  201. }
  202. static std::string DwarfDebugProducer;
  203. static void setDwarfDebugProducer(void) {
  204. if(!getenv("DEBUG_PRODUCER"))
  205. return;
  206. DwarfDebugProducer += getenv("DEBUG_PRODUCER");
  207. }
  208. static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
  209. raw_ostream &OS) {
  210. AsmLexer Lexer(MAI);
  211. Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
  212. bool Error = false;
  213. while (Lexer.Lex().isNot(AsmToken::Eof)) {
  214. AsmToken Tok = Lexer.getTok();
  215. switch (Tok.getKind()) {
  216. default:
  217. SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
  218. "unknown token");
  219. Error = true;
  220. break;
  221. case AsmToken::Error:
  222. Error = true; // error already printed.
  223. break;
  224. case AsmToken::Identifier:
  225. OS << "identifier: " << Lexer.getTok().getString();
  226. break;
  227. case AsmToken::Integer:
  228. OS << "int: " << Lexer.getTok().getString();
  229. break;
  230. case AsmToken::Real:
  231. OS << "real: " << Lexer.getTok().getString();
  232. break;
  233. case AsmToken::String:
  234. OS << "string: " << Lexer.getTok().getString();
  235. break;
  236. case AsmToken::Amp: OS << "Amp"; break;
  237. case AsmToken::AmpAmp: OS << "AmpAmp"; break;
  238. case AsmToken::At: OS << "At"; break;
  239. case AsmToken::Caret: OS << "Caret"; break;
  240. case AsmToken::Colon: OS << "Colon"; break;
  241. case AsmToken::Comma: OS << "Comma"; break;
  242. case AsmToken::Dollar: OS << "Dollar"; break;
  243. case AsmToken::Dot: OS << "Dot"; break;
  244. case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
  245. case AsmToken::Eof: OS << "Eof"; break;
  246. case AsmToken::Equal: OS << "Equal"; break;
  247. case AsmToken::EqualEqual: OS << "EqualEqual"; break;
  248. case AsmToken::Exclaim: OS << "Exclaim"; break;
  249. case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break;
  250. case AsmToken::Greater: OS << "Greater"; break;
  251. case AsmToken::GreaterEqual: OS << "GreaterEqual"; break;
  252. case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
  253. case AsmToken::Hash: OS << "Hash"; break;
  254. case AsmToken::LBrac: OS << "LBrac"; break;
  255. case AsmToken::LCurly: OS << "LCurly"; break;
  256. case AsmToken::LParen: OS << "LParen"; break;
  257. case AsmToken::Less: OS << "Less"; break;
  258. case AsmToken::LessEqual: OS << "LessEqual"; break;
  259. case AsmToken::LessGreater: OS << "LessGreater"; break;
  260. case AsmToken::LessLess: OS << "LessLess"; break;
  261. case AsmToken::Minus: OS << "Minus"; break;
  262. case AsmToken::Percent: OS << "Percent"; break;
  263. case AsmToken::Pipe: OS << "Pipe"; break;
  264. case AsmToken::PipePipe: OS << "PipePipe"; break;
  265. case AsmToken::Plus: OS << "Plus"; break;
  266. case AsmToken::RBrac: OS << "RBrac"; break;
  267. case AsmToken::RCurly: OS << "RCurly"; break;
  268. case AsmToken::RParen: OS << "RParen"; break;
  269. case AsmToken::Slash: OS << "Slash"; break;
  270. case AsmToken::Star: OS << "Star"; break;
  271. case AsmToken::Tilde: OS << "Tilde"; break;
  272. }
  273. // Print the token string.
  274. OS << " (\"";
  275. OS.write_escaped(Tok.getString());
  276. OS << "\")\n";
  277. }
  278. return Error;
  279. }
  280. static int fillCommandLineSymbols(MCAsmParser &Parser){
  281. for(auto &I: DefineSymbol){
  282. auto Pair = StringRef(I).split('=');
  283. if(Pair.second.empty()){
  284. errs() << "error: defsym must be of the form: sym=value: " << I;
  285. return 1;
  286. }
  287. int64_t Value;
  288. if(Pair.second.getAsInteger(0, Value)){
  289. errs() << "error: Value is not an integer: " << Pair.second;
  290. return 1;
  291. }
  292. auto &Context = Parser.getContext();
  293. auto Symbol = Context.getOrCreateSymbol(Pair.first);
  294. Parser.getStreamer().EmitAssignment(Symbol,
  295. MCConstantExpr::create(Value, Context));
  296. }
  297. return 0;
  298. }
  299. static int AssembleInput(const char *ProgName, const Target *TheTarget,
  300. SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
  301. MCAsmInfo &MAI, MCSubtargetInfo &STI,
  302. MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
  303. std::unique_ptr<MCAsmParser> Parser(
  304. createMCAsmParser(SrcMgr, Ctx, Str, MAI));
  305. std::unique_ptr<MCTargetAsmParser> TAP(
  306. TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
  307. if (!TAP) {
  308. errs() << ProgName
  309. << ": error: this target does not support assembly parsing.\n";
  310. return 1;
  311. }
  312. int SymbolResult = fillCommandLineSymbols(*Parser);
  313. if(SymbolResult)
  314. return SymbolResult;
  315. Parser->setShowParsedOperands(ShowInstOperands);
  316. Parser->setTargetParser(*TAP);
  317. int Res = Parser->Run(NoInitialTextSection);
  318. return Res;
  319. }
  320. // HLSL Change: changed calling convention to __cdecl
  321. int __cdecl main(int argc, char **argv) {
  322. // Print a stack trace if we signal out.
  323. sys::PrintStackTraceOnErrorSignal();
  324. PrettyStackTraceProgram X(argc, argv);
  325. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  326. // Initialize targets and assembly printers/parsers.
  327. llvm::InitializeAllTargetInfos();
  328. llvm::InitializeAllTargetMCs();
  329. llvm::InitializeAllAsmParsers();
  330. llvm::InitializeAllDisassemblers();
  331. // Register the target printer for --version.
  332. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  333. cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
  334. MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
  335. TripleName = Triple::normalize(TripleName);
  336. setDwarfDebugFlags(argc, argv);
  337. setDwarfDebugProducer();
  338. const char *ProgName = argv[0];
  339. const Target *TheTarget = GetTarget(ProgName);
  340. if (!TheTarget)
  341. return 1;
  342. // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
  343. // construct the Triple object.
  344. Triple TheTriple(TripleName);
  345. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
  346. MemoryBuffer::getFileOrSTDIN(InputFilename);
  347. if (std::error_code EC = BufferPtr.getError()) {
  348. errs() << ProgName << ": " << EC.message() << '\n';
  349. return 1;
  350. }
  351. MemoryBuffer *Buffer = BufferPtr->get();
  352. SourceMgr SrcMgr;
  353. // Tell SrcMgr about this buffer, which is what the parser will pick up.
  354. SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
  355. // Record the location of the include directories so that the lexer can find
  356. // it later.
  357. SrcMgr.setIncludeDirs(IncludeDirs);
  358. std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
  359. assert(MRI && "Unable to create target register info!");
  360. std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
  361. assert(MAI && "Unable to create target asm info!");
  362. if (CompressDebugSections) {
  363. if (!zlib::isAvailable()) {
  364. errs() << ProgName
  365. << ": build tools with zlib to enable -compress-debug-sections";
  366. return 1;
  367. }
  368. MAI->setCompressDebugSections(true);
  369. }
  370. // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
  371. // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
  372. MCObjectFileInfo MOFI;
  373. MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
  374. MOFI.InitMCObjectFileInfo(TheTriple, RelocModel, CMModel, Ctx);
  375. if (SaveTempLabels)
  376. Ctx.setAllowTemporaryLabels(false);
  377. Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
  378. // Default to 4 for dwarf version.
  379. unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
  380. if (DwarfVersion < 2 || DwarfVersion > 4) {
  381. errs() << ProgName << ": Dwarf version " << DwarfVersion
  382. << " is not supported." << '\n';
  383. return 1;
  384. }
  385. Ctx.setDwarfVersion(DwarfVersion);
  386. if (!DwarfDebugFlags.empty())
  387. Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
  388. if (!DwarfDebugProducer.empty())
  389. Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
  390. if (!DebugCompilationDir.empty())
  391. Ctx.setCompilationDir(DebugCompilationDir);
  392. if (!MainFileName.empty())
  393. Ctx.setMainFileName(MainFileName);
  394. // Package up features to be passed to target/subtarget
  395. std::string FeaturesStr;
  396. if (MAttrs.size()) {
  397. SubtargetFeatures Features;
  398. for (unsigned i = 0; i != MAttrs.size(); ++i)
  399. Features.AddFeature(MAttrs[i]);
  400. FeaturesStr = Features.getString();
  401. }
  402. std::unique_ptr<tool_output_file> Out = GetOutputStream();
  403. if (!Out)
  404. return 1;
  405. std::unique_ptr<buffer_ostream> BOS;
  406. raw_pwrite_stream *OS = &Out->os();
  407. std::unique_ptr<MCStreamer> Str;
  408. std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
  409. std::unique_ptr<MCSubtargetInfo> STI(
  410. TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
  411. MCInstPrinter *IP = nullptr;
  412. if (FileType == OFT_AssemblyFile) {
  413. IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
  414. *MAI, *MCII, *MRI);
  415. // Set the display preference for hex vs. decimal immediates.
  416. IP->setPrintImmHex(PrintImmHex);
  417. // Set up the AsmStreamer.
  418. MCCodeEmitter *CE = nullptr;
  419. MCAsmBackend *MAB = nullptr;
  420. if (ShowEncoding) {
  421. CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
  422. MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
  423. }
  424. auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
  425. Str.reset(TheTarget->createAsmStreamer(
  426. Ctx, std::move(FOut), /*asmverbose*/ true,
  427. /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
  428. } else if (FileType == OFT_Null) {
  429. Str.reset(TheTarget->createNullStreamer(Ctx));
  430. } else {
  431. assert(FileType == OFT_ObjectFile && "Invalid file type!");
  432. // Don't waste memory on names of temp labels.
  433. Ctx.setUseNamesOnTempLabels(false);
  434. if (!Out->os().supportsSeeking()) {
  435. BOS = make_unique<buffer_ostream>(Out->os());
  436. OS = BOS.get();
  437. }
  438. MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
  439. MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
  440. Str.reset(TheTarget->createMCObjectStreamer(TheTriple, Ctx, *MAB, *OS, CE,
  441. *STI, RelaxAll,
  442. /*DWARFMustBeAtTheEnd*/ false));
  443. if (NoExecStack)
  444. Str->InitSections(true);
  445. }
  446. int Res = 1;
  447. bool disassemble = false;
  448. switch (Action) {
  449. case AC_AsLex:
  450. Res = AsLexInput(SrcMgr, *MAI, Out->os());
  451. break;
  452. case AC_Assemble:
  453. Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
  454. *MCII, MCOptions);
  455. break;
  456. case AC_MDisassemble:
  457. assert(IP && "Expected assembly output");
  458. IP->setUseMarkup(1);
  459. disassemble = true;
  460. break;
  461. case AC_Disassemble:
  462. disassemble = true;
  463. break;
  464. }
  465. if (disassemble)
  466. Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
  467. *Buffer, SrcMgr, Out->os());
  468. // Keep output if no errors.
  469. if (Res == 0) Out->keep();
  470. return Res;
  471. }