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