llvm-ml.cpp 15 KB

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