aboutsummaryrefslogtreecommitdiff
path: root/backend/lib/Target/RISCV/RISCVAssemblyPrinter.cpp
blob: 85f4617be62e0432fc7525af185c87cf55f9bb81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// SPDX-License-Identifier: GPL-3.0-or-later

#include "rcc/Target/RISCV/RISCVAssemblyPrinter.h"

#include "RISCVAsmPrinter.h"
#include "RISCVTargetObjectFile.h"
#include "rcc/CodeGen/AsmPrinter.h"
#include "rcc/CodeGen/CompilationUnit.h"
#include "rcc/CodeGen/MachineFunction.h"
#include "rcc/CodeGen/MachineMCContext.h"
#include "rcc/IR/DataLayout.h"
#include "rcc/MC/MCContext.h"
#include "rcc/MC/MCStreamer.h"
#include "rcc/Target/RISCV/RISCVMCTargetLowering.h"
#include "rcc/Target/RISCV/RISCVTarget.h"

#include <string>
#include <utility>

namespace rcc::riscv {
namespace {

[[nodiscard]] AsmPrinterOptions printerOptions(AssemblyEmissionOptions Options) noexcept {
  return AsmPrinterOptions{
      .EmitFunctionDirectives = Options.EmitFunctionDirectives,
      .EmitCFI = Options.EmitCFI,
      .EmitBlockLabels = Options.EmitBlockLabels,
      .EmitInstructionSymbols = true,
      .VerifyInput = Options.VerifyInput,
  };
}

} // namespace

Expected<std::string> emitAssembly(const CompilationUnit &Unit, const TargetDescription &Target,
                                   AssemblyEmissionOptions Options) {
  mc::MCContext MCContext;
  MachineMCContext MachineContext(MCContext);
  RISCVMCTargetLowering Lowering(Target);
  RISCVELFTargetObjectFile ObjectFile;
  auto Layout = DataLayout::parse(TargetDataLayout);
  if (!Layout)
    return std::unexpected(Layout.error());
  mc::AsmTextStreamer Streamer(Lowering.instructionPrinter());
  RISCVAsmPrinter Printer(Target, Lowering, ObjectFile, std::move(*Layout), MachineContext,
                          Streamer, printerOptions(Options));
  auto Emitted = Printer.emitCompilationUnit(Unit);
  if (!Emitted)
    return std::unexpected(Emitted.error());
  return Streamer.takeOutput();
}

Expected<std::string> emitAssembly(const MachineFunction &Function, const TargetDescription &Target,
                                   AssemblyEmissionOptions Options) {
  mc::MCContext MCContext;
  MachineMCContext MachineContext(MCContext);
  RISCVMCTargetLowering Lowering(Target);
  RISCVELFTargetObjectFile ObjectFile;
  auto Layout = DataLayout::parse(TargetDataLayout);
  if (!Layout)
    return std::unexpected(Layout.error());
  mc::AsmTextStreamer Streamer(Lowering.instructionPrinter());
  RISCVAsmPrinter Printer(Target, Lowering, ObjectFile, std::move(*Layout), MachineContext,
                          Streamer, printerOptions(Options));
  auto Emitted = Printer.emitFunction(Function);
  if (!Emitted)
    return std::unexpected(Emitted.error());
  return Streamer.takeOutput();
}

} // namespace rcc::riscv