Move TableGen's parser and entry point into a library
[oota-llvm.git] / utils / TableGen / PseudoLoweringEmitter.cpp
1 //===- PseudoLoweringEmitter.cpp - PseudoLowering Generator -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #define DEBUG_TYPE "pseudo-lowering"
11 #include "CodeGenInstruction.h"
12 #include "PseudoLoweringEmitter.h"
13 #include "llvm/TableGen/Error.h"
14 #include "llvm/TableGen/Record.h"
15 #include "llvm/ADT/IndexedMap.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/Debug.h"
19 #include <vector>
20 using namespace llvm;
21
22 // FIXME: This pass currently can only expand a pseudo to a single instruction.
23 //        The pseudo expansion really should take a list of dags, not just
24 //        a single dag, so we can do fancier things.
25
26 unsigned PseudoLoweringEmitter::
27 addDagOperandMapping(Record *Rec, DagInit *Dag, CodeGenInstruction &Insn,
28                      IndexedMap<OpData> &OperandMap, unsigned BaseIdx) {
29   unsigned OpsAdded = 0;
30   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
31     if (DefInit *DI = dynamic_cast<DefInit*>(Dag->getArg(i))) {
32       // Physical register reference. Explicit check for the special case
33       // "zero_reg" definition.
34       if (DI->getDef()->isSubClassOf("Register") ||
35           DI->getDef()->getName() == "zero_reg") {
36         OperandMap[BaseIdx + i].Kind = OpData::Reg;
37         OperandMap[BaseIdx + i].Data.Reg = DI->getDef();
38         ++OpsAdded;
39         continue;
40       }
41
42       // Normal operands should always have the same type, or we have a
43       // problem.
44       // FIXME: We probably shouldn't ever get a non-zero BaseIdx here.
45       assert(BaseIdx == 0 && "Named subargument in pseudo expansion?!");
46       if (DI->getDef() != Insn.Operands[BaseIdx + i].Rec)
47         throw TGError(Rec->getLoc(),
48                       "Pseudo operand type '" + DI->getDef()->getName() +
49                       "' does not match expansion operand type '" +
50                       Insn.Operands[BaseIdx + i].Rec->getName() + "'");
51       // Source operand maps to destination operand. The Data element
52       // will be filled in later, just set the Kind for now. Do it
53       // for each corresponding MachineInstr operand, not just the first.
54       for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I)
55         OperandMap[BaseIdx + i + I].Kind = OpData::Operand;
56       OpsAdded += Insn.Operands[i].MINumOperands;
57     } else if (IntInit *II = dynamic_cast<IntInit*>(Dag->getArg(i))) {
58       OperandMap[BaseIdx + i].Kind = OpData::Imm;
59       OperandMap[BaseIdx + i].Data.Imm = II->getValue();
60       ++OpsAdded;
61     } else if (DagInit *SubDag = dynamic_cast<DagInit*>(Dag->getArg(i))) {
62       // Just add the operands recursively. This is almost certainly
63       // a constant value for a complex operand (> 1 MI operand).
64       unsigned NewOps =
65         addDagOperandMapping(Rec, SubDag, Insn, OperandMap, BaseIdx + i);
66       OpsAdded += NewOps;
67       // Since we added more than one, we also need to adjust the base.
68       BaseIdx += NewOps - 1;
69     } else
70       assert(0 && "Unhandled pseudo-expansion argument type!");
71   }
72   return OpsAdded;
73 }
74
75 void PseudoLoweringEmitter::evaluateExpansion(Record *Rec) {
76   DEBUG(dbgs() << "Pseudo definition: " << Rec->getName() << "\n");
77
78   // Validate that the result pattern has the corrent number and types
79   // of arguments for the instruction it references.
80   DagInit *Dag = Rec->getValueAsDag("ResultInst");
81   assert(Dag && "Missing result instruction in pseudo expansion!");
82   DEBUG(dbgs() << "  Result: " << *Dag << "\n");
83
84   DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
85   if (!OpDef)
86     throw TGError(Rec->getLoc(), Rec->getName() +
87                   " has unexpected operator type!");
88   Record *Operator = OpDef->getDef();
89   if (!Operator->isSubClassOf("Instruction"))
90     throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() +
91                                  "' is not an instruction!");
92
93   CodeGenInstruction Insn(Operator);
94
95   if (Insn.isCodeGenOnly || Insn.isPseudo)
96     throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() +
97                                  "' cannot be another pseudo instruction!");
98
99   if (Insn.Operands.size() != Dag->getNumArgs())
100     throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() +
101                                  "' operand count mismatch");
102
103   IndexedMap<OpData> OperandMap;
104   OperandMap.grow(Insn.Operands.size());
105
106   addDagOperandMapping(Rec, Dag, Insn, OperandMap, 0);
107
108   // If there are more operands that weren't in the DAG, they have to
109   // be operands that have default values, or we have an error. Currently,
110   // PredicateOperand and OptionalDefOperand both have default values.
111
112
113   // Validate that each result pattern argument has a matching (by name)
114   // argument in the source instruction, in either the (outs) or (ins) list.
115   // Also check that the type of the arguments match.
116   //
117   // Record the mapping of the source to result arguments for use by
118   // the lowering emitter.
119   CodeGenInstruction SourceInsn(Rec);
120   StringMap<unsigned> SourceOperands;
121   for (unsigned i = 0, e = SourceInsn.Operands.size(); i != e; ++i)
122     SourceOperands[SourceInsn.Operands[i].Name] = i;
123
124   DEBUG(dbgs() << "  Operand mapping:\n");
125   for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i) {
126     // We've already handled constant values. Just map instruction operands
127     // here.
128     if (OperandMap[Insn.Operands[i].MIOperandNo].Kind != OpData::Operand)
129       continue;
130     StringMap<unsigned>::iterator SourceOp =
131       SourceOperands.find(Dag->getArgName(i));
132     if (SourceOp == SourceOperands.end())
133       throw TGError(Rec->getLoc(),
134                     "Pseudo output operand '" + Dag->getArgName(i) +
135                     "' has no matching source operand.");
136     // Map the source operand to the destination operand index for each
137     // MachineInstr operand.
138     for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I)
139       OperandMap[Insn.Operands[i].MIOperandNo + I].Data.Operand =
140         SourceOp->getValue();
141
142     DEBUG(dbgs() << "    " << SourceOp->getValue() << " ==> " << i << "\n");
143   }
144
145   Expansions.push_back(PseudoExpansion(SourceInsn, Insn, OperandMap));
146 }
147
148 void PseudoLoweringEmitter::emitLoweringEmitter(raw_ostream &o) {
149   // Emit file header.
150   EmitSourceFileHeader("Pseudo-instruction MC lowering Source Fragment", o);
151
152   o << "bool " << Target.getName() + "AsmPrinter" << "::\n"
153     << "emitPseudoExpansionLowering(MCStreamer &OutStreamer,\n"
154     << "                            const MachineInstr *MI) {\n"
155     << "  switch (MI->getOpcode()) {\n"
156     << "    default: return false;\n";
157   for (unsigned i = 0, e = Expansions.size(); i != e; ++i) {
158     PseudoExpansion &Expansion = Expansions[i];
159     CodeGenInstruction &Source = Expansion.Source;
160     CodeGenInstruction &Dest = Expansion.Dest;
161     o << "    case " << Source.Namespace << "::"
162       << Source.TheDef->getName() << ": {\n"
163       << "      MCInst TmpInst;\n"
164       << "      MCOperand MCOp;\n"
165       << "      TmpInst.setOpcode(" << Dest.Namespace << "::"
166       << Dest.TheDef->getName() << ");\n";
167
168     // Copy the operands from the source instruction.
169     // FIXME: Instruction operands with defaults values (predicates and cc_out
170     //        in ARM, for example shouldn't need explicit values in the
171     //        expansion DAG.
172     unsigned MIOpNo = 0;
173     for (unsigned OpNo = 0, E = Dest.Operands.size(); OpNo != E;
174          ++OpNo) {
175       o << "      // Operand: " << Dest.Operands[OpNo].Name << "\n";
176       for (unsigned i = 0, e = Dest.Operands[OpNo].MINumOperands;
177            i != e; ++i) {
178         switch (Expansion.OperandMap[MIOpNo + i].Kind) {
179         default:
180           llvm_unreachable("Unknown operand type?!");
181         case OpData::Operand:
182           o << "      lowerOperand(MI->getOperand("
183             << Source.Operands[Expansion.OperandMap[MIOpNo].Data
184                 .Operand].MIOperandNo + i
185             << "), MCOp);\n"
186             << "      TmpInst.addOperand(MCOp);\n";
187           break;
188         case OpData::Imm:
189           o << "      TmpInst.addOperand(MCOperand::CreateImm("
190             << Expansion.OperandMap[MIOpNo + i].Data.Imm << "));\n";
191           break;
192         case OpData::Reg: {
193           Record *Reg = Expansion.OperandMap[MIOpNo + i].Data.Reg;
194           o << "      TmpInst.addOperand(MCOperand::CreateReg(";
195           // "zero_reg" is special.
196           if (Reg->getName() == "zero_reg")
197             o << "0";
198           else
199             o << Reg->getValueAsString("Namespace") << "::" << Reg->getName();
200           o << "));\n";
201           break;
202         }
203         }
204       }
205       MIOpNo += Dest.Operands[OpNo].MINumOperands;
206     }
207     if (Dest.Operands.isVariadic) {
208       o << "      // variable_ops\n";
209       o << "      for (unsigned i = " << MIOpNo
210         << ", e = MI->getNumOperands(); i != e; ++i)\n"
211         << "        if (lowerOperand(MI->getOperand(i), MCOp))\n"
212         << "          TmpInst.addOperand(MCOp);\n";
213     }
214     o << "      OutStreamer.EmitInstruction(TmpInst);\n"
215       << "      break;\n"
216       << "    }\n";
217   }
218   o << "  }\n  return true;\n}\n\n";
219 }
220
221 void PseudoLoweringEmitter::run(raw_ostream &o) {
222   Record *ExpansionClass = Records.getClass("PseudoInstExpansion");
223   Record *InstructionClass = Records.getClass("PseudoInstExpansion");
224   assert(ExpansionClass && "PseudoInstExpansion class definition missing!");
225   assert(InstructionClass && "Instruction class definition missing!");
226
227   std::vector<Record*> Insts;
228   for (std::map<std::string, Record*>::const_iterator I =
229          Records.getDefs().begin(), E = Records.getDefs().end(); I != E; ++I) {
230     if (I->second->isSubClassOf(ExpansionClass) &&
231         I->second->isSubClassOf(InstructionClass))
232       Insts.push_back(I->second);
233   }
234
235   // Process the pseudo expansion definitions, validating them as we do so.
236   for (unsigned i = 0, e = Insts.size(); i != e; ++i)
237     evaluateExpansion(Insts[i]);
238
239   // Generate expansion code to lower the pseudo to an MCInst of the real
240   // instruction.
241   emitLoweringEmitter(o);
242 }
243