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