[ORC] Add std::tuple support to SimplePackedSerialization.
[llvm-project.git] / llvm / utils / TableGen / PseudoLoweringEmitter.cpp
blob6acb630299c121403f31f7b19df410b23ead5439
1 //===- PseudoLoweringEmitter.cpp - PseudoLowering Generator -----*- 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 //===----------------------------------------------------------------------===//
9 #include "CodeGenInstruction.h"
10 #include "CodeGenTarget.h"
11 #include "llvm/ADT/IndexedMap.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringMap.h"
14 #include "llvm/Support/Debug.h"
15 #include "llvm/Support/ErrorHandling.h"
16 #include "llvm/TableGen/Error.h"
17 #include "llvm/TableGen/Record.h"
18 #include "llvm/TableGen/TableGenBackend.h"
19 #include <vector>
20 using namespace llvm;
22 #define DEBUG_TYPE "pseudo-lowering"
24 namespace {
25 class PseudoLoweringEmitter {
26 struct OpData {
27 enum MapKind { Operand, Imm, Reg };
28 MapKind Kind;
29 union {
30 unsigned Operand; // Operand number mapped to.
31 uint64_t Imm; // Integer immedate value.
32 Record *Reg; // Physical register.
33 } Data;
35 struct PseudoExpansion {
36 CodeGenInstruction Source; // The source pseudo instruction definition.
37 CodeGenInstruction Dest; // The destination instruction to lower to.
38 IndexedMap<OpData> OperandMap;
40 PseudoExpansion(CodeGenInstruction &s, CodeGenInstruction &d,
41 IndexedMap<OpData> &m) :
42 Source(s), Dest(d), OperandMap(m) {}
45 RecordKeeper &Records;
47 // It's overkill to have an instance of the full CodeGenTarget object,
48 // but it loads everything on demand, not in the constructor, so it's
49 // lightweight in performance, so it works out OK.
50 CodeGenTarget Target;
52 SmallVector<PseudoExpansion, 64> Expansions;
54 unsigned addDagOperandMapping(Record *Rec, DagInit *Dag,
55 CodeGenInstruction &Insn,
56 IndexedMap<OpData> &OperandMap,
57 unsigned BaseIdx);
58 void evaluateExpansion(Record *Pseudo);
59 void emitLoweringEmitter(raw_ostream &o);
60 public:
61 PseudoLoweringEmitter(RecordKeeper &R) : Records(R), Target(R) {}
63 /// run - Output the pseudo-lowerings.
64 void run(raw_ostream &o);
66 } // End anonymous namespace
68 // FIXME: This pass currently can only expand a pseudo to a single instruction.
69 // The pseudo expansion really should take a list of dags, not just
70 // a single dag, so we can do fancier things.
72 unsigned PseudoLoweringEmitter::
73 addDagOperandMapping(Record *Rec, DagInit *Dag, CodeGenInstruction &Insn,
74 IndexedMap<OpData> &OperandMap, unsigned BaseIdx) {
75 unsigned OpsAdded = 0;
76 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
77 if (DefInit *DI = dyn_cast<DefInit>(Dag->getArg(i))) {
78 // Physical register reference. Explicit check for the special case
79 // "zero_reg" definition.
80 if (DI->getDef()->isSubClassOf("Register") ||
81 DI->getDef()->getName() == "zero_reg") {
82 OperandMap[BaseIdx + i].Kind = OpData::Reg;
83 OperandMap[BaseIdx + i].Data.Reg = DI->getDef();
84 ++OpsAdded;
85 continue;
88 // Normal operands should always have the same type, or we have a
89 // problem.
90 // FIXME: We probably shouldn't ever get a non-zero BaseIdx here.
91 assert(BaseIdx == 0 && "Named subargument in pseudo expansion?!");
92 // FIXME: Are the message operand types backward?
93 if (DI->getDef() != Insn.Operands[BaseIdx + i].Rec) {
94 PrintError(Rec, "In pseudo instruction '" + Rec->getName() +
95 "', operand type '" + DI->getDef()->getName() +
96 "' does not match expansion operand type '" +
97 Insn.Operands[BaseIdx + i].Rec->getName() + "'");
98 PrintFatalNote(DI->getDef(),
99 "Value was assigned at the following location:");
101 // Source operand maps to destination operand. The Data element
102 // will be filled in later, just set the Kind for now. Do it
103 // for each corresponding MachineInstr operand, not just the first.
104 for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I)
105 OperandMap[BaseIdx + i + I].Kind = OpData::Operand;
106 OpsAdded += Insn.Operands[i].MINumOperands;
107 } else if (IntInit *II = dyn_cast<IntInit>(Dag->getArg(i))) {
108 OperandMap[BaseIdx + i].Kind = OpData::Imm;
109 OperandMap[BaseIdx + i].Data.Imm = II->getValue();
110 ++OpsAdded;
111 } else if (auto *BI = dyn_cast<BitsInit>(Dag->getArg(i))) {
112 auto *II = cast<IntInit>(BI->convertInitializerTo(IntRecTy::get()));
113 OperandMap[BaseIdx + i].Kind = OpData::Imm;
114 OperandMap[BaseIdx + i].Data.Imm = II->getValue();
115 ++OpsAdded;
116 } else if (DagInit *SubDag = dyn_cast<DagInit>(Dag->getArg(i))) {
117 // Just add the operands recursively. This is almost certainly
118 // a constant value for a complex operand (> 1 MI operand).
119 unsigned NewOps =
120 addDagOperandMapping(Rec, SubDag, Insn, OperandMap, BaseIdx + i);
121 OpsAdded += NewOps;
122 // Since we added more than one, we also need to adjust the base.
123 BaseIdx += NewOps - 1;
124 } else
125 llvm_unreachable("Unhandled pseudo-expansion argument type!");
127 return OpsAdded;
130 void PseudoLoweringEmitter::evaluateExpansion(Record *Rec) {
131 LLVM_DEBUG(dbgs() << "Pseudo definition: " << Rec->getName() << "\n");
133 // Validate that the result pattern has the corrent number and types
134 // of arguments for the instruction it references.
135 DagInit *Dag = Rec->getValueAsDag("ResultInst");
136 assert(Dag && "Missing result instruction in pseudo expansion!");
137 LLVM_DEBUG(dbgs() << " Result: " << *Dag << "\n");
139 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
140 if (!OpDef) {
141 PrintError(Rec, "In pseudo instruction '" + Rec->getName() +
142 "', result operator is not a record");
143 PrintFatalNote(Rec->getValue("ResultInst"),
144 "Result was assigned at the following location:");
146 Record *Operator = OpDef->getDef();
147 if (!Operator->isSubClassOf("Instruction")) {
148 PrintError(Rec, "In pseudo instruction '" + Rec->getName() +
149 "', result operator '" + Operator->getName() +
150 "' is not an instruction");
151 PrintFatalNote(Rec->getValue("ResultInst"),
152 "Result was assigned at the following location:");
155 CodeGenInstruction Insn(Operator);
157 if (Insn.isCodeGenOnly || Insn.isPseudo) {
158 PrintError(Rec, "In pseudo instruction '" + Rec->getName() +
159 "', result operator '" + Operator->getName() +
160 "' cannot be a pseudo instruction");
161 PrintFatalNote(Rec->getValue("ResultInst"),
162 "Result was assigned at the following location:");
165 if (Insn.Operands.size() != Dag->getNumArgs()) {
166 PrintError(Rec, "In pseudo instruction '" + Rec->getName() +
167 "', result operator '" + Operator->getName() +
168 "' has the wrong number of operands");
169 PrintFatalNote(Rec->getValue("ResultInst"),
170 "Result was assigned at the following location:");
173 unsigned NumMIOperands = 0;
174 for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i)
175 NumMIOperands += Insn.Operands[i].MINumOperands;
176 IndexedMap<OpData> OperandMap;
177 OperandMap.grow(NumMIOperands);
179 addDagOperandMapping(Rec, Dag, Insn, OperandMap, 0);
181 // If there are more operands that weren't in the DAG, they have to
182 // be operands that have default values, or we have an error. Currently,
183 // Operands that are a subclass of OperandWithDefaultOp have default values.
185 // Validate that each result pattern argument has a matching (by name)
186 // argument in the source instruction, in either the (outs) or (ins) list.
187 // Also check that the type of the arguments match.
189 // Record the mapping of the source to result arguments for use by
190 // the lowering emitter.
191 CodeGenInstruction SourceInsn(Rec);
192 StringMap<unsigned> SourceOperands;
193 for (unsigned i = 0, e = SourceInsn.Operands.size(); i != e; ++i)
194 SourceOperands[SourceInsn.Operands[i].Name] = i;
196 LLVM_DEBUG(dbgs() << " Operand mapping:\n");
197 for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i) {
198 // We've already handled constant values. Just map instruction operands
199 // here.
200 if (OperandMap[Insn.Operands[i].MIOperandNo].Kind != OpData::Operand)
201 continue;
202 StringMap<unsigned>::iterator SourceOp =
203 SourceOperands.find(Dag->getArgNameStr(i));
204 if (SourceOp == SourceOperands.end()) {
205 PrintError(Rec, "In pseudo instruction '" + Rec->getName() +
206 "', output operand '" + Dag->getArgNameStr(i) +
207 "' has no matching source operand");
208 PrintFatalNote(Rec->getValue("ResultInst"),
209 "Value was assigned at the following location:");
211 // Map the source operand to the destination operand index for each
212 // MachineInstr operand.
213 for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I)
214 OperandMap[Insn.Operands[i].MIOperandNo + I].Data.Operand =
215 SourceOp->getValue();
217 LLVM_DEBUG(dbgs() << " " << SourceOp->getValue() << " ==> " << i
218 << "\n");
221 Expansions.push_back(PseudoExpansion(SourceInsn, Insn, OperandMap));
224 void PseudoLoweringEmitter::emitLoweringEmitter(raw_ostream &o) {
225 // Emit file header.
226 emitSourceFileHeader("Pseudo-instruction MC lowering Source Fragment", o);
228 o << "bool " << Target.getName() + "AsmPrinter" << "::\n"
229 << "emitPseudoExpansionLowering(MCStreamer &OutStreamer,\n"
230 << " const MachineInstr *MI) {\n";
232 if (!Expansions.empty()) {
233 o << " switch (MI->getOpcode()) {\n"
234 << " default: return false;\n";
235 for (auto &Expansion : Expansions) {
236 CodeGenInstruction &Source = Expansion.Source;
237 CodeGenInstruction &Dest = Expansion.Dest;
238 o << " case " << Source.Namespace << "::"
239 << Source.TheDef->getName() << ": {\n"
240 << " MCInst TmpInst;\n"
241 << " MCOperand MCOp;\n"
242 << " TmpInst.setOpcode(" << Dest.Namespace << "::"
243 << Dest.TheDef->getName() << ");\n";
245 // Copy the operands from the source instruction.
246 // FIXME: Instruction operands with defaults values (predicates and cc_out
247 // in ARM, for example shouldn't need explicit values in the
248 // expansion DAG.
249 unsigned MIOpNo = 0;
250 for (const auto &DestOperand : Dest.Operands) {
251 o << " // Operand: " << DestOperand.Name << "\n";
252 for (unsigned i = 0, e = DestOperand.MINumOperands; i != e; ++i) {
253 switch (Expansion.OperandMap[MIOpNo + i].Kind) {
254 case OpData::Operand:
255 o << " lowerOperand(MI->getOperand("
256 << Source.Operands[Expansion.OperandMap[MIOpNo].Data
257 .Operand].MIOperandNo + i
258 << "), MCOp);\n"
259 << " TmpInst.addOperand(MCOp);\n";
260 break;
261 case OpData::Imm:
262 o << " TmpInst.addOperand(MCOperand::createImm("
263 << Expansion.OperandMap[MIOpNo + i].Data.Imm << "));\n";
264 break;
265 case OpData::Reg: {
266 Record *Reg = Expansion.OperandMap[MIOpNo + i].Data.Reg;
267 o << " TmpInst.addOperand(MCOperand::createReg(";
268 // "zero_reg" is special.
269 if (Reg->getName() == "zero_reg")
270 o << "0";
271 else
272 o << Reg->getValueAsString("Namespace") << "::"
273 << Reg->getName();
274 o << "));\n";
275 break;
279 MIOpNo += DestOperand.MINumOperands;
281 if (Dest.Operands.isVariadic) {
282 MIOpNo = Source.Operands.size() + 1;
283 o << " // variable_ops\n";
284 o << " for (unsigned i = " << MIOpNo
285 << ", e = MI->getNumOperands(); i != e; ++i)\n"
286 << " if (lowerOperand(MI->getOperand(i), MCOp))\n"
287 << " TmpInst.addOperand(MCOp);\n";
289 o << " EmitToStreamer(OutStreamer, TmpInst);\n"
290 << " break;\n"
291 << " }\n";
293 o << " }\n return true;";
294 } else
295 o << " return false;";
297 o << "\n}\n\n";
300 void PseudoLoweringEmitter::run(raw_ostream &o) {
301 StringRef Classes[] = {"PseudoInstExpansion", "Instruction"};
302 std::vector<Record *> Insts =
303 Records.getAllDerivedDefinitions(makeArrayRef(Classes));
305 // Process the pseudo expansion definitions, validating them as we do so.
306 Records.startTimer("Process definitions");
307 for (unsigned i = 0, e = Insts.size(); i != e; ++i)
308 evaluateExpansion(Insts[i]);
310 // Generate expansion code to lower the pseudo to an MCInst of the real
311 // instruction.
312 Records.startTimer("Emit expansion code");
313 emitLoweringEmitter(o);
316 namespace llvm {
318 void EmitPseudoLowering(RecordKeeper &RK, raw_ostream &OS) {
319 PseudoLoweringEmitter(RK).run(OS);
322 } // End llvm namespace