Factor out the predicate check code from DAGISelEmitter.cpp
[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<std::string, InstructionMemo> PredMap;
179   typedef std::map<MVT::SimpleValueType, PredMap> TypePredMap;
180   typedef std::map<std::string, TypePredMap> OpcodeTypePredMap;
181   typedef std::map<OperandsSignature, OpcodeTypePredMap> OperandsOpcodeTypePredMap;
182   OperandsOpcodeTypePredMap SimplePatterns;
183
184   for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
185        E = CGP.ptm_end(); I != E; ++I) {
186     const PatternToMatch &Pattern = *I;
187
188     // For now, just look at Instructions, so that we don't have to worry
189     // about emitting multiple instructions for a pattern.
190     TreePatternNode *Dst = Pattern.getDstPattern();
191     if (Dst->isLeaf()) continue;
192     Record *Op = Dst->getOperator();
193     if (!Op->isSubClassOf("Instruction"))
194       continue;
195     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
196     if (II.OperandList.empty())
197       continue;
198
199     // For now, ignore instructions where the first operand is not an
200     // output register.
201     Record *Op0Rec = II.OperandList[0].Rec;
202     if (!Op0Rec->isSubClassOf("RegisterClass"))
203       continue;
204     const CodeGenRegisterClass *DstRC = &Target.getRegisterClass(Op0Rec);
205     if (!DstRC)
206       continue;
207
208     // Inspect the pattern.
209     TreePatternNode *InstPatNode = Pattern.getSrcPattern();
210     if (!InstPatNode) continue;
211     if (InstPatNode->isLeaf()) continue;
212
213     Record *InstPatOp = InstPatNode->getOperator();
214     std::string OpcodeName = getOpcodeName(InstPatOp, CGP);
215     MVT::SimpleValueType VT = InstPatNode->getTypeNum(0);
216
217     // For now, filter out instructions which just set a register to
218     // an Operand or an immediate, like MOV32ri.
219     if (InstPatOp->isSubClassOf("Operand"))
220       continue;
221     if (InstPatOp->getName() == "imm" ||
222         InstPatOp->getName() == "fpimm")
223       continue;
224
225     // For now, filter out any instructions with predicates.
226     if (!InstPatNode->getPredicateFn().empty())
227       continue;
228
229     // Check all the operands.
230     OperandsSignature Operands;
231     if (!Operands.initialize(InstPatNode, Target, VT, DstRC))
232       continue;
233
234     // Get the predicate that guards this pattern.
235     std::string PredicateCheck = Pattern.getPredicateCheck();
236
237     // Ok, we found a pattern that we can handle. Remember it.
238     InstructionMemo Memo = {
239       Pattern.getDstPattern()->getOperator()->getName(),
240       DstRC
241     };
242     assert(!SimplePatterns[Operands][OpcodeName][VT].count(PredicateCheck) &&
243            "Duplicate pattern!");
244     SimplePatterns[Operands][OpcodeName][VT][PredicateCheck] = Memo;
245   }
246
247   // Declare the target FastISel class.
248   OS << "class FastISel : public llvm::FastISel {\n";
249   for (OperandsOpcodeTypePredMap::const_iterator OI = SimplePatterns.begin(),
250        OE = SimplePatterns.end(); OI != OE; ++OI) {
251     const OperandsSignature &Operands = OI->first;
252     const OpcodeTypePredMap &OTM = OI->second;
253
254     for (OpcodeTypePredMap::const_iterator I = OTM.begin(), E = OTM.end();
255          I != E; ++I) {
256       const std::string &Opcode = I->first;
257       const TypePredMap &TM = I->second;
258
259       for (TypePredMap::const_iterator TI = TM.begin(), TE = TM.end();
260            TI != TE; ++TI) {
261         MVT::SimpleValueType VT = TI->first;
262
263         OS << "  unsigned FastEmit_" << getLegalCName(Opcode)
264            << "_" << getLegalCName(getName(VT)) << "_";
265         Operands.PrintManglingSuffix(OS);
266         OS << "(";
267         Operands.PrintParameters(OS);
268         OS << ");\n";
269       }
270
271       OS << "  unsigned FastEmit_" << getLegalCName(Opcode) << "_";
272       Operands.PrintManglingSuffix(OS);
273       OS << "(MVT::SimpleValueType VT";
274       if (!Operands.empty())
275         OS << ", ";
276       Operands.PrintParameters(OS);
277       OS << ");\n";
278     }
279
280     OS << "  unsigned FastEmit_";
281     Operands.PrintManglingSuffix(OS);
282     OS << "(MVT::SimpleValueType VT, ISD::NodeType Opcode";
283     if (!Operands.empty())
284       OS << ", ";
285     Operands.PrintParameters(OS);
286     OS << ");\n";
287   }
288   OS << "\n";
289
290   // Declare the Subtarget member, which is used for predicate checks.
291   OS << "  const " << InstNS.substr(0, InstNS.size() - 2)
292      << "Subtarget *Subtarget;\n";
293   OS << "\n";
294
295   // Declare the constructor.
296   OS << "public:\n";
297   OS << "  explicit FastISel(MachineFunction &mf)\n";
298   OS << "     : llvm::FastISel(mf),\n";
299   OS << "       Subtarget(&TM.getSubtarget<" << InstNS.substr(0, InstNS.size() - 2)
300      << "Subtarget>()) {}\n";
301   OS << "};\n";
302   OS << "\n";
303
304   // Define the target FastISel creation function.
305   OS << "llvm::FastISel *createFastISel(MachineFunction &mf) {\n";
306   OS << "  return new FastISel(mf);\n";
307   OS << "}\n";
308   OS << "\n";
309
310   // Now emit code for all the patterns that we collected.
311   for (OperandsOpcodeTypePredMap::const_iterator OI = SimplePatterns.begin(),
312        OE = SimplePatterns.end(); OI != OE; ++OI) {
313     const OperandsSignature &Operands = OI->first;
314     const OpcodeTypePredMap &OTM = OI->second;
315
316     for (OpcodeTypePredMap::const_iterator I = OTM.begin(), E = OTM.end();
317          I != E; ++I) {
318       const std::string &Opcode = I->first;
319       const TypePredMap &TM = I->second;
320
321       OS << "// FastEmit functions for " << Opcode << ".\n";
322       OS << "\n";
323
324       // Emit one function for each opcode,type pair.
325       for (TypePredMap::const_iterator TI = TM.begin(), TE = TM.end();
326            TI != TE; ++TI) {
327         MVT::SimpleValueType VT = TI->first;
328         const PredMap &PM = TI->second;
329         bool HasPred = false;
330
331         OS << "unsigned FastISel::FastEmit_"
332            << getLegalCName(Opcode)
333            << "_" << getLegalCName(getName(VT)) << "_";
334         Operands.PrintManglingSuffix(OS);
335         OS << "(";
336         Operands.PrintParameters(OS);
337         OS << ") {\n";
338
339         // Emit code for each possible instruction. There may be
340         // multiple if there are subtarget concerns.
341         for (PredMap::const_iterator PI = PM.begin(), PE = PM.end();
342              PI != PE; ++PI) {
343           std::string PredicateCheck = PI->first;
344           const InstructionMemo &Memo = PI->second;
345   
346           if (PredicateCheck.empty()) {
347             assert(!HasPred && "Multiple instructions match, at least one has "
348                                "a predicate and at least one doesn't!");
349           } else {
350             OS << "  if (" + PredicateCheck + ")\n";
351             OS << "  ";
352             HasPred = true;
353           }
354           OS << "  return FastEmitInst_";
355           Operands.PrintManglingSuffix(OS);
356           OS << "(" << InstNS << Memo.Name << ", ";
357           OS << InstNS << Memo.RC->getName() << "RegisterClass";
358           if (!Operands.empty())
359             OS << ", ";
360           Operands.PrintArguments(OS);
361           OS << ");\n";
362         }
363         // Return 0 if none of the predicates were satisfied.
364         if (HasPred)
365           OS << "  return 0;\n";
366         OS << "}\n";
367         OS << "\n";
368       }
369
370       // Emit one function for the opcode that demultiplexes based on the type.
371       OS << "unsigned FastISel::FastEmit_"
372          << getLegalCName(Opcode) << "_";
373       Operands.PrintManglingSuffix(OS);
374       OS << "(MVT::SimpleValueType VT";
375       if (!Operands.empty())
376         OS << ", ";
377       Operands.PrintParameters(OS);
378       OS << ") {\n";
379       OS << "  switch (VT) {\n";
380       for (TypePredMap::const_iterator TI = TM.begin(), TE = TM.end();
381            TI != TE; ++TI) {
382         MVT::SimpleValueType VT = TI->first;
383         std::string TypeName = getName(VT);
384         OS << "  case " << TypeName << ": return FastEmit_"
385            << getLegalCName(Opcode) << "_" << getLegalCName(TypeName) << "_";
386         Operands.PrintManglingSuffix(OS);
387         OS << "(";
388         Operands.PrintArguments(OS);
389         OS << ");\n";
390       }
391       OS << "  default: return 0;\n";
392       OS << "  }\n";
393       OS << "}\n";
394       OS << "\n";
395     }
396
397     // Emit one function for the operand signature that demultiplexes based
398     // on opcode and type.
399     OS << "unsigned FastISel::FastEmit_";
400     Operands.PrintManglingSuffix(OS);
401     OS << "(MVT::SimpleValueType VT, ISD::NodeType Opcode";
402     if (!Operands.empty())
403       OS << ", ";
404     Operands.PrintParameters(OS);
405     OS << ") {\n";
406     OS << "  switch (Opcode) {\n";
407     for (OpcodeTypePredMap::const_iterator I = OTM.begin(), E = OTM.end();
408          I != E; ++I) {
409       const std::string &Opcode = I->first;
410
411       OS << "  case " << Opcode << ": return FastEmit_"
412          << getLegalCName(Opcode) << "_";
413       Operands.PrintManglingSuffix(OS);
414       OS << "(VT";
415       if (!Operands.empty())
416         OS << ", ";
417       Operands.PrintArguments(OS);
418       OS << ");\n";
419     }
420     OS << "  default: return 0;\n";
421     OS << "  }\n";
422     OS << "}\n";
423     OS << "\n";
424   }
425
426   OS << "} // namespace X86\n";
427   OS << "\n";
428   OS << "} // namespace llvm\n";
429 }
430
431 FastISelEmitter::FastISelEmitter(RecordKeeper &R)
432   : Records(R),
433     CGP(R),
434     Target(CGP.getTargetInfo()),
435     InstNS(Target.getInstNamespace() + "::") {
436
437   assert(InstNS.size() > 2 && "Can't determine target-specific namespace!");
438 }