Let tblgen only generate fastisel routines, not the class definition. This makes...
[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 /// InstructionMemo - This class holds additional information about an
48 /// instruction needed to emit code for it.
49 ///
50 struct InstructionMemo {
51   std::string Name;
52   const CodeGenRegisterClass *RC;
53   unsigned char SubRegNo;
54   std::vector<std::string>* PhysRegs;
55 };
56
57 /// OperandsSignature - This class holds a description of a list of operand
58 /// types. It has utility methods for emitting text based on the operands.
59 ///
60 struct OperandsSignature {
61   std::vector<std::string> Operands;
62
63   bool operator<(const OperandsSignature &O) const {
64     return Operands < O.Operands;
65   }
66
67   bool empty() const { return Operands.empty(); }
68
69   /// initialize - Examine the given pattern and initialize the contents
70   /// of the Operands array accordingly. Return true if all the operands
71   /// are supported, false otherwise.
72   ///
73   bool initialize(TreePatternNode *InstPatNode,
74                   const CodeGenTarget &Target,
75                   MVT::SimpleValueType VT) {
76     if (!InstPatNode->isLeaf() &&
77         InstPatNode->getOperator()->getName() == "imm") {
78       Operands.push_back("i");
79       return true;
80     }
81     if (!InstPatNode->isLeaf() &&
82         InstPatNode->getOperator()->getName() == "fpimm") {
83       Operands.push_back("f");
84       return true;
85     }
86     
87     const CodeGenRegisterClass *DstRC = 0;
88     
89     for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
90       TreePatternNode *Op = InstPatNode->getChild(i);
91       // For now, filter out any operand with a predicate.
92       if (!Op->getPredicateFn().empty())
93         return false;
94       // For now, filter out any operand with multiple values.
95       if (Op->getExtTypes().size() != 1)
96         return false;
97       // For now, all the operands must have the same type.
98       if (Op->getTypeNum(0) != VT)
99         return false;
100       if (!Op->isLeaf()) {
101         if (Op->getOperator()->getName() == "imm") {
102           Operands.push_back("i");
103           return true;
104         }
105         if (Op->getOperator()->getName() == "fpimm") {
106           Operands.push_back("f");
107           return true;
108         }
109         // For now, ignore other non-leaf nodes.
110         return false;
111       }
112       DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
113       if (!OpDI)
114         return false;
115       Record *OpLeafRec = OpDI->getDef();
116       // For now, the only other thing we accept is register operands.
117       
118       const CodeGenRegisterClass *RC = 0;
119       if (OpLeafRec->isSubClassOf("RegisterClass"))
120         RC = &Target.getRegisterClass(OpLeafRec);
121       else if (OpLeafRec->isSubClassOf("Register"))
122         RC = Target.getRegisterClassForRegister(OpLeafRec);
123       else
124         return false;
125       // For now, require the register operands' register classes to all
126       // be the same.
127       if (!RC)
128         return false;
129       // For now, all the operands must have the same register class.
130       if (DstRC) {
131         if (DstRC != RC)
132           return false;
133       } else
134         DstRC = RC;
135       Operands.push_back("r");
136     }
137     return true;
138   }
139
140   void PrintParameters(std::ostream &OS) const {
141     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
142       if (Operands[i] == "r") {
143         OS << "unsigned Op" << i;
144       } else if (Operands[i] == "i") {
145         OS << "uint64_t imm" << i;
146       } else if (Operands[i] == "f") {
147         OS << "ConstantFP *f" << i;
148       } else {
149         assert("Unknown operand kind!");
150         abort();
151       }
152       if (i + 1 != e)
153         OS << ", ";
154     }
155   }
156
157   void PrintArguments(std::ostream &OS,
158                       const std::vector<std::string>& PR) const {
159     assert(PR.size() == Operands.size());
160     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
161       if (PR[i] != "") {
162         OS << PR[i];
163       } else if (Operands[i] == "r") {
164         OS << "Op" << i;
165       } else if (Operands[i] == "i") {
166         OS << "imm" << i;
167       } else if (Operands[i] == "f") {
168         OS << "f" << i;
169       } else {
170         assert("Unknown operand kind!");
171         abort();
172       }
173       if (i + 1 != e)
174         OS << ", ";
175     }
176   }
177
178   void PrintArguments(std::ostream &OS) const {
179     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
180       if (Operands[i] == "r") {
181         OS << "Op" << i;
182       } else if (Operands[i] == "i") {
183         OS << "imm" << i;
184       } else if (Operands[i] == "f") {
185         OS << "f" << i;
186       } else {
187         assert("Unknown operand kind!");
188         abort();
189       }
190       if (i + 1 != e)
191         OS << ", ";
192     }
193   }
194
195
196   void PrintManglingSuffix(std::ostream &OS) const {
197     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
198       OS << Operands[i];
199     }
200   }
201 };
202
203 class FastISelMap {
204   typedef std::map<std::string, InstructionMemo> PredMap;
205   typedef std::map<MVT::SimpleValueType, PredMap> RetPredMap;
206   typedef std::map<MVT::SimpleValueType, RetPredMap> TypeRetPredMap;
207   typedef std::map<std::string, TypeRetPredMap> OpcodeTypeRetPredMap;
208   typedef std::map<OperandsSignature, OpcodeTypeRetPredMap> OperandsOpcodeTypeRetPredMap;
209
210   OperandsOpcodeTypeRetPredMap SimplePatterns;
211
212   std::string InstNS;
213
214 public:
215   explicit FastISelMap(std::string InstNS);
216
217   void CollectPatterns(CodeGenDAGPatterns &CGP);
218   void PrintClass(std::ostream &OS);
219   void PrintFunctionDefinitions(std::ostream &OS);
220 };
221
222 }
223
224 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
225   return CGP.getSDNodeInfo(Op).getEnumName();
226 }
227
228 static std::string getLegalCName(std::string OpName) {
229   std::string::size_type pos = OpName.find("::");
230   if (pos != std::string::npos)
231     OpName.replace(pos, 2, "_");
232   return OpName;
233 }
234
235 FastISelMap::FastISelMap(std::string instns)
236   : InstNS(instns) {
237 }
238
239 void FastISelMap::CollectPatterns(CodeGenDAGPatterns &CGP) {
240   const CodeGenTarget &Target = CGP.getTargetInfo();
241
242   // Determine the target's namespace name.
243   InstNS = Target.getInstNamespace() + "::";
244   assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
245
246   // Scan through all the patterns and record the simple ones.
247   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
248        E = CGP.ptm_end(); I != E; ++I) {
249     const PatternToMatch &Pattern = *I;
250
251     // For now, just look at Instructions, so that we don't have to worry
252     // about emitting multiple instructions for a pattern.
253     TreePatternNode *Dst = Pattern.getDstPattern();
254     if (Dst->isLeaf()) continue;
255     Record *Op = Dst->getOperator();
256     if (!Op->isSubClassOf("Instruction"))
257       continue;
258     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
259     if (II.OperandList.empty())
260       continue;
261
262     // For now, ignore instructions where the first operand is not an
263     // output register.
264     const CodeGenRegisterClass *DstRC = 0;
265     unsigned SubRegNo = ~0;
266     if (Op->getName() != "EXTRACT_SUBREG") {
267       Record *Op0Rec = II.OperandList[0].Rec;
268       if (!Op0Rec->isSubClassOf("RegisterClass"))
269         continue;
270       DstRC = &Target.getRegisterClass(Op0Rec);
271       if (!DstRC)
272         continue;
273     } else {
274       SubRegNo = static_cast<IntInit*>(
275                  Dst->getChild(1)->getLeafValue())->getValue();
276     }
277
278     // Inspect the pattern.
279     TreePatternNode *InstPatNode = Pattern.getSrcPattern();
280     if (!InstPatNode) continue;
281     if (InstPatNode->isLeaf()) continue;
282
283     Record *InstPatOp = InstPatNode->getOperator();
284     std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
285     MVT::SimpleValueType RetVT = InstPatNode->getTypeNum(0);
286     MVT::SimpleValueType VT = RetVT;
287     if (InstPatNode->getNumChildren())
288       VT = InstPatNode->getChild(0)->getTypeNum(0);
289
290     // For now, filter out instructions which just set a register to
291     // an Operand or an immediate, like MOV32ri.
292     if (InstPatOp->isSubClassOf("Operand"))
293       continue;
294
295     // For now, filter out any instructions with predicates.
296     if (!InstPatNode->getPredicateFn().empty())
297       continue;
298
299     // Check all the operands.
300     OperandsSignature Operands;
301     if (!Operands.initialize(InstPatNode, Target, VT))
302       continue;
303     
304     std::vector<std::string>* PhysRegInputs = new std::vector<std::string>();
305     if (!InstPatNode->isLeaf() &&
306         (InstPatNode->getOperator()->getName() == "imm" ||
307          InstPatNode->getOperator()->getName() == "fpimmm"))
308       PhysRegInputs->push_back("");
309     else if (!InstPatNode->isLeaf()) {
310       for (unsigned i = 0, e = InstPatNode->getNumChildren(); i != e; ++i) {
311         TreePatternNode *Op = InstPatNode->getChild(i);
312         if (!Op->isLeaf()) {
313           PhysRegInputs->push_back("");
314           continue;
315         }
316         
317         DefInit *OpDI = dynamic_cast<DefInit*>(Op->getLeafValue());
318         Record *OpLeafRec = OpDI->getDef();
319         std::string PhysReg;
320         if (OpLeafRec->isSubClassOf("Register")) {
321           PhysReg += static_cast<StringInit*>(OpLeafRec->getValue( \
322                      "Namespace")->getValue())->getValue();
323           PhysReg += "::";
324           
325           std::vector<CodeGenRegister> Regs = Target.getRegisters();
326           for (unsigned i = 0; i < Regs.size(); ++i) {
327             if (Regs[i].TheDef == OpLeafRec) {
328               PhysReg += Regs[i].getName();
329               break;
330             }
331           }
332         }
333       
334         PhysRegInputs->push_back(PhysReg);
335       }
336     } else
337       PhysRegInputs->push_back("");
338
339     // Get the predicate that guards this pattern.
340     std::string PredicateCheck = Pattern.getPredicateCheck();
341
342     // Ok, we found a pattern that we can handle. Remember it.
343     InstructionMemo Memo = {
344       Pattern.getDstPattern()->getOperator()->getName(),
345       DstRC,
346       SubRegNo,
347       PhysRegInputs
348     };
349     assert(!SimplePatterns[Operands][OpcodeName][VT][RetVT].count(PredicateCheck) &&
350            "Duplicate pattern!");
351     SimplePatterns[Operands][OpcodeName][VT][RetVT][PredicateCheck] = Memo;
352   }
353 }
354
355 void FastISelMap::PrintFunctionDefinitions(std::ostream &OS) {
356   // Now emit code for all the patterns that we collected.
357   for (OperandsOpcodeTypeRetPredMap::const_iterator OI = SimplePatterns.begin(),
358        OE = SimplePatterns.end(); OI != OE; ++OI) {
359     const OperandsSignature &Operands = OI->first;
360     const OpcodeTypeRetPredMap &OTM = OI->second;
361
362     for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
363          I != E; ++I) {
364       const std::string &Opcode = I->first;
365       const TypeRetPredMap &TM = I->second;
366
367       OS << "// FastEmit functions for " << Opcode << ".\n";
368       OS << "\n";
369
370       // Emit one function for each opcode,type pair.
371       for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
372            TI != TE; ++TI) {
373         MVT::SimpleValueType VT = TI->first;
374         const RetPredMap &RM = TI->second;
375         if (RM.size() != 1) {
376           for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
377                RI != RE; ++RI) {
378             MVT::SimpleValueType RetVT = RI->first;
379             const PredMap &PM = RI->second;
380             bool HasPred = false;
381
382             OS << "unsigned FastEmit_"
383                << getLegalCName(Opcode)
384                << "_" << getLegalCName(getName(VT))
385                << "_" << getLegalCName(getName(RetVT)) << "_";
386             Operands.PrintManglingSuffix(OS);
387             OS << "(";
388             Operands.PrintParameters(OS);
389             OS << ") {\n";
390
391             // Emit code for each possible instruction. There may be
392             // multiple if there are subtarget concerns.
393             for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
394                  PI != PE; ++PI) {
395               std::string PredicateCheck = PI->first;
396               const InstructionMemo &Memo = PI->second;
397   
398               if (PredicateCheck.empty()) {
399                 assert(!HasPred &&
400                        "Multiple instructions match, at least one has "
401                        "a predicate and at least one doesn't!");
402               } else {
403                 OS << "  if (" + PredicateCheck + ") {\n";
404                 OS << "  ";
405                 HasPred = true;
406               }
407               
408               for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
409                 if ((*Memo.PhysRegs)[i] != "")
410                   OS << "  TII.copyRegToReg(*MBB, MBB->end(), "
411                      << (*Memo.PhysRegs)[i] << ", Op" << i << ", "
412                      << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
413                      << (*Memo.PhysRegs)[i] << "), "
414                      << "MRI.getRegClass(Op" << i << "));\n";
415               }
416               
417               OS << "  return FastEmitInst_";
418               if (Memo.SubRegNo == (unsigned char)~0) {
419                 Operands.PrintManglingSuffix(OS);
420                 OS << "(" << InstNS << Memo.Name << ", ";
421                 OS << InstNS << Memo.RC->getName() << "RegisterClass";
422                 if (!Operands.empty())
423                   OS << ", ";
424                 Operands.PrintArguments(OS, *Memo.PhysRegs);
425                 OS << ");\n";
426               } else {
427                 OS << "extractsubreg(Op0, ";
428                 OS << (unsigned)Memo.SubRegNo;
429                 OS << ");\n";
430               }
431               
432               if (HasPred)
433                 OS << "}\n";
434               
435             }
436             // Return 0 if none of the predicates were satisfied.
437             if (HasPred)
438               OS << "  return 0;\n";
439             OS << "}\n";
440             OS << "\n";
441           }
442           
443           // Emit one function for the type that demultiplexes on return type.
444           OS << "unsigned FastEmit_"
445              << getLegalCName(Opcode) << "_"
446              << getLegalCName(getName(VT)) << "_";
447           Operands.PrintManglingSuffix(OS);
448           OS << "(MVT::SimpleValueType RetVT";
449           if (!Operands.empty())
450             OS << ", ";
451           Operands.PrintParameters(OS);
452           OS << ") {\nswitch (RetVT) {\n";
453           for (RetPredMap::const_iterator RI = RM.begin(), RE = RM.end();
454                RI != RE; ++RI) {
455             MVT::SimpleValueType RetVT = RI->first;
456             OS << "  case " << getName(RetVT) << ": return FastEmit_"
457                << getLegalCName(Opcode) << "_" << getLegalCName(getName(VT))
458                << "_" << getLegalCName(getName(RetVT)) << "_";
459             Operands.PrintManglingSuffix(OS);
460             OS << "(";
461             Operands.PrintArguments(OS);
462             OS << ");\n";
463           }
464           OS << "  default: return 0;\n}\n}\n\n";
465           
466         } else {
467           // Non-variadic return type.
468           OS << "unsigned FastEmit_"
469              << getLegalCName(Opcode) << "_"
470              << getLegalCName(getName(VT)) << "_";
471           Operands.PrintManglingSuffix(OS);
472           OS << "(MVT::SimpleValueType RetVT";
473           if (!Operands.empty())
474             OS << ", ";
475           Operands.PrintParameters(OS);
476           OS << ") {\n";
477           
478           OS << "  if (RetVT != " << getName(RM.begin()->first)
479              << ")\n    return 0;\n";
480           
481           const PredMap &PM = RM.begin()->second;
482           bool HasPred = false;
483           
484           // Emit code for each possible instruction. There may be
485           // multiple if there are subtarget concerns.
486           for (PredMap::const_iterator PI = PM.begin(), PE = PM.end(); PI != PE; ++PI) {
487             std::string PredicateCheck = PI->first;
488             const InstructionMemo &Memo = PI->second;
489
490             if (PredicateCheck.empty()) {
491               assert(!HasPred &&
492                      "Multiple instructions match, at least one has "
493                      "a predicate and at least one doesn't!");
494             } else {
495               OS << "  if (" + PredicateCheck + ") {\n";
496               OS << "  ";
497               HasPred = true;
498             }
499             
500              for (unsigned i = 0; i < Memo.PhysRegs->size(); ++i) {
501                 if ((*Memo.PhysRegs)[i] != "")
502                   OS << "  TII.copyRegToReg(*MBB, MBB->end(), "
503                      << (*Memo.PhysRegs)[i] << ", Op" << i << ", "
504                      << "TM.getRegisterInfo()->getPhysicalRegisterRegClass("
505                      << (*Memo.PhysRegs)[i] << "), "
506                      << "MRI.getRegClass(Op" << i << "));\n";
507               }
508             
509             OS << "  return FastEmitInst_";
510             
511             if (Memo.SubRegNo == (unsigned char)~0) {
512               Operands.PrintManglingSuffix(OS);
513               OS << "(" << InstNS << Memo.Name << ", ";
514               OS << InstNS << Memo.RC->getName() << "RegisterClass";
515               if (!Operands.empty())
516                 OS << ", ";
517               Operands.PrintArguments(OS, *Memo.PhysRegs);
518               OS << ");\n";
519             } else {
520               OS << "extractsubreg(Op0, ";
521               OS << (unsigned)Memo.SubRegNo;
522               OS << ");\n";
523             }
524             
525              if (HasPred)
526                OS << "  }\n";
527           }
528           
529           // Return 0 if none of the predicates were satisfied.
530           if (HasPred)
531             OS << "  return 0;\n";
532           OS << "}\n";
533           OS << "\n";
534         }
535       }
536
537       // Emit one function for the opcode that demultiplexes based on the type.
538       OS << "unsigned FastEmit_"
539          << getLegalCName(Opcode) << "_";
540       Operands.PrintManglingSuffix(OS);
541       OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT";
542       if (!Operands.empty())
543         OS << ", ";
544       Operands.PrintParameters(OS);
545       OS << ") {\n";
546       OS << "  switch (VT) {\n";
547       for (TypeRetPredMap::const_iterator TI = TM.begin(), TE = TM.end();
548            TI != TE; ++TI) {
549         MVT::SimpleValueType VT = TI->first;
550         std::string TypeName = getName(VT);
551         OS << "  case " << TypeName << ": return FastEmit_"
552            << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
553         Operands.PrintManglingSuffix(OS);
554         OS << "(RetVT";
555         if (!Operands.empty())
556           OS << ", ";
557         Operands.PrintArguments(OS);
558         OS << ");\n";
559       }
560       OS << "  default: return 0;\n";
561       OS << "  }\n";
562       OS << "}\n";
563       OS << "\n";
564     }
565
566     OS << "// Top-level FastEmit function.\n";
567     OS << "\n";
568
569     // Emit one function for the operand signature that demultiplexes based
570     // on opcode and type.
571     OS << "unsigned FastEmit_";
572     Operands.PrintManglingSuffix(OS);
573     OS << "(MVT::SimpleValueType VT, MVT::SimpleValueType RetVT, ISD::NodeType Opcode";
574     if (!Operands.empty())
575       OS << ", ";
576     Operands.PrintParameters(OS);
577     OS << ") {\n";
578     OS << "  switch (Opcode) {\n";
579     for (OpcodeTypeRetPredMap::const_iterator I = OTM.begin(), E = OTM.end();
580          I != E; ++I) {
581       const std::string &Opcode = I->first;
582
583       OS << "  case " << Opcode << ": return FastEmit_"
584          << getLegalCName(Opcode) << "_";
585       Operands.PrintManglingSuffix(OS);
586       OS << "(VT, RetVT";
587       if (!Operands.empty())
588         OS << ", ";
589       Operands.PrintArguments(OS);
590       OS << ");\n";
591     }
592     OS << "  default: return 0;\n";
593     OS << "  }\n";
594     OS << "}\n";
595     OS << "\n";
596   }
597 }
598
599 void FastISelEmitter::run(std::ostream &OS) {
600   const CodeGenTarget &Target = CGP.getTargetInfo();
601
602   // Determine the target's namespace name.
603   std::string InstNS = Target.getInstNamespace() + "::";
604   assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
605
606   EmitSourceFileHeader("\"Fast\" Instruction Selector for the " +
607                        Target.getName() + " target", OS);
608
609   FastISelMap F(InstNS);
610   F.CollectPatterns(CGP);
611   F.PrintFunctionDefinitions(OS);
612 }
613
614 FastISelEmitter::FastISelEmitter(RecordKeeper &R)
615   : Records(R),
616     CGP(R) {
617 }
618