PseudoLoweringEmitter.cpp 13 KB

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