Basic fast-isel support for instructions with constant int operands.
[oota-llvm.git] / utils / TableGen / FastISelEmitter.cpp
1 //===- FastISelEmitter.cpp - Generate an instruction selector -------------===//
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 // This tablegen backend emits a "fast" instruction selector.
11 //
12 // This instruction selection method is designed to emit very poor code
13 // quickly. Also, it is not designed to do much lowering, so most illegal
14 // types (e.g. i64 on 32-bit targets) and operations (e.g. calls) are not
15 // supported and cannot easily be added. Blocks containing operations
16 // that are not supported need to be handled by a more capable selector,
17 // such as the SelectionDAG selector.
18 //
19 // The intended use for "fast" instruction selection is "-O0" mode
20 // compilation, where the quality of the generated code is irrelevant when
21 // weighed against the speed at which the code can be generated.
22 //
23 // If compile time is so important, you might wonder why we don't just
24 // skip codegen all-together, emit LLVM bytecode files, and execute them
25 // with an interpreter. The answer is that it would complicate linking and
26 // debugging, and also because that isn't how a compiler is expected to
27 // work in some circles.
28 //
29 // If you need better generated code or more lowering than what this
30 // instruction selector provides, use the SelectionDAG (DAGISel) instruction
31 // selector instead. If you're looking here because SelectionDAG isn't fast
32 // enough, consider looking into improving the SelectionDAG infastructure
33 // instead. At the time of this writing there remain several major
34 // opportunities for improvement.
35 // 
36 //===----------------------------------------------------------------------===//
37
38 #include "FastISelEmitter.h"
39 #include "Record.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Streams.h"
42 #include "llvm/ADT/VectorExtras.h"
43 using namespace llvm;
44
45 namespace {
46
47 /// OperandsSignature - This class holds a description of a list of operand
48 /// types. It has utility methods for emitting text based on the operands.
49 ///
50 struct OperandsSignature {
51   std::vector<std::string> Operands;
52
53   bool operator<(const OperandsSignature &O) const {
54     return Operands < O.Operands;
55   }
56
57   bool empty() const { return Operands.empty(); }
58
59   /// initialize - Examine the given pattern and initialize the contents
60   /// of the Operands array accordingly. Return true if all the operands
61   /// are supported, false otherwise.
62   ///
63   bool initialize(TreePatternNode *InstPatNode,
64                   const CodeGenTarget &Target,
65                   MVT::SimpleValueType VT,
66                   const CodeGenRegisterClass *DstRC) {
67     for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
68       TreePatternNode *Op = InstPatNode->getChild(i);
69       // For now, filter out any operand with a predicate.
70       if (!Op->getPredicateFn().empty())
71         return false;
72       // For now, filter out any operand with multiple values.
73       if (Op->getExtTypes().size() != 1)
74         return false;
75       // For now, all the operands must have the same type.
76       if (Op->getTypeNum(0) != VT)
77         return false;
78       if (!Op->isLeaf()) {
79         if (Op->getOperator()->getName() == "imm") {
80           Operands.push_back("i");
81           return true;
82         }
83         // For now, ignore fpimm and other non-leaf nodes.
84         return false;
85       }
86       DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
87       if (!OpDI)
88         return false;
89       Record *OpLeafRec = OpDI->getDef();
90       // TODO: handle instructions which have physreg operands.
91       if (OpLeafRec->isSubClassOf("Register"))
92         return false;
93       // For now, the only other thing we accept is register operands.
94       if (!OpLeafRec->isSubClassOf("RegisterClass"))
95         return false;
96       // For now, require the register operands' register classes to all
97       // be the same.
98       const CodeGenRegisterClass *RC = &Target.getRegisterClass(OpLeafRec);
99       if (!RC)
100         return false;
101       // For now, all the operands must have the same register class.
102       if (DstRC != RC)
103         return false;
104       Operands.push_back("r");
105     }
106     return true;
107   }
108
109   void PrintParameters(std::ostream &OS) const {
110     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
111       if (Operands[i] == "r") {
112         OS << "unsigned Op" << i;
113       } else if (Operands[i] == "i") {
114         OS << "uint64_t imm" << i;
115       } else {
116         assert("Unknown operand kind!");
117         abort();
118       }
119       if (i + 1 != e)
120         OS << ", ";
121     }
122   }
123
124   void PrintArguments(std::ostream &OS) const {
125     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
126       if (Operands[i] == "r") {
127         OS << "Op" << i;
128       } else if (Operands[i] == "i") {
129         OS << "imm" << i;
130       } else {
131         assert("Unknown operand kind!");
132         abort();
133       }
134       if (i + 1 != e)
135         OS << ", ";
136     }
137   }
138
139   void PrintManglingSuffix(std::ostream &OS) const {
140     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
141       OS << Operands[i];
142     }
143   }
144 };
145
146 /// InstructionMemo - This class holds additional information about an
147 /// instruction needed to emit code for it.
148 ///
149 struct InstructionMemo {
150   std::string Name;
151   const CodeGenRegisterClass *RC;
152 };
153
154 }
155
156 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
157   return CGP.getSDNodeInfo(Op).getEnumName();
158 }
159
160 static std::string getLegalCName(std::string OpName) {
161   std::string::size_type pos = OpName.find("::");
162   if (pos != std::string::npos)
163     OpName.replace(pos, 2, "_");
164   return OpName;
165 }
166
167 void FastISelEmitter::run(std::ostream &OS) {
168   EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
169                        Target.getName() + " target", OS);
170
171   OS << "#include \"llvm/CodeGen/FastISel.h\"\n";
172   OS << "\n";
173   OS << "namespace llvm {\n";
174   OS << "\n";
175   OS << "namespace " << InstNS.substr(0, InstNS.size() - 2) << " {\n";
176   OS << "\n";
177   
178   typedef std::map<MVT::SimpleValueType, InstructionMemo> TypeMap;
179   typedef std::map<std::string, TypeMap> OpcodeTypeMap;
180   typedef std::map<OperandsSignature, OpcodeTypeMap> OperandsOpcodeTypeMap;
181   OperandsOpcodeTypeMap SimplePatterns;
182
183   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
184        E = CGP.ptm_end(); I != E; ++I) {
185     const PatternToMatch &Pattern = *I;
186
187     // For now, just look at Instructions, so that we don't have to worry
188     // about emitting multiple instructions for a pattern.
189     TreePatternNode *Dst = Pattern.getDstPattern();
190     if (Dst->isLeaf()) continue;
191     Record *Op = Dst->getOperator();
192     if (!Op->isSubClassOf("Instruction"))
193       continue;
194     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
195     if (II.OperandList.empty())
196       continue;
197
198     // For now, ignore instructions where the first operand is not an
199     // output register.
200     Record *Op0Rec = II.OperandList[0].Rec;
201     if (!Op0Rec->isSubClassOf("RegisterClass"))
202       continue;
203     const CodeGenRegisterClass *DstRC = &Target.getRegisterClass(Op0Rec);
204     if (!DstRC)
205       continue;
206
207     // Inspect the pattern.
208     TreePatternNode *InstPatNode = Pattern.getSrcPattern();
209     if (!InstPatNode) continue;
210     if (InstPatNode->isLeaf()) continue;
211
212     Record *InstPatOp = InstPatNode->getOperator();
213     std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
214     MVT::SimpleValueType VT = InstPatNode->getTypeNum(0);
215
216     // For now, filter out instructions which just set a register to
217     // an Operand or an immediate, like MOV32ri.
218     if (InstPatOp->isSubClassOf("Operand"))
219       continue;
220     if (InstPatOp->getName() == "imm" ||
221         InstPatOp->getName() == "fpimm")
222       continue;
223
224     // For now, filter out any instructions with predicates.
225     if (!InstPatNode->getPredicateFn().empty())
226       continue;
227
228     // Check all the operands.
229     OperandsSignature Operands;
230     if (!Operands.initialize(InstPatNode, Target, VT, DstRC))
231       continue;
232
233     // Ok, we found a pattern that we can handle. Remember it.
234     InstructionMemo Memo = {
235       Pattern.getDstPattern()->getOperator()->getName(),
236       DstRC
237     };
238     SimplePatterns[Operands][OpcodeName][VT] = Memo;
239   }
240
241   // Declare the target FastISel class.
242   OS << "class FastISel : public llvm::FastISel {\n";
243   for (OperandsOpcodeTypeMap::const_iterator OI = SimplePatterns.begin(),
244        OE = SimplePatterns.end(); OI != OE; ++OI) {
245     const OperandsSignature &Operands = OI->first;
246     const OpcodeTypeMap &OTM = OI->second;
247
248     for (OpcodeTypeMap::const_iterator I = OTM.begin(), E = OTM.end();
249          I != E; ++I) {
250       const std::string &Opcode = I->first;
251       const TypeMap &TM = I->second;
252
253       for (TypeMap::const_iterator TI = TM.begin(), TE = TM.end();
254            TI != TE; ++TI) {
255         MVT::SimpleValueType VT = TI->first;
256
257         OS << "  unsigned FastEmit_" << getLegalCName(Opcode)
258            << "_" << getLegalCName(getName(VT)) << "_";
259         Operands.PrintManglingSuffix(OS);
260         OS << "(";
261         Operands.PrintParameters(OS);
262         OS << ");\n";
263       }
264
265       OS << "  unsigned FastEmit_" << getLegalCName(Opcode) << "_";
266       Operands.PrintManglingSuffix(OS);
267       OS << "(MVT::SimpleValueType VT";
268       if (!Operands.empty())
269         OS << ", ";
270       Operands.PrintParameters(OS);
271       OS << ");\n";
272     }
273
274     OS << "  unsigned FastEmit_";
275     Operands.PrintManglingSuffix(OS);
276     OS << "(MVT::SimpleValueType VT, ISD::NodeType Opcode";
277     if (!Operands.empty())
278       OS << ", ";
279     Operands.PrintParameters(OS);
280     OS << ");\n";
281   }
282   OS << "public:\n";
283   OS << "  explicit FastISel(MachineFunction &mf) : llvm::FastISel(mf) {}\n";
284   OS << "};\n";
285   OS << "\n";
286
287   // Define the target FastISel creation function.
288   OS << "llvm::FastISel *createFastISel(MachineFunction &mf) {\n";
289   OS << "  return new FastISel(mf);\n";
290   OS << "}\n";
291   OS << "\n";
292
293   // Now emit code for all the patterns that we collected.
294   for (OperandsOpcodeTypeMap::const_iterator OI = SimplePatterns.begin(),
295        OE = SimplePatterns.end(); OI != OE; ++OI) {
296     const OperandsSignature &Operands = OI->first;
297     const OpcodeTypeMap &OTM = OI->second;
298
299     for (OpcodeTypeMap::const_iterator I = OTM.begin(), E = OTM.end();
300          I != E; ++I) {
301       const std::string &Opcode = I->first;
302       const TypeMap &TM = I->second;
303
304       OS << "// FastEmit functions for " << Opcode << ".\n";
305       OS << "\n";
306
307       // Emit one function for each opcode,type pair.
308       for (TypeMap::const_iterator TI = TM.begin(), TE = TM.end();
309            TI != TE; ++TI) {
310         MVT::SimpleValueType VT = TI->first;
311         const InstructionMemo &Memo = TI->second;
312   
313         OS << "unsigned FastISel::FastEmit_"
314            << getLegalCName(Opcode)
315            << "_" << getLegalCName(getName(VT)) << "_";
316         Operands.PrintManglingSuffix(OS);
317         OS << "(";
318         Operands.PrintParameters(OS);
319         OS << ") {\n";
320         OS << "  return FastEmitInst_";
321         Operands.PrintManglingSuffix(OS);
322         OS << "(" << InstNS << Memo.Name << ", ";
323         OS << InstNS << Memo.RC->getName() << "RegisterClass";
324         if (!Operands.empty())
325           OS << ", ";
326         Operands.PrintArguments(OS);
327         OS << ");\n";
328         OS << "}\n";
329         OS << "\n";
330       }
331
332       // Emit one function for the opcode that demultiplexes based on the type.
333       OS << "unsigned FastISel::FastEmit_"
334          << getLegalCName(Opcode) << "_";
335       Operands.PrintManglingSuffix(OS);
336       OS << "(MVT::SimpleValueType VT";
337       if (!Operands.empty())
338         OS << ", ";
339       Operands.PrintParameters(OS);
340       OS << ") {\n";
341       OS << "  switch (VT) {\n";
342       for (TypeMap::const_iterator TI = TM.begin(), TE = TM.end();
343            TI != TE; ++TI) {
344         MVT::SimpleValueType VT = TI->first;
345         std::string TypeName = getName(VT);
346         OS << "  case " << TypeName << ": return FastEmit_"
347            << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
348         Operands.PrintManglingSuffix(OS);
349         OS << "(";
350         Operands.PrintArguments(OS);
351         OS << ");\n";
352       }
353       OS << "  default: return 0;\n";
354       OS << "  }\n";
355       OS << "}\n";
356       OS << "\n";
357     }
358
359     // Emit one function for the operand signature that demultiplexes based
360     // on opcode and type.
361     OS << "unsigned FastISel::FastEmit_";
362     Operands.PrintManglingSuffix(OS);
363     OS << "(MVT::SimpleValueType VT, ISD::NodeType Opcode";
364     if (!Operands.empty())
365       OS << ", ";
366     Operands.PrintParameters(OS);
367     OS << ") {\n";
368     OS << "  switch (Opcode) {\n";
369     for (OpcodeTypeMap::const_iterator I = OTM.begin(), E = OTM.end();
370          I != E; ++I) {
371       const std::string &Opcode = I->first;
372
373       OS << "  case " << Opcode << ": return FastEmit_"
374          << getLegalCName(Opcode) << "_";
375       Operands.PrintManglingSuffix(OS);
376       OS << "(VT";
377       if (!Operands.empty())
378         OS << ", ";
379       Operands.PrintArguments(OS);
380       OS << ");\n";
381     }
382     OS << "  default: return 0;\n";
383     OS << "  }\n";
384     OS << "}\n";
385     OS << "\n";
386   }
387
388   OS << "} // namespace X86\n";
389   OS << "\n";
390   OS << "} // namespace llvm\n";
391 }
392
393 FastISelEmitter::FastISelEmitter(RecordKeeper &R)
394   : Records(R),
395     CGP(R),
396     Target(CGP.getTargetInfo()),
397     InstNS(Target.getInstNamespace() + "::") {
398
399   assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
400 }