1//===-- LlvmState.cpp -------------------------------------------*- 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#include "LlvmState.h"
10#include "Target.h"
11#include "llvm/ADT/SmallVector.h"
12#include "llvm/MC/MCCodeEmitter.h"
13#include "llvm/MC/MCContext.h"
14#include "llvm/MC/MCFixup.h"
15#include "llvm/MC/MCObjectFileInfo.h"
16#include "llvm/MC/TargetRegistry.h"
17#include "llvm/Target/TargetMachine.h"
18#include "llvm/Target/TargetOptions.h"
19#include "llvm/TargetParser/Host.h"
20
21namespace llvm {
22namespace exegesis {
23
24Expected<LLVMState>
25LLVMState::create(const cl::LibraryOptionsContext &LibraryOptions,
26 std::string TripleName, std::string CpuName,
27 const StringRef Features, bool UseDummyPerfCounters) {
28 if (TripleName.empty())
29 TripleName = Triple::normalize(Str: sys::getDefaultTargetTriple());
30
31 Triple TheTriple(TripleName);
32
33 // Get the target specific parser.
34 std::string Error;
35 const Target *TheTarget =
36 TargetRegistry::lookupTarget(/*MArch=*/ArchName: "", TheTriple, Error);
37 if (!TheTarget) {
38 return make_error<StringError>(Args: "no LLVM target for triple " + TripleName,
39 Args: inconvertibleErrorCode());
40 }
41
42 // Update Triple with the updated triple from the target lookup.
43 TripleName = TheTriple.str();
44
45 if (CpuName == "native") {
46 // case for cross generating, when native arch and target mismatch
47 if ((Triple(sys::getProcessTriple()).getArch() !=
48 Triple(TripleName).getArch()))
49 return make_error<StringError>(
50 Args: "A CPU must be explicitly specified when cross compiling. To see all "
51 "possible options for " +
52 TripleName + " triple use -mcpu=help",
53 Args: inconvertibleErrorCode());
54 CpuName = std::string(sys::getHostCPUName());
55 }
56
57 std::unique_ptr<MCSubtargetInfo> STI(
58 TheTarget->createMCSubtargetInfo(TheTriple, CPU: CpuName, Features: ""));
59 if (!STI) {
60 return make_error<StringError>(Args: "unable to create subtarget info",
61 Args: inconvertibleErrorCode());
62 }
63
64 assert(STI && "Unable to create subtarget info!");
65 if (!STI->isCPUStringValid(CPU: CpuName)) {
66 return make_error<StringError>(Args: Twine("invalid CPU name (")
67 .concat(Suffix: CpuName)
68 .concat(Suffix: ") for triple ")
69 .concat(Suffix: TripleName),
70 Args: inconvertibleErrorCode());
71 }
72 TargetOptions Options;
73 Options.MCOptions.LibraryOptions = &LibraryOptions;
74 std::unique_ptr<const TargetMachine> TM(TheTarget->createTargetMachine(
75 TT: TheTriple, CPU: CpuName, Features, Options, RM: Reloc::Model::Static));
76 if (!TM) {
77 return make_error<StringError>(Args: "unable to create target machine",
78 Args: inconvertibleErrorCode());
79 }
80
81 const ExegesisTarget *ET =
82 TripleName.empty() ? &ExegesisTarget::getDefault()
83 : ExegesisTarget::lookup(TT: TM->getTargetTriple());
84 if (!ET) {
85 return make_error<StringError>(Args: "no Exegesis target for triple " +
86 TripleName,
87 Args: inconvertibleErrorCode());
88 }
89 const PfmCountersInfo &PCI = UseDummyPerfCounters
90 ? ET->getDummyPfmCounters()
91 : ET->getPfmCounters(CpuName);
92 return LLVMState(std::move(TM), ET, &PCI);
93}
94
95LLVMState::LLVMState(std::unique_ptr<const TargetMachine> TM,
96 const ExegesisTarget *ET, const PfmCountersInfo *PCI)
97 : TheExegesisTarget(ET), TheTargetMachine(std::move(TM)), PfmCounters(PCI),
98 OpcodeNameToOpcodeIdxMapping(createOpcodeNameToOpcodeIdxMapping()),
99 RegNameToRegNoMapping(createRegNameToRegNoMapping()) {
100 BitVector ReservedRegs = getFunctionReservedRegs(TM: getTargetMachine());
101 for (const MCPhysReg Reg : TheExegesisTarget->getUnavailableRegisters())
102 ReservedRegs.set(Reg);
103 RATC.reset(
104 p: new RegisterAliasingTrackerCache(getRegInfo(), std::move(ReservedRegs)));
105 IC.reset(
106 p: new InstructionsCache(getInstrInfo(), getRATC(), &getSubtargetInfo()));
107}
108
109std::unique_ptr<TargetMachine> LLVMState::createTargetMachine() const {
110 return std::unique_ptr<TargetMachine>(
111 TheTargetMachine->getTarget().createTargetMachine(
112 TT: Triple(TheTargetMachine->getTargetTriple().normalize()),
113 CPU: TheTargetMachine->getTargetCPU(),
114 Features: TheTargetMachine->getTargetFeatureString(), Options: TheTargetMachine->Options,
115 RM: Reloc::Model::Static));
116}
117
118std::optional<MCRegister>
119LLVMState::getRegisterNumberFromName(StringRef RegisterName) const {
120 auto RegisterIt = RegNameToRegNoMapping->find(Val: RegisterName);
121 if (RegisterIt == RegNameToRegNoMapping->end())
122 return std::nullopt;
123 return RegisterIt->second;
124}
125
126std::unique_ptr<const DenseMap<StringRef, unsigned>>
127LLVMState::createOpcodeNameToOpcodeIdxMapping() const {
128 const MCInstrInfo &InstrInfo = getInstrInfo();
129 auto Map = std::make_unique<DenseMap<StringRef, unsigned>>(
130 args: InstrInfo.getNumOpcodes());
131 for (unsigned I = 0, E = InstrInfo.getNumOpcodes(); I < E; ++I)
132 (*Map)[InstrInfo.getName(Opcode: I)] = I;
133 assert(Map->size() == InstrInfo.getNumOpcodes() && "Size prediction failed");
134 return std::move(Map);
135}
136
137std::unique_ptr<const DenseMap<StringRef, MCRegister>>
138LLVMState::createRegNameToRegNoMapping() const {
139 const MCRegisterInfo &RegInfo = getRegInfo();
140 auto Map =
141 std::make_unique<DenseMap<StringRef, MCRegister>>(args: RegInfo.getNumRegs());
142 // Special-case RegNo 0, which would otherwise be spelled as ''.
143 (*Map)[kNoRegister] = 0;
144 for (unsigned I = 1, E = RegInfo.getNumRegs(); I < E; ++I)
145 (*Map)[RegInfo.getName(RegNo: I)] = I;
146 assert(Map->size() == RegInfo.getNumRegs() && "Size prediction failed");
147 return std::move(Map);
148}
149
150bool LLVMState::canAssemble(const MCInst &Inst) const {
151 MCContext Context(TheTargetMachine->getTargetTriple(),
152 TheTargetMachine->getMCAsmInfo(),
153 TheTargetMachine->getMCRegisterInfo(),
154 TheTargetMachine->getMCSubtargetInfo());
155 std::unique_ptr<const MCCodeEmitter> CodeEmitter(
156 TheTargetMachine->getTarget().createMCCodeEmitter(
157 II: *TheTargetMachine->getMCInstrInfo(), Ctx&: Context));
158 assert(CodeEmitter && "unable to create code emitter");
159 SmallVector<char, 16> Tmp;
160 SmallVector<MCFixup, 4> Fixups;
161 CodeEmitter->encodeInstruction(Inst, CB&: Tmp, Fixups,
162 STI: TheTargetMachine->getMCSubtargetInfo());
163 return Tmp.size() > 0;
164}
165
166} // namespace exegesis
167} // namespace llvm
168