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