llvm-mc.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. #include "Disassembler.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/MCTargetOptionsCommandFlags.h"
  28. #include "llvm/MC/TargetRegistry.h"
  29. #include "llvm/Support/CommandLine.h"
  30. #include "llvm/Support/Compression.h"
  31. #include "llvm/Support/FileUtilities.h"
  32. #include "llvm/Support/FormattedStream.h"
  33. #include "llvm/Support/Host.h"
  34. #include "llvm/Support/InitLLVM.h"
  35. #include "llvm/Support/MemoryBuffer.h"
  36. #include "llvm/Support/SourceMgr.h"
  37. #include "llvm/Support/TargetSelect.h"
  38. #include "llvm/Support/ToolOutputFile.h"
  39. #include "llvm/Support/WithColor.h"
  40. using namespace llvm;
  41. static mc::RegisterMCTargetOptionsFlags MOF;
  42. static cl::OptionCategory MCCategory("MC Options");
  43. static cl::opt<std::string> InputFilename(cl::Positional,
  44. cl::desc("<input file>"),
  45. cl::init("-"), cl::cat(MCCategory));
  46. static cl::list<std::string>
  47. DisassemblerOptions("M", cl::desc("Disassembler options"),
  48. cl::cat(MCCategory));
  49. static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
  50. cl::value_desc("filename"),
  51. cl::init("-"), cl::cat(MCCategory));
  52. static cl::opt<std::string> SplitDwarfFile("split-dwarf-file",
  53. cl::desc("DWO output filename"),
  54. cl::value_desc("filename"),
  55. cl::cat(MCCategory));
  56. static cl::opt<bool> ShowEncoding("show-encoding",
  57. cl::desc("Show instruction encodings"),
  58. cl::cat(MCCategory));
  59. static cl::opt<bool> RelaxELFRel(
  60. "relax-relocations", cl::init(true),
  61. cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"),
  62. cl::cat(MCCategory));
  63. static cl::opt<DebugCompressionType> CompressDebugSections(
  64. "compress-debug-sections", cl::ValueOptional,
  65. cl::init(DebugCompressionType::None),
  66. cl::desc("Choose DWARF debug sections compression:"),
  67. cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
  68. clEnumValN(DebugCompressionType::Z, "zlib",
  69. "Use zlib compression"),
  70. clEnumValN(DebugCompressionType::GNU, "zlib-gnu",
  71. "Use zlib-gnu compression (deprecated)")),
  72. cl::cat(MCCategory));
  73. static cl::opt<bool>
  74. ShowInst("show-inst", cl::desc("Show internal instruction representation"),
  75. cl::cat(MCCategory));
  76. static cl::opt<bool>
  77. ShowInstOperands("show-inst-operands",
  78. cl::desc("Show instructions operands as parsed"),
  79. cl::cat(MCCategory));
  80. static cl::opt<unsigned>
  81. OutputAsmVariant("output-asm-variant",
  82. cl::desc("Syntax variant to use for output printing"),
  83. cl::cat(MCCategory));
  84. static cl::opt<bool>
  85. PrintImmHex("print-imm-hex", cl::init(false),
  86. cl::desc("Prefer hex format for immediate values"),
  87. cl::cat(MCCategory));
  88. static cl::list<std::string>
  89. DefineSymbol("defsym",
  90. cl::desc("Defines a symbol to be an integer constant"),
  91. cl::cat(MCCategory));
  92. static cl::opt<bool>
  93. PreserveComments("preserve-comments",
  94. cl::desc("Preserve Comments in outputted assembly"),
  95. cl::cat(MCCategory));
  96. enum OutputFileType {
  97. OFT_Null,
  98. OFT_AssemblyFile,
  99. OFT_ObjectFile
  100. };
  101. static cl::opt<OutputFileType>
  102. FileType("filetype", cl::init(OFT_AssemblyFile),
  103. cl::desc("Choose an output file type:"),
  104. cl::values(clEnumValN(OFT_AssemblyFile, "asm",
  105. "Emit an assembly ('.s') file"),
  106. clEnumValN(OFT_Null, "null",
  107. "Don't emit anything (for timing purposes)"),
  108. clEnumValN(OFT_ObjectFile, "obj",
  109. "Emit a native object ('.o') file")),
  110. cl::cat(MCCategory));
  111. static cl::list<std::string> IncludeDirs("I",
  112. cl::desc("Directory of include files"),
  113. cl::value_desc("directory"),
  114. cl::Prefix, cl::cat(MCCategory));
  115. static cl::opt<std::string>
  116. ArchName("arch",
  117. cl::desc("Target arch to assemble for, "
  118. "see -version for available targets"),
  119. cl::cat(MCCategory));
  120. static cl::opt<std::string>
  121. TripleName("triple",
  122. cl::desc("Target triple to assemble for, "
  123. "see -version for available targets"),
  124. cl::cat(MCCategory));
  125. static cl::opt<std::string>
  126. MCPU("mcpu",
  127. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  128. cl::value_desc("cpu-name"), cl::init(""), cl::cat(MCCategory));
  129. static cl::list<std::string>
  130. MAttrs("mattr", cl::CommaSeparated,
  131. cl::desc("Target specific attributes (-mattr=help for details)"),
  132. cl::value_desc("a1,+a2,-a3,..."), cl::cat(MCCategory));
  133. static cl::opt<bool> PIC("position-independent",
  134. cl::desc("Position independent"), cl::init(false),
  135. cl::cat(MCCategory));
  136. static cl::opt<bool>
  137. LargeCodeModel("large-code-model",
  138. cl::desc("Create cfi directives that assume the code might "
  139. "be more than 2gb away"),
  140. cl::cat(MCCategory));
  141. static cl::opt<bool>
  142. NoInitialTextSection("n",
  143. cl::desc("Don't assume assembly file starts "
  144. "in the text section"),
  145. cl::cat(MCCategory));
  146. static cl::opt<bool>
  147. GenDwarfForAssembly("g",
  148. cl::desc("Generate dwarf debugging info for assembly "
  149. "source files"),
  150. cl::cat(MCCategory));
  151. static cl::opt<std::string>
  152. DebugCompilationDir("fdebug-compilation-dir",
  153. cl::desc("Specifies the debug info's compilation dir"),
  154. cl::cat(MCCategory));
  155. static cl::list<std::string> DebugPrefixMap(
  156. "fdebug-prefix-map", cl::desc("Map file source paths in debug info"),
  157. cl::value_desc("= separated key-value pairs"), cl::cat(MCCategory));
  158. static cl::opt<std::string> MainFileName(
  159. "main-file-name",
  160. cl::desc("Specifies the name we should consider the input file"),
  161. cl::cat(MCCategory));
  162. static cl::opt<bool> SaveTempLabels("save-temp-labels",
  163. cl::desc("Don't discard temporary labels"),
  164. cl::cat(MCCategory));
  165. static cl::opt<bool> LexMasmIntegers(
  166. "masm-integers",
  167. cl::desc("Enable binary and hex masm integers (0b110 and 0ABCh)"),
  168. cl::cat(MCCategory));
  169. static cl::opt<bool> LexMasmHexFloats(
  170. "masm-hexfloats",
  171. cl::desc("Enable MASM-style hex float initializers (3F800000r)"),
  172. cl::cat(MCCategory));
  173. static cl::opt<bool> LexMotorolaIntegers(
  174. "motorola-integers",
  175. cl::desc("Enable binary and hex Motorola integers (%110 and $ABC)"),
  176. cl::cat(MCCategory));
  177. static cl::opt<bool> NoExecStack("no-exec-stack",
  178. cl::desc("File doesn't need an exec stack"),
  179. cl::cat(MCCategory));
  180. enum ActionType {
  181. AC_AsLex,
  182. AC_Assemble,
  183. AC_Disassemble,
  184. AC_MDisassemble,
  185. };
  186. static cl::opt<ActionType> Action(
  187. cl::desc("Action to perform:"), cl::init(AC_Assemble),
  188. cl::values(clEnumValN(AC_AsLex, "as-lex", "Lex tokens from a .s file"),
  189. clEnumValN(AC_Assemble, "assemble",
  190. "Assemble a .s file (default)"),
  191. clEnumValN(AC_Disassemble, "disassemble",
  192. "Disassemble strings of hex bytes"),
  193. clEnumValN(AC_MDisassemble, "mdis",
  194. "Marked up disassembly of strings of hex bytes")),
  195. cl::cat(MCCategory));
  196. static const Target *GetTarget(const char *ProgName) {
  197. // Figure out the target triple.
  198. if (TripleName.empty())
  199. TripleName = sys::getDefaultTargetTriple();
  200. Triple TheTriple(Triple::normalize(TripleName));
  201. // Get the target specific parser.
  202. std::string Error;
  203. const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
  204. Error);
  205. if (!TheTarget) {
  206. WithColor::error(errs(), ProgName) << Error;
  207. return nullptr;
  208. }
  209. // Update the triple name and return the found target.
  210. TripleName = TheTriple.getTriple();
  211. return TheTarget;
  212. }
  213. static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path,
  214. sys::fs::OpenFlags Flags) {
  215. std::error_code EC;
  216. auto Out = std::make_unique<ToolOutputFile>(Path, EC, Flags);
  217. if (EC) {
  218. WithColor::error() << EC.message() << '\n';
  219. return nullptr;
  220. }
  221. return Out;
  222. }
  223. static std::string DwarfDebugFlags;
  224. static void setDwarfDebugFlags(int argc, char **argv) {
  225. if (!getenv("RC_DEBUG_OPTIONS"))
  226. return;
  227. for (int i = 0; i < argc; i++) {
  228. DwarfDebugFlags += argv[i];
  229. if (i + 1 < argc)
  230. DwarfDebugFlags += " ";
  231. }
  232. }
  233. static std::string DwarfDebugProducer;
  234. static void setDwarfDebugProducer() {
  235. if(!getenv("DEBUG_PRODUCER"))
  236. return;
  237. DwarfDebugProducer += getenv("DEBUG_PRODUCER");
  238. }
  239. static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
  240. raw_ostream &OS) {
  241. AsmLexer Lexer(MAI);
  242. Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
  243. bool Error = false;
  244. while (Lexer.Lex().isNot(AsmToken::Eof)) {
  245. Lexer.getTok().dump(OS);
  246. OS << "\n";
  247. if (Lexer.getTok().getKind() == AsmToken::Error)
  248. Error = true;
  249. }
  250. return Error;
  251. }
  252. static int fillCommandLineSymbols(MCAsmParser &Parser) {
  253. for (auto &I: DefineSymbol) {
  254. auto Pair = StringRef(I).split('=');
  255. auto Sym = Pair.first;
  256. auto Val = Pair.second;
  257. if (Sym.empty() || Val.empty()) {
  258. WithColor::error() << "defsym must be of the form: sym=value: " << I
  259. << "\n";
  260. return 1;
  261. }
  262. int64_t Value;
  263. if (Val.getAsInteger(0, Value)) {
  264. WithColor::error() << "value is not an integer: " << Val << "\n";
  265. return 1;
  266. }
  267. Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
  268. }
  269. return 0;
  270. }
  271. static int AssembleInput(const char *ProgName, const Target *TheTarget,
  272. SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
  273. MCAsmInfo &MAI, MCSubtargetInfo &STI,
  274. MCInstrInfo &MCII, MCTargetOptions const &MCOptions) {
  275. std::unique_ptr<MCAsmParser> Parser(
  276. createMCAsmParser(SrcMgr, Ctx, Str, MAI));
  277. std::unique_ptr<MCTargetAsmParser> TAP(
  278. TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
  279. if (!TAP) {
  280. WithColor::error(errs(), ProgName)
  281. << "this target does not support assembly parsing.\n";
  282. return 1;
  283. }
  284. int SymbolResult = fillCommandLineSymbols(*Parser);
  285. if(SymbolResult)
  286. return SymbolResult;
  287. Parser->setShowParsedOperands(ShowInstOperands);
  288. Parser->setTargetParser(*TAP);
  289. Parser->getLexer().setLexMasmIntegers(LexMasmIntegers);
  290. Parser->getLexer().setLexMasmHexFloats(LexMasmHexFloats);
  291. Parser->getLexer().setLexMotorolaIntegers(LexMotorolaIntegers);
  292. int Res = Parser->Run(NoInitialTextSection);
  293. return Res;
  294. }
  295. int main(int argc, char **argv) {
  296. InitLLVM X(argc, argv);
  297. // Initialize targets and assembly printers/parsers.
  298. llvm::InitializeAllTargetInfos();
  299. llvm::InitializeAllTargetMCs();
  300. llvm::InitializeAllAsmParsers();
  301. llvm::InitializeAllDisassemblers();
  302. // Register the target printer for --version.
  303. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  304. cl::HideUnrelatedOptions({&MCCategory, &getColorCategory()});
  305. cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
  306. const MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
  307. setDwarfDebugFlags(argc, argv);
  308. setDwarfDebugProducer();
  309. const char *ProgName = argv[0];
  310. const Target *TheTarget = GetTarget(ProgName);
  311. if (!TheTarget)
  312. return 1;
  313. // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
  314. // construct the Triple object.
  315. Triple TheTriple(TripleName);
  316. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
  317. MemoryBuffer::getFileOrSTDIN(InputFilename, /*IsText=*/true);
  318. if (std::error_code EC = BufferPtr.getError()) {
  319. WithColor::error(errs(), ProgName)
  320. << InputFilename << ": " << EC.message() << '\n';
  321. return 1;
  322. }
  323. MemoryBuffer *Buffer = BufferPtr->get();
  324. SourceMgr SrcMgr;
  325. // Tell SrcMgr about this buffer, which is what the parser will pick up.
  326. SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
  327. // Record the location of the include directories so that the lexer can find
  328. // it later.
  329. SrcMgr.setIncludeDirs(IncludeDirs);
  330. std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
  331. assert(MRI && "Unable to create target register info!");
  332. std::unique_ptr<MCAsmInfo> MAI(
  333. TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
  334. assert(MAI && "Unable to create target asm info!");
  335. MAI->setRelaxELFRelocations(RelaxELFRel);
  336. if (CompressDebugSections != DebugCompressionType::None) {
  337. if (!zlib::isAvailable()) {
  338. WithColor::error(errs(), ProgName)
  339. << "build tools with zlib to enable -compress-debug-sections";
  340. return 1;
  341. }
  342. MAI->setCompressDebugSections(CompressDebugSections);
  343. }
  344. MAI->setPreserveAsmComments(PreserveComments);
  345. // Package up features to be passed to target/subtarget
  346. std::string FeaturesStr;
  347. if (MAttrs.size()) {
  348. SubtargetFeatures Features;
  349. for (unsigned i = 0; i != MAttrs.size(); ++i)
  350. Features.AddFeature(MAttrs[i]);
  351. FeaturesStr = Features.getString();
  352. }
  353. std::unique_ptr<MCSubtargetInfo> STI(
  354. TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
  355. assert(STI && "Unable to create subtarget info!");
  356. // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
  357. // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
  358. MCContext Ctx(TheTriple, MAI.get(), MRI.get(), STI.get(), &SrcMgr,
  359. &MCOptions);
  360. std::unique_ptr<MCObjectFileInfo> MOFI(
  361. TheTarget->createMCObjectFileInfo(Ctx, PIC, LargeCodeModel));
  362. Ctx.setObjectFileInfo(MOFI.get());
  363. if (SaveTempLabels)
  364. Ctx.setAllowTemporaryLabels(false);
  365. Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
  366. // Default to 4 for dwarf version.
  367. unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
  368. if (DwarfVersion < 2 || DwarfVersion > 5) {
  369. errs() << ProgName << ": Dwarf version " << DwarfVersion
  370. << " is not supported." << '\n';
  371. return 1;
  372. }
  373. Ctx.setDwarfVersion(DwarfVersion);
  374. if (MCOptions.Dwarf64) {
  375. // The 64-bit DWARF format was introduced in DWARFv3.
  376. if (DwarfVersion < 3) {
  377. errs() << ProgName
  378. << ": the 64-bit DWARF format is not supported for DWARF versions "
  379. "prior to 3\n";
  380. return 1;
  381. }
  382. // 32-bit targets don't support DWARF64, which requires 64-bit relocations.
  383. if (MAI->getCodePointerSize() < 8) {
  384. errs() << ProgName
  385. << ": the 64-bit DWARF format is only supported for 64-bit "
  386. "targets\n";
  387. return 1;
  388. }
  389. // If needsDwarfSectionOffsetDirective is true, we would eventually call
  390. // MCStreamer::emitSymbolValue() with IsSectionRelative = true, but that
  391. // is supported only for 4-byte long references.
  392. if (MAI->needsDwarfSectionOffsetDirective()) {
  393. errs() << ProgName << ": the 64-bit DWARF format is not supported for "
  394. << TheTriple.normalize() << "\n";
  395. return 1;
  396. }
  397. Ctx.setDwarfFormat(dwarf::DWARF64);
  398. }
  399. if (!DwarfDebugFlags.empty())
  400. Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
  401. if (!DwarfDebugProducer.empty())
  402. Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
  403. if (!DebugCompilationDir.empty())
  404. Ctx.setCompilationDir(DebugCompilationDir);
  405. else {
  406. // If no compilation dir is set, try to use the current directory.
  407. SmallString<128> CWD;
  408. if (!sys::fs::current_path(CWD))
  409. Ctx.setCompilationDir(CWD);
  410. }
  411. for (const auto &Arg : DebugPrefixMap) {
  412. const auto &KV = StringRef(Arg).split('=');
  413. Ctx.addDebugPrefixMapEntry(std::string(KV.first), std::string(KV.second));
  414. }
  415. if (!MainFileName.empty())
  416. Ctx.setMainFileName(MainFileName);
  417. if (GenDwarfForAssembly)
  418. Ctx.setGenDwarfRootFile(InputFilename, Buffer->getBuffer());
  419. sys::fs::OpenFlags Flags = (FileType == OFT_AssemblyFile)
  420. ? sys::fs::OF_TextWithCRLF
  421. : sys::fs::OF_None;
  422. std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename, Flags);
  423. if (!Out)
  424. return 1;
  425. std::unique_ptr<ToolOutputFile> DwoOut;
  426. if (!SplitDwarfFile.empty()) {
  427. if (FileType != OFT_ObjectFile) {
  428. WithColor::error() << "dwo output only supported with object files\n";
  429. return 1;
  430. }
  431. DwoOut = GetOutputStream(SplitDwarfFile, sys::fs::OF_None);
  432. if (!DwoOut)
  433. return 1;
  434. }
  435. std::unique_ptr<buffer_ostream> BOS;
  436. raw_pwrite_stream *OS = &Out->os();
  437. std::unique_ptr<MCStreamer> Str;
  438. std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
  439. assert(MCII && "Unable to create instruction info!");
  440. MCInstPrinter *IP = nullptr;
  441. if (FileType == OFT_AssemblyFile) {
  442. IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
  443. *MAI, *MCII, *MRI);
  444. if (!IP) {
  445. WithColor::error()
  446. << "unable to create instruction printer for target triple '"
  447. << TheTriple.normalize() << "' with assembly variant "
  448. << OutputAsmVariant << ".\n";
  449. return 1;
  450. }
  451. for (StringRef Opt : DisassemblerOptions)
  452. if (!IP->applyTargetSpecificCLOption(Opt)) {
  453. WithColor::error() << "invalid disassembler option '" << Opt << "'\n";
  454. return 1;
  455. }
  456. // Set the display preference for hex vs. decimal immediates.
  457. IP->setPrintImmHex(PrintImmHex);
  458. // Set up the AsmStreamer.
  459. std::unique_ptr<MCCodeEmitter> CE;
  460. if (ShowEncoding)
  461. CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
  462. std::unique_ptr<MCAsmBackend> MAB(
  463. TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
  464. auto FOut = std::make_unique<formatted_raw_ostream>(*OS);
  465. Str.reset(
  466. TheTarget->createAsmStreamer(Ctx, std::move(FOut), /*asmverbose*/ true,
  467. /*useDwarfDirectory*/ true, IP,
  468. std::move(CE), std::move(MAB), ShowInst));
  469. } else if (FileType == OFT_Null) {
  470. Str.reset(TheTarget->createNullStreamer(Ctx));
  471. } else {
  472. assert(FileType == OFT_ObjectFile && "Invalid file type!");
  473. if (!Out->os().supportsSeeking()) {
  474. BOS = std::make_unique<buffer_ostream>(Out->os());
  475. OS = BOS.get();
  476. }
  477. MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
  478. MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
  479. Str.reset(TheTarget->createMCObjectStreamer(
  480. TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB),
  481. DwoOut ? MAB->createDwoObjectWriter(*OS, DwoOut->os())
  482. : MAB->createObjectWriter(*OS),
  483. std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
  484. MCOptions.MCIncrementalLinkerCompatible,
  485. /*DWARFMustBeAtTheEnd*/ false));
  486. if (NoExecStack)
  487. Str->initSections(true, *STI);
  488. }
  489. // Use Assembler information for parsing.
  490. Str->setUseAssemblerInfoForParsing(true);
  491. int Res = 1;
  492. bool disassemble = false;
  493. switch (Action) {
  494. case AC_AsLex:
  495. Res = AsLexInput(SrcMgr, *MAI, Out->os());
  496. break;
  497. case AC_Assemble:
  498. Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
  499. *MCII, MCOptions);
  500. break;
  501. case AC_MDisassemble:
  502. assert(IP && "Expected assembly output");
  503. IP->setUseMarkup(true);
  504. disassemble = true;
  505. break;
  506. case AC_Disassemble:
  507. disassemble = true;
  508. break;
  509. }
  510. if (disassemble)
  511. Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str, *Buffer,
  512. SrcMgr, Ctx, Out->os(), MCOptions);
  513. // Keep output if no errors.
  514. if (Res == 0) {
  515. Out->keep();
  516. if (DwoOut)
  517. DwoOut->keep();
  518. }
  519. return Res;
  520. }