PseudoLoweringEmitter.cpp revision 239462
1224133Sdim//===- PseudoLoweringEmitter.cpp - PseudoLowering Generator -----*- C++ -*-===//
2224133Sdim//
3224133Sdim//                     The LLVM Compiler Infrastructure
4224133Sdim//
5224133Sdim// This file is distributed under the University of Illinois Open Source
6224133Sdim// License. See LICENSE.TXT for details.
7224133Sdim//
8224133Sdim//===----------------------------------------------------------------------===//
9224133Sdim
10224133Sdim#define DEBUG_TYPE "pseudo-lowering"
11224133Sdim#include "CodeGenInstruction.h"
12239462Sdim#include "CodeGenTarget.h"
13224133Sdim#include "llvm/ADT/IndexedMap.h"
14239462Sdim#include "llvm/ADT/SmallVector.h"
15224133Sdim#include "llvm/ADT/StringMap.h"
16239462Sdim#include "llvm/Support/Debug.h"
17224133Sdim#include "llvm/Support/ErrorHandling.h"
18239462Sdim#include "llvm/TableGen/Error.h"
19239462Sdim#include "llvm/TableGen/Record.h"
20239462Sdim#include "llvm/TableGen/TableGenBackend.h"
21224133Sdim#include <vector>
22224133Sdimusing namespace llvm;
23224133Sdim
24239462Sdimnamespace {
25239462Sdimclass PseudoLoweringEmitter {
26239462Sdim  struct OpData {
27239462Sdim    enum MapKind { Operand, Imm, Reg };
28239462Sdim    MapKind Kind;
29239462Sdim    union {
30239462Sdim      unsigned Operand;   // Operand number mapped to.
31239462Sdim      uint64_t Imm;       // Integer immedate value.
32239462Sdim      Record *Reg;        // Physical register.
33239462Sdim    } Data;
34239462Sdim  };
35239462Sdim  struct PseudoExpansion {
36239462Sdim    CodeGenInstruction Source;  // The source pseudo instruction definition.
37239462Sdim    CodeGenInstruction Dest;    // The destination instruction to lower to.
38239462Sdim    IndexedMap<OpData> OperandMap;
39239462Sdim
40239462Sdim    PseudoExpansion(CodeGenInstruction &s, CodeGenInstruction &d,
41239462Sdim                    IndexedMap<OpData> &m) :
42239462Sdim      Source(s), Dest(d), OperandMap(m) {}
43239462Sdim  };
44239462Sdim
45239462Sdim  RecordKeeper &Records;
46239462Sdim
47239462Sdim  // It's overkill to have an instance of the full CodeGenTarget object,
48239462Sdim  // but it loads everything on demand, not in the constructor, so it's
49239462Sdim  // lightweight in performance, so it works out OK.
50239462Sdim  CodeGenTarget Target;
51239462Sdim
52239462Sdim  SmallVector<PseudoExpansion, 64> Expansions;
53239462Sdim
54239462Sdim  unsigned addDagOperandMapping(Record *Rec, DagInit *Dag,
55239462Sdim                                CodeGenInstruction &Insn,
56239462Sdim                                IndexedMap<OpData> &OperandMap,
57239462Sdim                                unsigned BaseIdx);
58239462Sdim  void evaluateExpansion(Record *Pseudo);
59239462Sdim  void emitLoweringEmitter(raw_ostream &o);
60239462Sdimpublic:
61239462Sdim  PseudoLoweringEmitter(RecordKeeper &R) : Records(R), Target(R) {}
62239462Sdim
63239462Sdim  /// run - Output the pseudo-lowerings.
64239462Sdim  void run(raw_ostream &o);
65239462Sdim};
66239462Sdim} // End anonymous namespace
67239462Sdim
68224133Sdim// FIXME: This pass currently can only expand a pseudo to a single instruction.
69224133Sdim//        The pseudo expansion really should take a list of dags, not just
70224133Sdim//        a single dag, so we can do fancier things.
71224133Sdim
72224133Sdimunsigned PseudoLoweringEmitter::
73224133SdimaddDagOperandMapping(Record *Rec, DagInit *Dag, CodeGenInstruction &Insn,
74224133Sdim                     IndexedMap<OpData> &OperandMap, unsigned BaseIdx) {
75224133Sdim  unsigned OpsAdded = 0;
76224133Sdim  for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
77224133Sdim    if (DefInit *DI = dynamic_cast<DefInit*>(Dag->getArg(i))) {
78224133Sdim      // Physical register reference. Explicit check for the special case
79224133Sdim      // "zero_reg" definition.
80224133Sdim      if (DI->getDef()->isSubClassOf("Register") ||
81224133Sdim          DI->getDef()->getName() == "zero_reg") {
82224133Sdim        OperandMap[BaseIdx + i].Kind = OpData::Reg;
83224133Sdim        OperandMap[BaseIdx + i].Data.Reg = DI->getDef();
84224133Sdim        ++OpsAdded;
85224133Sdim        continue;
86224133Sdim      }
87224133Sdim
88224133Sdim      // Normal operands should always have the same type, or we have a
89224133Sdim      // problem.
90224133Sdim      // FIXME: We probably shouldn't ever get a non-zero BaseIdx here.
91224133Sdim      assert(BaseIdx == 0 && "Named subargument in pseudo expansion?!");
92224133Sdim      if (DI->getDef() != Insn.Operands[BaseIdx + i].Rec)
93224133Sdim        throw TGError(Rec->getLoc(),
94224133Sdim                      "Pseudo operand type '" + DI->getDef()->getName() +
95224133Sdim                      "' does not match expansion operand type '" +
96224133Sdim                      Insn.Operands[BaseIdx + i].Rec->getName() + "'");
97224133Sdim      // Source operand maps to destination operand. The Data element
98224133Sdim      // will be filled in later, just set the Kind for now. Do it
99224133Sdim      // for each corresponding MachineInstr operand, not just the first.
100224133Sdim      for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I)
101224133Sdim        OperandMap[BaseIdx + i + I].Kind = OpData::Operand;
102224133Sdim      OpsAdded += Insn.Operands[i].MINumOperands;
103224133Sdim    } else if (IntInit *II = dynamic_cast<IntInit*>(Dag->getArg(i))) {
104224133Sdim      OperandMap[BaseIdx + i].Kind = OpData::Imm;
105224133Sdim      OperandMap[BaseIdx + i].Data.Imm = II->getValue();
106224133Sdim      ++OpsAdded;
107224133Sdim    } else if (DagInit *SubDag = dynamic_cast<DagInit*>(Dag->getArg(i))) {
108224133Sdim      // Just add the operands recursively. This is almost certainly
109224133Sdim      // a constant value for a complex operand (> 1 MI operand).
110224133Sdim      unsigned NewOps =
111224133Sdim        addDagOperandMapping(Rec, SubDag, Insn, OperandMap, BaseIdx + i);
112224133Sdim      OpsAdded += NewOps;
113224133Sdim      // Since we added more than one, we also need to adjust the base.
114224133Sdim      BaseIdx += NewOps - 1;
115224133Sdim    } else
116234353Sdim      llvm_unreachable("Unhandled pseudo-expansion argument type!");
117224133Sdim  }
118224133Sdim  return OpsAdded;
119224133Sdim}
120224133Sdim
121224133Sdimvoid PseudoLoweringEmitter::evaluateExpansion(Record *Rec) {
122224133Sdim  DEBUG(dbgs() << "Pseudo definition: " << Rec->getName() << "\n");
123224133Sdim
124224133Sdim  // Validate that the result pattern has the corrent number and types
125224133Sdim  // of arguments for the instruction it references.
126224133Sdim  DagInit *Dag = Rec->getValueAsDag("ResultInst");
127224133Sdim  assert(Dag && "Missing result instruction in pseudo expansion!");
128224133Sdim  DEBUG(dbgs() << "  Result: " << *Dag << "\n");
129224133Sdim
130224133Sdim  DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
131224133Sdim  if (!OpDef)
132224133Sdim    throw TGError(Rec->getLoc(), Rec->getName() +
133224133Sdim                  " has unexpected operator type!");
134224133Sdim  Record *Operator = OpDef->getDef();
135224133Sdim  if (!Operator->isSubClassOf("Instruction"))
136224133Sdim    throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() +
137224133Sdim                                 "' is not an instruction!");
138224133Sdim
139224133Sdim  CodeGenInstruction Insn(Operator);
140224133Sdim
141224133Sdim  if (Insn.isCodeGenOnly || Insn.isPseudo)
142224133Sdim    throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() +
143224133Sdim                                 "' cannot be another pseudo instruction!");
144224133Sdim
145224133Sdim  if (Insn.Operands.size() != Dag->getNumArgs())
146224133Sdim    throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() +
147224133Sdim                                 "' operand count mismatch");
148224133Sdim
149234353Sdim  unsigned NumMIOperands = 0;
150234353Sdim  for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i)
151234353Sdim    NumMIOperands += Insn.Operands[i].MINumOperands;
152224133Sdim  IndexedMap<OpData> OperandMap;
153234353Sdim  OperandMap.grow(NumMIOperands);
154224133Sdim
155224133Sdim  addDagOperandMapping(Rec, Dag, Insn, OperandMap, 0);
156224133Sdim
157224133Sdim  // If there are more operands that weren't in the DAG, they have to
158224133Sdim  // be operands that have default values, or we have an error. Currently,
159224133Sdim  // PredicateOperand and OptionalDefOperand both have default values.
160224133Sdim
161224133Sdim
162224133Sdim  // Validate that each result pattern argument has a matching (by name)
163224133Sdim  // argument in the source instruction, in either the (outs) or (ins) list.
164224133Sdim  // Also check that the type of the arguments match.
165224133Sdim  //
166224133Sdim  // Record the mapping of the source to result arguments for use by
167224133Sdim  // the lowering emitter.
168224133Sdim  CodeGenInstruction SourceInsn(Rec);
169224133Sdim  StringMap<unsigned> SourceOperands;
170224133Sdim  for (unsigned i = 0, e = SourceInsn.Operands.size(); i != e; ++i)
171224133Sdim    SourceOperands[SourceInsn.Operands[i].Name] = i;
172224133Sdim
173224133Sdim  DEBUG(dbgs() << "  Operand mapping:\n");
174224133Sdim  for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i) {
175224133Sdim    // We've already handled constant values. Just map instruction operands
176224133Sdim    // here.
177224133Sdim    if (OperandMap[Insn.Operands[i].MIOperandNo].Kind != OpData::Operand)
178224133Sdim      continue;
179224133Sdim    StringMap<unsigned>::iterator SourceOp =
180224133Sdim      SourceOperands.find(Dag->getArgName(i));
181224133Sdim    if (SourceOp == SourceOperands.end())
182224133Sdim      throw TGError(Rec->getLoc(),
183224133Sdim                    "Pseudo output operand '" + Dag->getArgName(i) +
184224133Sdim                    "' has no matching source operand.");
185224133Sdim    // Map the source operand to the destination operand index for each
186224133Sdim    // MachineInstr operand.
187224133Sdim    for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I)
188224133Sdim      OperandMap[Insn.Operands[i].MIOperandNo + I].Data.Operand =
189224133Sdim        SourceOp->getValue();
190224133Sdim
191224133Sdim    DEBUG(dbgs() << "    " << SourceOp->getValue() << " ==> " << i << "\n");
192224133Sdim  }
193224133Sdim
194224133Sdim  Expansions.push_back(PseudoExpansion(SourceInsn, Insn, OperandMap));
195224133Sdim}
196224133Sdim
197224133Sdimvoid PseudoLoweringEmitter::emitLoweringEmitter(raw_ostream &o) {
198224133Sdim  // Emit file header.
199239462Sdim  emitSourceFileHeader("Pseudo-instruction MC lowering Source Fragment", o);
200224133Sdim
201224133Sdim  o << "bool " << Target.getName() + "AsmPrinter" << "::\n"
202224133Sdim    << "emitPseudoExpansionLowering(MCStreamer &OutStreamer,\n"
203224133Sdim    << "                            const MachineInstr *MI) {\n"
204224133Sdim    << "  switch (MI->getOpcode()) {\n"
205224133Sdim    << "    default: return false;\n";
206224133Sdim  for (unsigned i = 0, e = Expansions.size(); i != e; ++i) {
207224133Sdim    PseudoExpansion &Expansion = Expansions[i];
208224133Sdim    CodeGenInstruction &Source = Expansion.Source;
209224133Sdim    CodeGenInstruction &Dest = Expansion.Dest;
210224133Sdim    o << "    case " << Source.Namespace << "::"
211224133Sdim      << Source.TheDef->getName() << ": {\n"
212224133Sdim      << "      MCInst TmpInst;\n"
213224133Sdim      << "      MCOperand MCOp;\n"
214224133Sdim      << "      TmpInst.setOpcode(" << Dest.Namespace << "::"
215224133Sdim      << Dest.TheDef->getName() << ");\n";
216224133Sdim
217224133Sdim    // Copy the operands from the source instruction.
218224133Sdim    // FIXME: Instruction operands with defaults values (predicates and cc_out
219224133Sdim    //        in ARM, for example shouldn't need explicit values in the
220224133Sdim    //        expansion DAG.
221224133Sdim    unsigned MIOpNo = 0;
222224133Sdim    for (unsigned OpNo = 0, E = Dest.Operands.size(); OpNo != E;
223224133Sdim         ++OpNo) {
224224133Sdim      o << "      // Operand: " << Dest.Operands[OpNo].Name << "\n";
225224133Sdim      for (unsigned i = 0, e = Dest.Operands[OpNo].MINumOperands;
226224133Sdim           i != e; ++i) {
227224133Sdim        switch (Expansion.OperandMap[MIOpNo + i].Kind) {
228224133Sdim        case OpData::Operand:
229224133Sdim          o << "      lowerOperand(MI->getOperand("
230224133Sdim            << Source.Operands[Expansion.OperandMap[MIOpNo].Data
231224133Sdim                .Operand].MIOperandNo + i
232224133Sdim            << "), MCOp);\n"
233224133Sdim            << "      TmpInst.addOperand(MCOp);\n";
234224133Sdim          break;
235224133Sdim        case OpData::Imm:
236224133Sdim          o << "      TmpInst.addOperand(MCOperand::CreateImm("
237224133Sdim            << Expansion.OperandMap[MIOpNo + i].Data.Imm << "));\n";
238224133Sdim          break;
239224133Sdim        case OpData::Reg: {
240224133Sdim          Record *Reg = Expansion.OperandMap[MIOpNo + i].Data.Reg;
241224133Sdim          o << "      TmpInst.addOperand(MCOperand::CreateReg(";
242224133Sdim          // "zero_reg" is special.
243224133Sdim          if (Reg->getName() == "zero_reg")
244224133Sdim            o << "0";
245224133Sdim          else
246224133Sdim            o << Reg->getValueAsString("Namespace") << "::" << Reg->getName();
247224133Sdim          o << "));\n";
248224133Sdim          break;
249224133Sdim        }
250224133Sdim        }
251224133Sdim      }
252224133Sdim      MIOpNo += Dest.Operands[OpNo].MINumOperands;
253224133Sdim    }
254224133Sdim    if (Dest.Operands.isVariadic) {
255224133Sdim      o << "      // variable_ops\n";
256224133Sdim      o << "      for (unsigned i = " << MIOpNo
257224133Sdim        << ", e = MI->getNumOperands(); i != e; ++i)\n"
258224133Sdim        << "        if (lowerOperand(MI->getOperand(i), MCOp))\n"
259224133Sdim        << "          TmpInst.addOperand(MCOp);\n";
260224133Sdim    }
261224133Sdim    o << "      OutStreamer.EmitInstruction(TmpInst);\n"
262224133Sdim      << "      break;\n"
263224133Sdim      << "    }\n";
264224133Sdim  }
265224133Sdim  o << "  }\n  return true;\n}\n\n";
266224133Sdim}
267224133Sdim
268224133Sdimvoid PseudoLoweringEmitter::run(raw_ostream &o) {
269224133Sdim  Record *ExpansionClass = Records.getClass("PseudoInstExpansion");
270224133Sdim  Record *InstructionClass = Records.getClass("PseudoInstExpansion");
271224133Sdim  assert(ExpansionClass && "PseudoInstExpansion class definition missing!");
272224133Sdim  assert(InstructionClass && "Instruction class definition missing!");
273224133Sdim
274224133Sdim  std::vector<Record*> Insts;
275224133Sdim  for (std::map<std::string, Record*>::const_iterator I =
276224133Sdim         Records.getDefs().begin(), E = Records.getDefs().end(); I != E; ++I) {
277224133Sdim    if (I->second->isSubClassOf(ExpansionClass) &&
278224133Sdim        I->second->isSubClassOf(InstructionClass))
279224133Sdim      Insts.push_back(I->second);
280224133Sdim  }
281224133Sdim
282224133Sdim  // Process the pseudo expansion definitions, validating them as we do so.
283224133Sdim  for (unsigned i = 0, e = Insts.size(); i != e; ++i)
284224133Sdim    evaluateExpansion(Insts[i]);
285224133Sdim
286224133Sdim  // Generate expansion code to lower the pseudo to an MCInst of the real
287224133Sdim  // instruction.
288224133Sdim  emitLoweringEmitter(o);
289224133Sdim}
290224133Sdim
291239462Sdimnamespace llvm {
292239462Sdim
293239462Sdimvoid EmitPseudoLowering(RecordKeeper &RK, raw_ostream &OS) {
294239462Sdim  PseudoLoweringEmitter(RK).run(OS);
295239462Sdim}
296239462Sdim
297239462Sdim} // End llvm namespace
298