1//===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- 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// This utility is a simple driver that allows command line hacking on machine
10// code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Disassembler.h"
15#include "llvm/ADT/ScopeExit.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/MC/MCAsmBackend.h"
18#include "llvm/MC/MCAsmInfo.h"
19#include "llvm/MC/MCCodeEmitter.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCInstPrinter.h"
22#include "llvm/MC/MCInstrInfo.h"
23#include "llvm/MC/MCLFI.h"
24#include "llvm/MC/MCObjectFileInfo.h"
25#include "llvm/MC/MCObjectWriter.h"
26#include "llvm/MC/MCParser/AsmLexer.h"
27#include "llvm/MC/MCParser/MCTargetAsmParser.h"
28#include "llvm/MC/MCRegisterInfo.h"
29#include "llvm/MC/MCStreamer.h"
30#include "llvm/MC/MCSubtargetInfo.h"
31#include "llvm/MC/MCTargetOptionsCommandFlags.h"
32#include "llvm/MC/TargetRegistry.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Compression.h"
35#include "llvm/Support/FormattedStream.h"
36#include "llvm/Support/InitLLVM.h"
37#include "llvm/Support/LibraryOptionsContext.h"
38#include "llvm/Support/MemoryBuffer.h"
39#include "llvm/Support/SourceMgr.h"
40#include "llvm/Support/SourceMgrDiagnosticVerifier.h"
41#include "llvm/Support/TargetSelect.h"
42#include "llvm/Support/TimeProfiler.h"
43#include "llvm/Support/ToolOutputFile.h"
44#include "llvm/Support/VirtualFileSystem.h"
45#include "llvm/Support/WithColor.h"
46#include "llvm/TargetParser/Host.h"
47#include <memory>
48#include <optional>
49
50using namespace llvm;
51
52static cl::OptionCategory MCCategory("MC Options");
53
54static cl::opt<std::string> InputFilename(cl::Positional,
55 cl::desc("<input file>"),
56 cl::init(Val: "-"), cl::cat(MCCategory));
57
58static cl::list<std::string> InstPrinterOptions("M",
59 cl::desc("InstPrinter options"),
60 cl::cat(MCCategory));
61
62static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
63 cl::value_desc("filename"),
64 cl::init(Val: "-"), cl::cat(MCCategory));
65
66static cl::opt<std::string> SplitDwarfFile("split-dwarf-file",
67 cl::desc("DWO output filename"),
68 cl::value_desc("filename"),
69 cl::cat(MCCategory));
70
71static cl::opt<bool> ShowEncoding("show-encoding",
72 cl::desc("Show instruction encodings"),
73 cl::cat(MCCategory));
74
75static cl::opt<DebugCompressionType> CompressDebugSections(
76 "compress-debug-sections", cl::ValueOptional,
77 cl::init(Val: DebugCompressionType::None),
78 cl::desc("Choose DWARF debug sections compression:"),
79 cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
80 clEnumValN(DebugCompressionType::Zlib, "zlib", "Use zlib"),
81 clEnumValN(DebugCompressionType::Zstd, "zstd", "Use zstd")),
82 cl::cat(MCCategory));
83
84static cl::opt<bool>
85 ShowInst("show-inst", cl::desc("Show internal instruction representation"),
86 cl::cat(MCCategory));
87
88static cl::opt<bool>
89 ShowInstOperands("show-inst-operands",
90 cl::desc("Show instructions operands as parsed"),
91 cl::cat(MCCategory));
92
93static cl::opt<unsigned>
94 OutputAsmVariant("output-asm-variant",
95 cl::desc("Syntax variant to use for output printing"),
96 cl::cat(MCCategory));
97
98static cl::opt<bool>
99 PrintImmHex("print-imm-hex", cl::init(Val: false),
100 cl::desc("Prefer hex format for immediate values"),
101 cl::cat(MCCategory));
102
103static cl::opt<bool>
104 HexBytes("hex",
105 cl::desc("Take raw hexadecimal bytes as input for disassembly. "
106 "Whitespace is ignored"),
107 cl::cat(MCCategory));
108
109static cl::list<std::string>
110 DefineSymbol("defsym",
111 cl::desc("Defines a symbol to be an integer constant"),
112 cl::cat(MCCategory));
113
114static cl::opt<bool>
115 PreserveComments("preserve-comments",
116 cl::desc("Preserve Comments in outputted assembly"),
117 cl::cat(MCCategory));
118
119static cl::opt<unsigned> CommentColumn("comment-column",
120 cl::desc("Asm comments indentation"),
121 cl::init(Val: 40));
122
123enum OutputFileType {
124 OFT_Null,
125 OFT_AssemblyFile,
126 OFT_ObjectFile
127};
128static cl::opt<OutputFileType>
129 FileType("filetype", cl::init(Val: OFT_AssemblyFile),
130 cl::desc("Choose an output file type:"),
131 cl::values(clEnumValN(OFT_AssemblyFile, "asm",
132 "Emit an assembly ('.s') file"),
133 clEnumValN(OFT_Null, "null",
134 "Don't emit anything (for timing purposes)"),
135 clEnumValN(OFT_ObjectFile, "obj",
136 "Emit a native object ('.o') file")),
137 cl::cat(MCCategory));
138
139static cl::list<std::string> IncludeDirs("I",
140 cl::desc("Directory of include files"),
141 cl::value_desc("directory"),
142 cl::Prefix, cl::cat(MCCategory));
143
144static cl::opt<std::string>
145 ArchName("arch",
146 cl::desc("Target arch to assemble for, "
147 "see -version for available targets"),
148 cl::cat(MCCategory));
149
150static cl::opt<std::string>
151 TripleName("triple",
152 cl::desc("Target triple to assemble for, "
153 "see -version for available targets"),
154 cl::cat(MCCategory));
155
156static cl::opt<std::string>
157 MCPU("mcpu",
158 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
159 cl::value_desc("cpu-name"), cl::init(Val: ""), cl::cat(MCCategory));
160
161static cl::list<std::string>
162 MAttrs("mattr", cl::CommaSeparated,
163 cl::desc("Target specific attributes (-mattr=help for details)"),
164 cl::value_desc("a1,+a2,-a3,..."), cl::cat(MCCategory));
165
166static cl::opt<bool> PIC("position-independent",
167 cl::desc("Position independent"), cl::init(Val: false),
168 cl::cat(MCCategory));
169
170static cl::opt<bool>
171 LargeCodeModel("large-code-model",
172 cl::desc("Create cfi directives that assume the code might "
173 "be more than 2gb away"),
174 cl::cat(MCCategory));
175
176static cl::opt<bool>
177 NoInitialTextSection("n",
178 cl::desc("Don't assume assembly file starts "
179 "in the text section"),
180 cl::cat(MCCategory));
181
182static cl::opt<bool>
183 GenDwarfForAssembly("g",
184 cl::desc("Generate dwarf debugging info for assembly "
185 "source files"),
186 cl::cat(MCCategory));
187
188static cl::opt<std::string>
189 DebugCompilationDir("fdebug-compilation-dir",
190 cl::desc("Specifies the debug info's compilation dir"),
191 cl::cat(MCCategory));
192
193static cl::list<std::string> DebugPrefixMap(
194 "fdebug-prefix-map", cl::desc("Map file source paths in debug info"),
195 cl::value_desc("= separated key-value pairs"), cl::cat(MCCategory));
196
197static cl::opt<std::string> MainFileName(
198 "main-file-name",
199 cl::desc("Specifies the name we should consider the input file"),
200 cl::cat(MCCategory));
201
202static cl::opt<bool> LexMasmIntegers(
203 "masm-integers",
204 cl::desc("Enable binary and hex masm integers (0b110 and 0ABCh)"),
205 cl::cat(MCCategory));
206
207static cl::opt<bool> LexMasmHexFloats(
208 "masm-hexfloats",
209 cl::desc("Enable MASM-style hex float initializers (3F800000r)"),
210 cl::cat(MCCategory));
211
212static cl::opt<bool> LexMotorolaIntegers(
213 "motorola-integers",
214 cl::desc("Enable binary and hex Motorola integers (%110 and $ABC)"),
215 cl::cat(MCCategory));
216
217static cl::opt<bool> NoExecStack("no-exec-stack",
218 cl::desc("File doesn't need an exec stack"),
219 cl::cat(MCCategory));
220
221static cl::list<std::string>
222 Verify("verify", cl::CommaSeparated, cl::ValueOptional,
223 cl::desc("Check diagnostics against '<prefix>-<kind>' comments in "
224 "the input (default prefix: 'expected')"),
225 cl::value_desc("prefixes"), cl::cat(MCCategory));
226
227enum ActionType {
228 AC_AsLex,
229 AC_Assemble,
230 AC_Disassemble,
231 AC_MDisassemble,
232 AC_CDisassemble,
233};
234
235static cl::opt<ActionType> Action(
236 cl::desc("Action to perform:"), cl::init(Val: AC_Assemble),
237 cl::values(clEnumValN(AC_AsLex, "as-lex", "Lex tokens from a .s file"),
238 clEnumValN(AC_Assemble, "assemble",
239 "Assemble a .s file (default)"),
240 clEnumValN(AC_Disassemble, "disassemble",
241 "Disassemble strings of hex bytes"),
242 clEnumValN(AC_MDisassemble, "mdis",
243 "Marked up disassembly of strings of hex bytes"),
244 clEnumValN(AC_CDisassemble, "cdis",
245 "Colored disassembly of strings of hex bytes")),
246 cl::cat(MCCategory));
247
248static cl::opt<unsigned>
249 NumBenchmarkRuns("runs", cl::desc("Number of runs for benchmarking"),
250 cl::cat(MCCategory));
251
252static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));
253
254static cl::opt<unsigned> TimeTraceGranularity(
255 "time-trace-granularity",
256 cl::desc(
257 "Minimum time granularity (in microseconds) traced by time profiler"),
258 cl::init(Val: 500), cl::Hidden);
259
260static cl::opt<std::string>
261 TimeTraceFile("time-trace-file",
262 cl::desc("Specify time trace file destination"),
263 cl::value_desc("filename"));
264
265static const Target *GetTarget(const char *ProgName) {
266 // Figure out the target triple.
267 if (TripleName.empty())
268 TripleName = sys::getDefaultTargetTriple();
269 Triple TheTriple(Triple::normalize(Str: TripleName));
270
271 // Get the target specific parser.
272 std::string Error;
273 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
274 Error);
275 if (!TheTarget) {
276 WithColor::error(OS&: errs(), Prefix: ProgName) << Error;
277 return nullptr;
278 }
279
280 // Update the triple name and return the found target.
281 TripleName = TheTriple.getTriple();
282 return TheTarget;
283}
284
285static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path,
286 sys::fs::OpenFlags Flags) {
287 std::error_code EC;
288 auto Out = std::make_unique<ToolOutputFile>(args&: Path, args&: EC, args&: Flags);
289 if (EC) {
290 WithColor::error() << EC.message() << '\n';
291 return nullptr;
292 }
293
294 return Out;
295}
296
297static std::string DwarfDebugFlags;
298static void setDwarfDebugFlags(int argc, char **argv) {
299 if (!getenv(name: "RC_DEBUG_OPTIONS"))
300 return;
301 for (int i = 0; i < argc; i++) {
302 DwarfDebugFlags += argv[i];
303 if (i + 1 < argc)
304 DwarfDebugFlags += " ";
305 }
306}
307
308static std::string DwarfDebugProducer;
309static void setDwarfDebugProducer() {
310 if(!getenv(name: "DEBUG_PRODUCER"))
311 return;
312 DwarfDebugProducer += getenv(name: "DEBUG_PRODUCER");
313}
314
315static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
316 raw_ostream &OS) {
317
318 AsmLexer Lexer(MAI);
319 Lexer.setBuffer(Buf: SrcMgr.getMemoryBuffer(i: SrcMgr.getMainFileID())->getBuffer());
320
321 bool Error = false;
322 while (Lexer.Lex().isNot(K: AsmToken::Eof)) {
323 Lexer.getTok().dump(OS);
324 OS << "\n";
325 if (Lexer.getTok().getKind() == AsmToken::Error)
326 Error = true;
327 }
328
329 return Error;
330}
331
332static int fillCommandLineSymbols(MCAsmParser &Parser) {
333 for (auto &I: DefineSymbol) {
334 auto Pair = StringRef(I).split(Separator: '=');
335 auto Sym = Pair.first;
336 auto Val = Pair.second;
337
338 if (Sym.empty() || Val.empty()) {
339 Parser.getSourceManager().PrintMessage(
340 Loc: SMLoc(), Kind: SourceMgr::DK_Error,
341 Msg: "defsym must be of the form: sym=value: " + I);
342 return 1;
343 }
344 int64_t Value;
345 if (Val.getAsInteger(Radix: 0, Result&: Value)) {
346 Parser.getSourceManager().PrintMessage(Loc: SMLoc(), Kind: SourceMgr::DK_Error,
347 Msg: "value is not an integer: " + Val);
348 return 1;
349 }
350 Parser.getContext().setSymbolValue(Streamer&: Parser.getStreamer(), Sym, Val: Value);
351 }
352 return 0;
353}
354
355static int AssembleInput(const Target *TheTarget, SourceMgr &SrcMgr,
356 MCContext &Ctx, MCStreamer &Str, MCAsmInfo &MAI,
357 MCSubtargetInfo &STI, MCInstrInfo &MCII,
358 MCTargetOptions const &MCOptions) {
359 std::unique_ptr<MCAsmParser> Parser(
360 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
361 std::unique_ptr<MCTargetAsmParser> TAP(
362 TheTarget->createMCAsmParser(STI, Parser&: *Parser, MII: MCII));
363
364 if (!TAP) {
365 SrcMgr.PrintMessage(Loc: SMLoc(), Kind: SourceMgr::DK_Error,
366 Msg: "this target does not support assembly parsing.");
367 return 1;
368 }
369
370 int SymbolResult = fillCommandLineSymbols(Parser&: *Parser);
371 if(SymbolResult)
372 return SymbolResult;
373 Parser->setShowParsedOperands(ShowInstOperands);
374 Parser->setTargetParser(*TAP);
375 Parser->getLexer().setLexMasmIntegers(LexMasmIntegers);
376 Parser->getLexer().setLexMasmHexFloats(LexMasmHexFloats);
377 Parser->getLexer().setLexMotorolaIntegers(LexMotorolaIntegers);
378
379 int Res = Parser->Run(NoInitialTextSection);
380
381 return Res;
382}
383
384int main(int argc, char **argv) {
385 InitLLVM X(argc, argv);
386
387 // Initialize targets and assembly printers/parsers.
388 llvm::InitializeAllTargetInfos();
389 llvm::InitializeAllTargetMCs();
390 llvm::InitializeAllAsmParsers();
391 llvm::InitializeAllDisassemblers();
392
393 // Register the target printer for --version.
394 cl::AddExtraVersionPrinter(func: TargetRegistry::printRegisteredTargetsForVersion);
395
396 cl::HideUnrelatedOptions(Categories: {&MCCategory, &getColorCategory()});
397 cl::LibraryOptionsContext LibraryOptions;
398 cl::parseCommandLineOptions(Context&: LibraryOptions, ToolOptions: mc::getToolOptions(),
399 Args: ArrayRef(argv, argc),
400 Overview: "llvm machine code playground\n");
401
402 if (TimeTrace)
403 timeTraceProfilerInitialize(TimeTraceGranularity, ProcName: argv[0]);
404
405 llvm::scope_exit TimeTraceScopeExit([]() {
406 if (!TimeTrace)
407 return;
408 if (auto E = timeTraceProfilerWrite(PreferredFileName: TimeTraceFile, FallbackFileName: OutputFilename)) {
409 logAllUnhandledErrors(E: std::move(E), OS&: errs());
410 return;
411 }
412 timeTraceProfilerCleanup();
413 });
414
415 MCTargetOptions MCOptions = mc::getMCTargetOptions(C: LibraryOptions);
416 MCOptions.CompressDebugSections = CompressDebugSections.getValue();
417 MCOptions.ShowMCInst = ShowInst;
418 MCOptions.AsmVerbose = true;
419 MCOptions.MCNoExecStack = NoExecStack;
420 MCOptions.MCUseDwarfDirectory = MCTargetOptions::EnableDwarfDirectory;
421 MCOptions.InstPrinterOptions = InstPrinterOptions;
422 if (OutputAsmVariant.getNumOccurrences())
423 MCOptions.OutputAsmVariant = OutputAsmVariant;
424
425 setDwarfDebugFlags(argc, argv);
426 setDwarfDebugProducer();
427
428 const char *ProgName = argv[0];
429
430 SmallVector<StringRef> VerifyPrefixes;
431 for (StringRef Prefix : Verify) {
432 if (Prefix.empty())
433 continue;
434 if (!isAlpha(C: Prefix[0]) || !all_of(Range&: Prefix, P: [](char C) {
435 return isAlnum(C) || C == '-' || C == '_';
436 })) {
437 WithColor::error(OS&: errs(), Prefix: ProgName)
438 << "invalid prefix '" << Prefix
439 << "' for --verify: prefixes must start with a letter and contain "
440 "only alphanumeric characters, hyphens and underscores\n";
441 return 1;
442 }
443 VerifyPrefixes.push_back(Elt: Prefix);
444 }
445 if (Verify.getNumOccurrences() && VerifyPrefixes.empty())
446 VerifyPrefixes.push_back(Elt: "expected");
447 // --as-lex prints lexer errors as tokens rather than reporting diagnostics,
448 // so there would be nothing to verify.
449 if (!VerifyPrefixes.empty() && Action == AC_AsLex) {
450 WithColor::error(OS&: errs(), Prefix: ProgName)
451 << "--verify is not supported with --as-lex\n";
452 return 1;
453 }
454
455 const Target *TheTarget = GetTarget(ProgName);
456 if (!TheTarget)
457 return 1;
458 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
459 // construct the Triple object.
460 Triple TheTriple(TripleName);
461
462 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
463 MemoryBuffer::getFileOrSTDIN(Filename: InputFilename, /*IsText=*/true);
464 if (std::error_code EC = BufferPtr.getError()) {
465 WithColor::error(OS&: errs(), Prefix: ProgName)
466 << InputFilename << ": " << EC.message() << '\n';
467 return 1;
468 }
469 MemoryBuffer *Buffer = BufferPtr->get();
470
471 SourceMgr SrcMgr;
472
473 // Tell SrcMgr about this buffer, which is what the parser will pick up.
474 SrcMgr.AddNewSourceBuffer(F: std::move(*BufferPtr), IncludeLoc: SMLoc());
475
476 // Record the location of the include directories so that the lexer can find
477 // it later.
478 SrcMgr.setIncludeDirs(IncludeDirs);
479 SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem());
480
481 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT: TheTriple));
482 assert(MRI && "Unable to create target register info!");
483
484 std::unique_ptr<MCAsmInfo> MAI(
485 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
486 assert(MAI && "Unable to create target asm info!");
487
488 if (CompressDebugSections != DebugCompressionType::None) {
489 if (const char *Reason = compression::getReasonIfUnsupported(
490 F: compression::formatFor(Type: CompressDebugSections))) {
491 WithColor::error(OS&: errs(), Prefix: ProgName)
492 << "--compress-debug-sections: " << Reason;
493 return 1;
494 }
495 }
496 MAI->setPreserveAsmComments(PreserveComments);
497 MAI->setCommentColumn(CommentColumn);
498
499 // Package up features to be passed to target/subtarget
500 SubtargetFeatures Features;
501 std::string FeaturesStr;
502
503 // Replace -mcpu=native with Host CPU and features.
504 if (MCPU == "native") {
505 MCPU = std::string(llvm::sys::getHostCPUName());
506
507 llvm::StringMap<bool> TargetFeatures = llvm::sys::getHostCPUFeatures();
508 for (auto const &[FeatureName, IsSupported] : TargetFeatures)
509 Features.AddFeature(String: FeatureName, Enable: IsSupported);
510 }
511
512 // Handle features passed to target/subtarget.
513 for (unsigned i = 0; i != MAttrs.size(); ++i)
514 Features.AddFeature(String: MAttrs[i]);
515 FeaturesStr = Features.getString();
516
517 std::unique_ptr<MCSubtargetInfo> STI(
518 TheTarget->createMCSubtargetInfo(TheTriple, CPU: MCPU, Features: FeaturesStr));
519 if (!STI) {
520 WithColor::error(OS&: errs(), Prefix: ProgName) << "unable to create subtarget info\n";
521 return 1;
522 }
523
524 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
525 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
526 MCContext Ctx(TheTriple, *MAI, *MRI, *STI, &SrcMgr);
527 std::unique_ptr<MCObjectFileInfo> MOFI(
528 TheTarget->createMCObjectFileInfo(Ctx, PIC, LargeCodeModel));
529 Ctx.setObjectFileInfo(MOFI.get());
530
531 std::optional<SourceMgrDiagnosticVerifier> Verifier;
532 if (!VerifyPrefixes.empty()) {
533 Verifier.emplace(args&: VerifyPrefixes);
534 // Scan the input up front so that its directives are checked even if it
535 // produces no diagnostics.
536 (void)Verifier->computeExpectedDiags(os&: errs(), mgr&: SrcMgr,
537 buf: SrcMgr.getMemoryBuffer(i: 1));
538 // Most diagnostics are reported through SrcMgr, but some (e.g. from the
539 // CFI checker) are only reported through Ctx, so route both to Ctx.
540 Ctx.setDiagnosticHandler([&](const SMDiagnostic &Diag, bool,
541 const SourceMgr &,
542 std::vector<const MDNode *> &) {
543 SMLoc Loc = Diag.getLoc();
544 const MemoryBuffer *Buf = nullptr;
545 if (unsigned ID = Loc.isValid() ? SrcMgr.FindBufferContainingLoc(Loc) : 0)
546 Buf = SrcMgr.getMemoryBuffer(i: ID);
547 // SMDiagnostic columns are 0-based, but printed (and written in
548 // directives) as 1-based.
549 if (Verifier->process(os&: errs(), mgr&: SrcMgr, kind: Diag.getKind(), hasLoc: Loc.isValid(), buf: Buf,
550 lineNo: Diag.getLineNo(), colNo: Diag.getColumnNo() + 1,
551 message: Diag.getMessage()) !=
552 SourceMgrDiagnosticVerifier::MatchResult::Unexpected)
553 return;
554 SourceMgrDiagnosticVerifier::printMessage(
555 os&: errs(), mgr: SrcMgr, loc: Buf ? Loc : SMLoc(),
556 msg: "unexpected " +
557 SourceMgrDiagnosticVerifier::getDiagKindStr(kind: Diag.getKind()) +
558 ": " + Diag.getMessage());
559 });
560 SrcMgr.setDiagHandler(
561 DH: [](const SMDiagnostic &Diag, void *Ctx) {
562 static_cast<MCContext *>(Ctx)->diagnose(SMD: Diag);
563 },
564 Ctx: &Ctx);
565 }
566
567 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
568 // Default to 4 for dwarf version.
569 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
570 if (DwarfVersion < 2 || DwarfVersion > 6) {
571 errs() << ProgName << ": Dwarf version " << DwarfVersion
572 << " is not supported." << '\n';
573 return 1;
574 }
575 Ctx.setDwarfVersion(DwarfVersion);
576 if (MCOptions.Dwarf64) {
577 // The 64-bit DWARF format was introduced in DWARFv3.
578 if (DwarfVersion < 3) {
579 errs() << ProgName
580 << ": the 64-bit DWARF format is not supported for DWARF versions "
581 "prior to 3\n";
582 return 1;
583 }
584 // 32-bit targets don't support DWARF64, which requires 64-bit relocations.
585 if (MAI->getCodePointerSize() < 8) {
586 errs() << ProgName
587 << ": the 64-bit DWARF format is only supported for 64-bit "
588 "targets\n";
589 return 1;
590 }
591 // If needsDwarfSectionOffsetDirective is true, we would eventually call
592 // MCStreamer::emitSymbolValue() with IsSectionRelative = true, but that
593 // is supported only for 4-byte long references.
594 if (MAI->needsDwarfSectionOffsetDirective()) {
595 errs() << ProgName << ": the 64-bit DWARF format is not supported for "
596 << TheTriple.normalize() << "\n";
597 return 1;
598 }
599 Ctx.setDwarfFormat(dwarf::DWARF64);
600 }
601 if (!DwarfDebugFlags.empty())
602 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
603 if (!DwarfDebugProducer.empty())
604 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
605 if (!DebugCompilationDir.empty())
606 Ctx.setCompilationDir(DebugCompilationDir);
607 else {
608 // If no compilation dir is set, try to use the current directory.
609 SmallString<128> CWD;
610 if (!sys::fs::current_path(result&: CWD))
611 Ctx.setCompilationDir(CWD);
612 }
613 for (const auto &Arg : DebugPrefixMap) {
614 const auto &KV = StringRef(Arg).split(Separator: '=');
615 Ctx.addDebugPrefixMapEntry(From: std::string(KV.first), To: std::string(KV.second));
616 }
617 if (!MainFileName.empty())
618 Ctx.setMainFileName(MainFileName);
619 if (GenDwarfForAssembly)
620 Ctx.setGenDwarfRootFile(FileName: InputFilename, Buffer: Buffer->getBuffer());
621
622 sys::fs::OpenFlags Flags = (FileType == OFT_AssemblyFile)
623 ? sys::fs::OF_TextWithCRLF
624 : sys::fs::OF_None;
625 std::unique_ptr<ToolOutputFile> Out = GetOutputStream(Path: OutputFilename, Flags);
626 if (!Out)
627 return 1;
628
629 std::unique_ptr<ToolOutputFile> DwoOut;
630 if (!SplitDwarfFile.empty()) {
631 if (FileType != OFT_ObjectFile) {
632 WithColor::error() << "dwo output only supported with object files\n";
633 return 1;
634 }
635 DwoOut = GetOutputStream(Path: SplitDwarfFile, Flags: sys::fs::OF_None);
636 if (!DwoOut)
637 return 1;
638 }
639
640 std::unique_ptr<buffer_ostream> BOS;
641 raw_pwrite_stream *OS = &Out->os();
642 std::unique_ptr<MCStreamer> Str;
643
644 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
645 assert(MCII && "Unable to create instruction info!");
646
647 std::unique_ptr<MCInstPrinter> IP;
648 if (FileType == OFT_AssemblyFile) {
649 unsigned AsmVariant = MAI->getOutputAssemblerDialect();
650 IP.reset(p: TheTarget->createMCInstPrinter(T: Triple(TripleName), SyntaxVariant: AsmVariant,
651 MAI: *MAI, MII: *MCII, MRI: *MRI));
652
653 if (!IP) {
654 WithColor::error()
655 << "unable to create instruction printer for target triple '"
656 << TheTriple.normalize() << "' with assembly variant " << AsmVariant
657 << "\n";
658 return 1;
659 }
660
661 for (StringRef Opt : InstPrinterOptions)
662 if (!IP->applyTargetSpecificCLOption(Opt)) {
663 WithColor::error() << "invalid InstPrinter option '" << Opt << "'\n";
664 return 1;
665 }
666
667 // Set the display preference for hex vs. decimal immediates.
668 IP->setPrintImmHex(PrintImmHex);
669
670 switch (Action) {
671 case AC_MDisassemble:
672 IP->setUseMarkup(true);
673 break;
674 case AC_CDisassemble:
675 IP->setUseColor(true);
676 break;
677 default:
678 break;
679 }
680
681 // Set up the AsmStreamer.
682 std::unique_ptr<MCCodeEmitter> CE;
683 if (ShowEncoding)
684 CE.reset(p: TheTarget->createMCCodeEmitter(II: *MCII, Ctx));
685
686 std::unique_ptr<MCAsmBackend> MAB(
687 TheTarget->createMCAsmBackend(STI: *STI, MRI: *MRI, Options: MCOptions));
688 auto FOut = std::make_unique<formatted_raw_ostream>(args&: *OS);
689 Str.reset(p: TheTarget->createAsmStreamer(Ctx, OS: std::move(FOut), IP: std::move(IP),
690 CE: std::move(CE), TAB: std::move(MAB)));
691
692 Triple T(TripleName);
693 if (T.isLFI())
694 initializeLFIMCStreamer(Streamer&: *Str.get(), Ctx, TheTriple: T);
695 } else if (FileType == OFT_Null) {
696 Str.reset(p: TheTarget->createNullStreamer(Ctx));
697 } else {
698 assert(FileType == OFT_ObjectFile && "Invalid file type!");
699
700 if (!Out->os().supportsSeeking()) {
701 BOS = std::make_unique<buffer_ostream>(args&: Out->os());
702 OS = BOS.get();
703 }
704
705 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(II: *MCII, Ctx);
706 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(STI: *STI, MRI: *MRI, Options: MCOptions);
707 Str.reset(p: TheTarget->createMCObjectStreamer(
708 T: TheTriple, Ctx, TAB: std::unique_ptr<MCAsmBackend>(MAB),
709 OW: DwoOut ? MAB->createDwoObjectWriter(OS&: *OS, DwoOS&: DwoOut->os())
710 : MAB->createObjectWriter(OS&: *OS),
711 Emitter: std::unique_ptr<MCCodeEmitter>(CE), STI: *STI));
712 Str->emitVersionForTarget(Target: TheTriple, SDKVersion: VersionTuple(), DarwinTargetVariantTriple: nullptr,
713 DarwinTargetVariantSDKVersion: VersionTuple());
714 }
715
716 int Res = 1;
717 bool disassemble = false;
718 switch (Action) {
719 case AC_AsLex:
720 Res = AsLexInput(SrcMgr, MAI&: *MAI, OS&: Out->os());
721 break;
722 case AC_Assemble:
723 Res = AssembleInput(TheTarget, SrcMgr, Ctx, Str&: *Str, MAI&: *MAI, STI&: *STI, MCII&: *MCII,
724 MCOptions);
725 break;
726 case AC_MDisassemble:
727 case AC_CDisassemble:
728 case AC_Disassemble:
729 disassemble = true;
730 break;
731 }
732 if (disassemble)
733 Res = Disassembler::disassemble(T: *TheTarget, STI&: *STI, Streamer&: *Str, Buffer&: *Buffer, SM&: SrcMgr,
734 Ctx, HexBytes, NumBenchmarkRuns);
735
736 bool Verified = !Verifier || Verifier->verify(os&: errs(), mgr&: SrcMgr);
737
738 // Keep output if no errors.
739 if (Res == 0 && Verified) {
740 Out->keep();
741 if (DwoOut)
742 DwoOut->keep();
743 }
744
745 return Verifier ? !Verified : Res;
746}
747