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