llvm-ml.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. //===-- llvm-ml.cpp - masm-compatible assembler -----------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // A simple driver around MasmParser; based on llvm-mc.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/StringSwitch.h"
  13. #include "llvm/MC/MCAsmBackend.h"
  14. #include "llvm/MC/MCAsmInfo.h"
  15. #include "llvm/MC/MCCodeEmitter.h"
  16. #include "llvm/MC/MCContext.h"
  17. #include "llvm/MC/MCInstPrinter.h"
  18. #include "llvm/MC/MCInstrInfo.h"
  19. #include "llvm/MC/MCObjectFileInfo.h"
  20. #include "llvm/MC/MCObjectWriter.h"
  21. #include "llvm/MC/MCParser/AsmLexer.h"
  22. #include "llvm/MC/MCParser/MCTargetAsmParser.h"
  23. #include "llvm/MC/MCRegisterInfo.h"
  24. #include "llvm/MC/MCStreamer.h"
  25. #include "llvm/MC/MCSubtargetInfo.h"
  26. #include "llvm/MC/MCTargetOptionsCommandFlags.h"
  27. #include "llvm/Option/Arg.h"
  28. #include "llvm/Option/ArgList.h"
  29. #include "llvm/Option/Option.h"
  30. #include "llvm/Support/Compression.h"
  31. #include "llvm/Support/FileUtilities.h"
  32. #include "llvm/Support/FormatVariadic.h"
  33. #include "llvm/Support/FormattedStream.h"
  34. #include "llvm/Support/Host.h"
  35. #include "llvm/Support/InitLLVM.h"
  36. #include "llvm/Support/MemoryBuffer.h"
  37. #include "llvm/Support/Path.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"
  42. #include "llvm/Support/WithColor.h"
  43. using namespace llvm;
  44. using namespace llvm::opt;
  45. namespace {
  46. enum ID {
  47. OPT_INVALID = 0, // This is not an option ID.
  48. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  49. HELPTEXT, METAVAR, VALUES) \
  50. OPT_##ID,
  51. #include "Opts.inc"
  52. #undef OPTION
  53. };
  54. #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
  55. #include "Opts.inc"
  56. #undef PREFIX
  57. static const opt::OptTable::Info InfoTable[] = {
  58. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  59. HELPTEXT, METAVAR, VALUES) \
  60. { \
  61. PREFIX, NAME, HELPTEXT, \
  62. METAVAR, OPT_##ID, opt::Option::KIND##Class, \
  63. PARAM, FLAGS, OPT_##GROUP, \
  64. OPT_##ALIAS, ALIASARGS, VALUES},
  65. #include "Opts.inc"
  66. #undef OPTION
  67. };
  68. class MLOptTable : public opt::OptTable {
  69. public:
  70. MLOptTable() : OptTable(InfoTable, /*IgnoreCase=*/false) {}
  71. };
  72. } // namespace
  73. static Triple GetTriple(StringRef ProgName, opt::InputArgList &Args) {
  74. // Figure out the target triple.
  75. StringRef DefaultBitness = "32";
  76. SmallString<255> Program = ProgName;
  77. sys::path::replace_extension(Program, "");
  78. if (Program.endswith("ml64"))
  79. DefaultBitness = "64";
  80. StringRef TripleName =
  81. StringSwitch<StringRef>(Args.getLastArgValue(OPT_bitness, DefaultBitness))
  82. .Case("32", "i386-pc-windows")
  83. .Case("64", "x86_64-pc-windows")
  84. .Default("");
  85. return Triple(Triple::normalize(TripleName));
  86. }
  87. static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path) {
  88. std::error_code EC;
  89. auto Out = std::make_unique<ToolOutputFile>(Path, EC, sys::fs::F_None);
  90. if (EC) {
  91. WithColor::error() << EC.message() << '\n';
  92. return nullptr;
  93. }
  94. return Out;
  95. }
  96. static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, raw_ostream &OS) {
  97. AsmLexer Lexer(MAI);
  98. Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
  99. Lexer.setLexMasmIntegers(true);
  100. Lexer.useMasmDefaultRadix(true);
  101. Lexer.setLexMasmHexFloats(true);
  102. Lexer.setLexMasmStrings(true);
  103. bool Error = false;
  104. while (Lexer.Lex().isNot(AsmToken::Eof)) {
  105. Lexer.getTok().dump(OS);
  106. OS << "\n";
  107. if (Lexer.getTok().getKind() == AsmToken::Error)
  108. Error = true;
  109. }
  110. return Error;
  111. }
  112. static int AssembleInput(StringRef ProgName, const Target *TheTarget,
  113. SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
  114. MCAsmInfo &MAI, MCSubtargetInfo &STI,
  115. MCInstrInfo &MCII, MCTargetOptions &MCOptions,
  116. const opt::ArgList &InputArgs) {
  117. std::unique_ptr<MCAsmParser> Parser(
  118. createMCMasmParser(SrcMgr, Ctx, Str, MAI, 0));
  119. std::unique_ptr<MCTargetAsmParser> TAP(
  120. TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
  121. if (!TAP) {
  122. WithColor::error(errs(), ProgName)
  123. << "this target does not support assembly parsing.\n";
  124. return 1;
  125. }
  126. Parser->setShowParsedOperands(InputArgs.hasArg(OPT_show_inst_operands));
  127. Parser->setTargetParser(*TAP);
  128. Parser->getLexer().setLexMasmIntegers(true);
  129. Parser->getLexer().useMasmDefaultRadix(true);
  130. Parser->getLexer().setLexMasmHexFloats(true);
  131. Parser->getLexer().setLexMasmStrings(true);
  132. auto Defines = InputArgs.getAllArgValues(OPT_define);
  133. for (StringRef Define : Defines) {
  134. const auto NameValue = Define.split('=');
  135. StringRef Name = NameValue.first, Value = NameValue.second;
  136. if (Parser->defineMacro(Name, Value)) {
  137. WithColor::error(errs(), ProgName)
  138. << "can't define macro '" << Name << "' = '" << Value << "'\n";
  139. return 1;
  140. }
  141. }
  142. int Res = Parser->Run(/*NoInitialTextSection=*/true);
  143. return Res;
  144. }
  145. int main(int Argc, char **Argv) {
  146. InitLLVM X(Argc, Argv);
  147. StringRef ProgName = sys::path::filename(Argv[0]);
  148. // Initialize targets and assembly printers/parsers.
  149. llvm::InitializeAllTargetInfos();
  150. llvm::InitializeAllTargetMCs();
  151. llvm::InitializeAllAsmParsers();
  152. llvm::InitializeAllDisassemblers();
  153. MLOptTable T;
  154. unsigned MissingArgIndex, MissingArgCount;
  155. ArrayRef<const char *> ArgsArr = makeArrayRef(Argv + 1, Argc - 1);
  156. opt::InputArgList InputArgs =
  157. T.ParseArgs(ArgsArr, MissingArgIndex, MissingArgCount);
  158. std::string InputFilename;
  159. for (auto *Arg : InputArgs.filtered(OPT_INPUT)) {
  160. std::string ArgString = Arg->getAsString(InputArgs);
  161. if (ArgString == "-" || StringRef(ArgString).endswith(".asm")) {
  162. if (!InputFilename.empty()) {
  163. WithColor::warning(errs(), ProgName)
  164. << "does not support multiple assembly files in one command; "
  165. << "ignoring '" << InputFilename << "'\n";
  166. }
  167. InputFilename = ArgString;
  168. } else {
  169. std::string Diag;
  170. raw_string_ostream OS(Diag);
  171. OS << "invalid option '" << ArgString << "'";
  172. std::string Nearest;
  173. if (T.findNearest(ArgString, Nearest) < 2)
  174. OS << ", did you mean '" << Nearest << "'?";
  175. WithColor::error(errs(), ProgName) << OS.str() << '\n';
  176. exit(1);
  177. }
  178. }
  179. for (auto *Arg : InputArgs.filtered(OPT_assembly_file)) {
  180. if (!InputFilename.empty()) {
  181. WithColor::warning(errs(), ProgName)
  182. << "does not support multiple assembly files in one command; "
  183. << "ignoring '" << InputFilename << "'\n";
  184. }
  185. InputFilename = Arg->getAsString(InputArgs);
  186. }
  187. for (auto *Arg : InputArgs.filtered(OPT_unsupported_Group)) {
  188. WithColor::warning(errs(), ProgName)
  189. << "ignoring unsupported '" << Arg->getOption().getName()
  190. << "' option\n";
  191. }
  192. if (InputArgs.hasArg(OPT_help)) {
  193. std::string Usage = llvm::formatv("{0} [ /options ] file", ProgName).str();
  194. T.PrintHelp(outs(), Usage.c_str(), "LLVM MASM Assembler",
  195. /*ShowHidden=*/false);
  196. return 0;
  197. } else if (InputFilename.empty()) {
  198. outs() << "USAGE: " << ProgName << " [ /options ] file\n"
  199. << "Run \"" << ProgName << " /?\" or \"" << ProgName
  200. << " /help\" for more info.\n";
  201. return 0;
  202. }
  203. MCTargetOptions MCOptions;
  204. MCOptions.AssemblyLanguage = "masm";
  205. Triple TheTriple = GetTriple(ProgName, InputArgs);
  206. std::string Error;
  207. const Target *TheTarget = TargetRegistry::lookupTarget("", TheTriple, Error);
  208. if (!TheTarget) {
  209. WithColor::error(errs(), ProgName) << Error;
  210. return 1;
  211. }
  212. const std::string &TripleName = TheTriple.getTriple();
  213. bool SafeSEH = InputArgs.hasArg(OPT_safeseh);
  214. if (SafeSEH && !(TheTriple.isArch32Bit() && TheTriple.isX86())) {
  215. WithColor::warning()
  216. << "/safeseh applies only to 32-bit X86 platforms; ignoring.\n";
  217. SafeSEH = false;
  218. }
  219. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
  220. MemoryBuffer::getFileOrSTDIN(InputFilename);
  221. if (std::error_code EC = BufferPtr.getError()) {
  222. WithColor::error(errs(), ProgName)
  223. << InputFilename << ": " << EC.message() << '\n';
  224. return 1;
  225. }
  226. SourceMgr SrcMgr;
  227. // Tell SrcMgr about this buffer, which is what the parser will pick up.
  228. SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
  229. // Record the location of the include directories so that the lexer can find
  230. // it later.
  231. SrcMgr.setIncludeDirs(InputArgs.getAllArgValues(OPT_include_path));
  232. std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
  233. assert(MRI && "Unable to create target register info!");
  234. std::unique_ptr<MCAsmInfo> MAI(
  235. TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
  236. assert(MAI && "Unable to create target asm info!");
  237. MAI->setPreserveAsmComments(InputArgs.hasArg(OPT_preserve_comments));
  238. // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
  239. // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
  240. MCObjectFileInfo MOFI;
  241. MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
  242. MOFI.InitMCObjectFileInfo(TheTriple, /*PIC=*/false, Ctx,
  243. /*LargeCodeModel=*/true);
  244. if (InputArgs.hasArg(OPT_save_temp_labels))
  245. Ctx.setAllowTemporaryLabels(false);
  246. // Set compilation information.
  247. SmallString<128> CWD;
  248. if (!sys::fs::current_path(CWD))
  249. Ctx.setCompilationDir(CWD);
  250. Ctx.setMainFileName(InputFilename);
  251. StringRef FileType = InputArgs.getLastArgValue(OPT_filetype, "obj");
  252. SmallString<255> DefaultOutputFilename;
  253. if (InputArgs.hasArg(OPT_as_lex)) {
  254. DefaultOutputFilename = "-";
  255. } else {
  256. DefaultOutputFilename = InputFilename;
  257. sys::path::replace_extension(DefaultOutputFilename, FileType);
  258. }
  259. const StringRef OutputFilename =
  260. InputArgs.getLastArgValue(OPT_output_file, DefaultOutputFilename);
  261. std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename);
  262. if (!Out)
  263. return 1;
  264. std::unique_ptr<buffer_ostream> BOS;
  265. raw_pwrite_stream *OS = &Out->os();
  266. std::unique_ptr<MCStreamer> Str;
  267. std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
  268. assert(MCII && "Unable to create instruction info!");
  269. std::unique_ptr<MCSubtargetInfo> STI(TheTarget->createMCSubtargetInfo(
  270. TripleName, /*CPU=*/"", /*Features=*/""));
  271. assert(STI && "Unable to create subtarget info!");
  272. MCInstPrinter *IP = nullptr;
  273. if (FileType == "s") {
  274. const bool OutputATTAsm = InputArgs.hasArg(OPT_output_att_asm);
  275. const unsigned OutputAsmVariant = OutputATTAsm ? 0U // ATT dialect
  276. : 1U; // Intel dialect
  277. IP = TheTarget->createMCInstPrinter(TheTriple, OutputAsmVariant, *MAI,
  278. *MCII, *MRI);
  279. if (!IP) {
  280. WithColor::error()
  281. << "unable to create instruction printer for target triple '"
  282. << TheTriple.normalize() << "' with "
  283. << (OutputATTAsm ? "ATT" : "Intel") << " assembly variant.\n";
  284. return 1;
  285. }
  286. // Set the display preference for hex vs. decimal immediates.
  287. IP->setPrintImmHex(InputArgs.hasArg(OPT_print_imm_hex));
  288. // Set up the AsmStreamer.
  289. std::unique_ptr<MCCodeEmitter> CE;
  290. if (InputArgs.hasArg(OPT_show_encoding))
  291. CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
  292. std::unique_ptr<MCAsmBackend> MAB(
  293. TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
  294. auto FOut = std::make_unique<formatted_raw_ostream>(*OS);
  295. Str.reset(TheTarget->createAsmStreamer(
  296. Ctx, std::move(FOut), /*asmverbose*/ true,
  297. /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB),
  298. InputArgs.hasArg(OPT_show_inst)));
  299. } else if (FileType == "null") {
  300. Str.reset(TheTarget->createNullStreamer(Ctx));
  301. } else if (FileType == "obj") {
  302. if (!Out->os().supportsSeeking()) {
  303. BOS = std::make_unique<buffer_ostream>(Out->os());
  304. OS = BOS.get();
  305. }
  306. MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
  307. MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
  308. Str.reset(TheTarget->createMCObjectStreamer(
  309. TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB),
  310. MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(CE), *STI,
  311. MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
  312. /*DWARFMustBeAtTheEnd*/ false));
  313. } else {
  314. llvm_unreachable("Invalid file type!");
  315. }
  316. if (TheTriple.isOSBinFormatCOFF()) {
  317. // Emit an absolute @feat.00 symbol. This is a features bitfield read by
  318. // link.exe.
  319. int64_t Feat00Flags = 0x2;
  320. if (SafeSEH) {
  321. // According to the PE-COFF spec, the LSB of this value marks the object
  322. // for "registered SEH". This means that all SEH handler entry points
  323. // must be registered in .sxdata. Use of any unregistered handlers will
  324. // cause the process to terminate immediately.
  325. Feat00Flags |= 0x1;
  326. }
  327. MCSymbol *Feat00Sym = Ctx.getOrCreateSymbol("@feat.00");
  328. Feat00Sym->setRedefinable(true);
  329. Str->emitSymbolAttribute(Feat00Sym, MCSA_Global);
  330. Str->emitAssignment(Feat00Sym, MCConstantExpr::create(Feat00Flags, Ctx));
  331. }
  332. // Use Assembler information for parsing.
  333. Str->setUseAssemblerInfoForParsing(true);
  334. int Res = 1;
  335. if (InputArgs.hasArg(OPT_as_lex)) {
  336. // -as-lex; Lex only, and output a stream of tokens
  337. Res = AsLexInput(SrcMgr, *MAI, Out->os());
  338. } else {
  339. Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
  340. *MCII, MCOptions, InputArgs);
  341. }
  342. // Keep output if no errors.
  343. if (Res == 0)
  344. Out->keep();
  345. return Res;
  346. }