add a new Push2 opcode for targets (like cellspu) which have
[oota-llvm.git] / utils / TableGen / DAGISelMatcherEmitter.cpp
1 //===- DAGISelMatcherEmitter.cpp - Matcher Emitter ------------------------===//
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 file contains code to generate C++ code a matcher.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "DAGISelMatcher.h"
15 #include "CodeGenDAGPatterns.h"
16 #include "Record.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/Support/FormattedStream.h"
21 using namespace llvm;
22
23 namespace {
24 enum {
25   CommentIndent = 30
26 };
27 }
28
29 /// ClassifyInt - Classify an integer by size, return '1','2','4','8' if this
30 /// fits in 1, 2, 4, or 8 sign extended bytes.
31 static char ClassifyInt(int64_t Val) {
32   if (Val == int8_t(Val))  return '1';
33   if (Val == int16_t(Val)) return '2';
34   if (Val == int32_t(Val)) return '4';
35   return '8';
36 }
37
38 /// EmitInt - Emit the specified integer, returning the number of bytes emitted.
39 static unsigned EmitInt(int64_t Val, formatted_raw_ostream &OS) {
40   unsigned BytesEmitted = 1;
41   OS << (int)(unsigned char)Val << ", ";
42   if (Val == int8_t(Val)) {
43     OS << '\n';
44     return BytesEmitted;
45   }
46   
47   OS << (int)(unsigned char)(Val >> 8) << ", ";
48   ++BytesEmitted;
49   
50   if (Val != int16_t(Val)) {
51     OS << (int)(unsigned char)(Val >> 16) << ", "
52        << (int)(unsigned char)(Val >> 24) << ", ";
53     BytesEmitted += 2;
54     
55     if (Val != int32_t(Val)) {
56       OS << (int)(unsigned char)(Val >> 32) << ", "
57          << (int)(unsigned char)(Val >> 40) << ", "
58          << (int)(unsigned char)(Val >> 48) << ", "
59          << (int)(unsigned char)(Val >> 56) << ", ";
60       BytesEmitted += 4;
61     }   
62   }
63   
64   OS.PadToColumn(CommentIndent) << "// " << Val << " aka 0x";
65   OS.write_hex(Val) << '\n';
66   return BytesEmitted;
67 }
68
69 namespace {
70 class MatcherTableEmitter {
71   StringMap<unsigned> NodePredicateMap, PatternPredicateMap;
72   std::vector<std::string> NodePredicates, PatternPredicates;
73
74   DenseMap<const ComplexPattern*, unsigned> ComplexPatternMap;
75   std::vector<const ComplexPattern*> ComplexPatterns;
76
77
78   DenseMap<Record*, unsigned> NodeXFormMap;
79   std::vector<const Record*> NodeXForms;
80
81 public:
82   MatcherTableEmitter() {}
83
84   unsigned EmitMatcherList(const MatcherNode *N, unsigned Indent,
85                            unsigned StartIdx, formatted_raw_ostream &OS);
86   
87   void EmitPredicateFunctions(formatted_raw_ostream &OS);
88 private:
89   unsigned EmitMatcher(const MatcherNode *N, unsigned Indent,
90                        formatted_raw_ostream &OS);
91   
92   unsigned getNodePredicate(StringRef PredName) {
93     unsigned &Entry = NodePredicateMap[PredName];
94     if (Entry == 0) {
95       NodePredicates.push_back(PredName.str());
96       Entry = NodePredicates.size();
97     }
98     return Entry-1;
99   }
100   unsigned getPatternPredicate(StringRef PredName) {
101     unsigned &Entry = PatternPredicateMap[PredName];
102     if (Entry == 0) {
103       PatternPredicates.push_back(PredName.str());
104       Entry = PatternPredicates.size();
105     }
106     return Entry-1;
107   }
108   
109   unsigned getComplexPat(const ComplexPattern &P) {
110     unsigned &Entry = ComplexPatternMap[&P];
111     if (Entry == 0) {
112       ComplexPatterns.push_back(&P);
113       Entry = ComplexPatterns.size();
114     }
115     return Entry-1;
116   }
117   
118   unsigned getNodeXFormID(Record *Rec) {
119     unsigned &Entry = NodeXFormMap[Rec];
120     if (Entry == 0) {
121       NodeXForms.push_back(Rec);
122       Entry = NodeXForms.size();
123     }
124     return Entry-1;
125   }
126   
127 };
128 } // end anonymous namespace.
129
130 /// EmitMatcherOpcodes - Emit bytes for the specified matcher and return
131 /// the number of bytes emitted.
132 unsigned MatcherTableEmitter::
133 EmitMatcher(const MatcherNode *N, unsigned Indent, formatted_raw_ostream &OS) {
134   OS.PadToColumn(Indent*2);
135   
136   switch (N->getKind()) {
137   case MatcherNode::Push: assert(0 && "Should be handled by caller");
138   case MatcherNode::RecordNode:
139     OS << "OPC_RecordNode,";
140     OS.PadToColumn(CommentIndent) << "// "
141        << cast<RecordMatcherNode>(N)->getWhatFor() << '\n';
142     return 1;
143       
144   case MatcherNode::RecordMemRef:
145     OS << "OPC_RecordMemRef,\n";
146     return 1;
147       
148   case MatcherNode::CaptureFlagInput:
149     OS << "OPC_CaptureFlagInput,\n";
150     return 1;
151       
152   case MatcherNode::MoveChild:
153     OS << "OPC_MoveChild, "
154        << cast<MoveChildMatcherNode>(N)->getChildNo() << ",\n";
155     return 2;
156       
157   case MatcherNode::MoveParent:
158     OS << "OPC_MoveParent,\n";
159     return 1;
160       
161   case MatcherNode::CheckSame:
162     OS << "OPC_CheckSame, "
163        << cast<CheckSameMatcherNode>(N)->getMatchNumber() << ",\n";
164     return 2;
165
166   case MatcherNode::CheckPatternPredicate: {
167     StringRef Pred = cast<CheckPatternPredicateMatcherNode>(N)->getPredicate();
168     OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
169     OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
170     return 2;
171   }
172   case MatcherNode::CheckPredicate: {
173     StringRef Pred = cast<CheckPredicateMatcherNode>(N)->getPredicateName();
174     OS << "OPC_CheckPredicate, " << getNodePredicate(Pred) << ',';
175     OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
176     return 2;
177   }
178
179   case MatcherNode::CheckOpcode:
180     OS << "OPC_CheckOpcode, "
181        << cast<CheckOpcodeMatcherNode>(N)->getOpcodeName() << ",\n";
182     return 2;
183       
184   case MatcherNode::CheckMultiOpcode: {
185     const CheckMultiOpcodeMatcherNode *CMO=cast<CheckMultiOpcodeMatcherNode>(N);
186     OS << "OPC_CheckMultiOpcode, " << CMO->getNumOpcodeNames() << ", ";
187     for (unsigned i = 0, e = CMO->getNumOpcodeNames(); i != e; ++i)
188       OS << CMO->getOpcodeName(i) << ", ";
189     OS << '\n';
190     return 2 + CMO->getNumOpcodeNames();
191   }
192       
193   case MatcherNode::CheckType:
194     OS << "OPC_CheckType, "
195        << getEnumName(cast<CheckTypeMatcherNode>(N)->getType()) << ",\n";
196     return 2;
197
198   case MatcherNode::CheckInteger: {
199     int64_t Val = cast<CheckIntegerMatcherNode>(N)->getValue();
200     OS << "OPC_CheckInteger" << ClassifyInt(Val) << ", ";
201     return EmitInt(Val, OS)+1;
202   }   
203   case MatcherNode::CheckCondCode:
204     OS << "OPC_CheckCondCode, ISD::"
205        << cast<CheckCondCodeMatcherNode>(N)->getCondCodeName() << ",\n";
206     return 2;
207       
208   case MatcherNode::CheckValueType:
209     OS << "OPC_CheckValueType, MVT::"
210        << cast<CheckValueTypeMatcherNode>(N)->getTypeName() << ",\n";
211     return 2;
212
213   case MatcherNode::CheckComplexPat: {
214     const ComplexPattern &Pattern =
215       cast<CheckComplexPatMatcherNode>(N)->getPattern();
216     OS << "OPC_CheckComplexPat, " << getComplexPat(Pattern) << ',';
217     OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
218     OS << ": " << Pattern.getNumOperands() << " operands";
219     if (Pattern.hasProperty(SDNPHasChain))
220       OS << " + chain result and input";
221     OS << '\n';
222     return 2;
223   }
224       
225   case MatcherNode::CheckAndImm: {
226     int64_t Val = cast<CheckAndImmMatcherNode>(N)->getValue();
227     OS << "OPC_CheckAndImm" << ClassifyInt(Val) << ", ";
228     return EmitInt(Val, OS)+1;
229   }
230
231   case MatcherNode::CheckOrImm: {
232     int64_t Val = cast<CheckOrImmMatcherNode>(N)->getValue();
233     OS << "OPC_CheckOrImm" << ClassifyInt(Val) << ", ";
234     return EmitInt(Val, OS)+1;
235   }
236   case MatcherNode::CheckFoldableChainNode:
237     OS << "OPC_CheckFoldableChainNode,\n";
238     return 1;
239   case MatcherNode::CheckChainCompatible:
240     OS << "OPC_CheckChainCompatible, "
241        << cast<CheckChainCompatibleMatcherNode>(N)->getPreviousOp() << ",\n";
242     return 2;
243       
244   case MatcherNode::EmitInteger: {
245     int64_t Val = cast<EmitIntegerMatcherNode>(N)->getValue();
246     OS << "OPC_EmitInteger" << ClassifyInt(Val) << ", "
247        << getEnumName(cast<EmitIntegerMatcherNode>(N)->getVT()) << ", ";
248     return EmitInt(Val, OS)+2;
249   }
250   case MatcherNode::EmitStringInteger: {
251     const std::string &Val = cast<EmitStringIntegerMatcherNode>(N)->getValue();
252     // These should always fit into one byte.
253     OS << "OPC_EmitInteger1, "
254       << getEnumName(cast<EmitStringIntegerMatcherNode>(N)->getVT()) << ", "
255       << Val << ",\n";
256     return 3;
257   }
258       
259   case MatcherNode::EmitRegister:
260     OS << "OPC_EmitRegister, "
261        << getEnumName(cast<EmitRegisterMatcherNode>(N)->getVT()) << ", ";
262     if (Record *R = cast<EmitRegisterMatcherNode>(N)->getReg())
263       OS << getQualifiedName(R) << ",\n";
264     else
265       OS << "0 /*zero_reg*/,\n";
266     return 3;
267       
268   case MatcherNode::EmitConvertToTarget:
269     OS << "OPC_EmitConvertToTarget, "
270        << cast<EmitConvertToTargetMatcherNode>(N)->getSlot() << ",\n";
271     return 2;
272       
273   case MatcherNode::EmitMergeInputChains: {
274     const EmitMergeInputChainsMatcherNode *MN =
275       cast<EmitMergeInputChainsMatcherNode>(N);
276     OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
277     for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
278       OS << MN->getNode(i) << ", ";
279     OS << '\n';
280     return 2+MN->getNumNodes();
281   }
282   case MatcherNode::EmitCopyToReg:
283     OS << "OPC_EmitCopyToReg, "
284        << cast<EmitCopyToRegMatcherNode>(N)->getSrcSlot() << ", "
285        << getQualifiedName(cast<EmitCopyToRegMatcherNode>(N)->getDestPhysReg())
286        << ",\n";
287     return 3;
288   case MatcherNode::EmitNodeXForm: {
289     const EmitNodeXFormMatcherNode *XF = cast<EmitNodeXFormMatcherNode>(N);
290     OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
291        << XF->getSlot() << ',';
292     OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName()<<'\n';
293     return 3;
294   }
295       
296   case MatcherNode::EmitNode: {
297     const EmitNodeMatcherNode *EN = cast<EmitNodeMatcherNode>(N);
298     OS << "OPC_EmitNode, TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
299     
300     if (EN->hasChain())   OS << "|OPFL_Chain";
301     if (EN->hasFlag())    OS << "|OPFL_Flag";
302     if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
303     if (EN->getNumFixedArityOperands() != -1)
304       OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
305     OS << ",\n";
306     
307     OS.PadToColumn(Indent*2+4) << EN->getNumVTs() << "/*#VTs*/, ";
308     for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
309       OS << getEnumName(EN->getVT(i)) << ", ";
310
311     OS << EN->getNumOperands() << "/*#Ops*/, ";
312     for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
313       OS << EN->getOperand(i) << ", ";
314     OS << '\n';
315     return 6+EN->getNumVTs()+EN->getNumOperands();
316   }
317   case MatcherNode::CompleteMatch: {
318     const CompleteMatchMatcherNode *CM = cast<CompleteMatchMatcherNode>(N);
319     OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
320     for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
321       OS << CM->getResult(i) << ", ";
322     OS << '\n';
323     OS.PadToColumn(Indent*2) << "// Src: "
324       << *CM->getPattern().getSrcPattern() << '\n';
325     OS.PadToColumn(Indent*2) << "// Dst: " 
326       << *CM->getPattern().getDstPattern() << '\n';
327     return 2+CM->getNumResults();
328   }
329   }
330   assert(0 && "Unreachable");
331   return 0;
332 }
333
334 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
335 unsigned MatcherTableEmitter::
336 EmitMatcherList(const MatcherNode *N, unsigned Indent, unsigned CurrentIdx,
337                 formatted_raw_ostream &OS) {
338   unsigned Size = 0;
339   while (N) {
340     // Push is a special case since it is binary.
341     if (const PushMatcherNode *PMN = dyn_cast<PushMatcherNode>(N)) {
342       // We need to encode the child and the offset of the failure code before
343       // emitting either of them.  Handle this by buffering the output into a
344       // string while we get the size.
345       SmallString<128> TmpBuf;
346       unsigned NextSize;
347       {
348         raw_svector_ostream OS(TmpBuf);
349         formatted_raw_ostream FOS(OS);
350         NextSize = EmitMatcherList(cast<PushMatcherNode>(N)->getNext(),
351                                    Indent+1, CurrentIdx+2, FOS);
352       }
353
354       // In the unlikely event that we have something too big to emit with a
355       // one byte offset, regenerate it with a two-byte one.
356       if (NextSize > 255) {
357         TmpBuf.clear();
358         raw_svector_ostream OS(TmpBuf);
359         formatted_raw_ostream FOS(OS);
360         NextSize = EmitMatcherList(cast<PushMatcherNode>(N)->getNext(),
361                                    Indent+1, CurrentIdx+3, FOS);
362         if (NextSize > 65535) {
363           errs() <<
364             "Tblgen internal error: can't handle pattern this complex yet\n";
365           exit(1);
366         }
367       }
368       
369       OS << "/*" << CurrentIdx << "*/";
370       OS.PadToColumn(Indent*2);
371       
372       if (NextSize < 256)
373         OS << "OPC_Push, " << NextSize << ",\n";
374       else
375         OS << "OPC_Push2, " << (NextSize&255) << ", " << (NextSize>>8) << ",\n";
376       OS << TmpBuf.str();
377       
378       Size += 2+NextSize;
379       CurrentIdx += 2+NextSize;
380       N = PMN->getFailure();
381       continue;
382     }
383   
384     OS << "/*" << CurrentIdx << "*/";
385     unsigned MatcherSize = EmitMatcher(N, Indent, OS);
386     Size += MatcherSize;
387     CurrentIdx += MatcherSize;
388     
389     // If there are other nodes in this list, iterate to them, otherwise we're
390     // done.
391     N = N->getNext();
392   }
393   return Size;
394 }
395
396 void MatcherTableEmitter::EmitPredicateFunctions(formatted_raw_ostream &OS) {
397   // FIXME: Don't build off the DAGISelEmitter's predicates, emit them directly
398   // here into the case stmts.
399   
400   // Emit pattern predicates.
401   OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
402   OS << "  switch (PredNo) {\n";
403   OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
404   for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
405     OS << "  case " << i << ": return "  << PatternPredicates[i] << ";\n";
406   OS << "  }\n";
407   OS << "}\n\n";
408
409   // Emit Node predicates.
410   OS << "bool CheckNodePredicate(SDNode *N, unsigned PredNo) const {\n";
411   OS << "  switch (PredNo) {\n";
412   OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
413   for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i)
414     OS << "  case " << i << ": return "  << NodePredicates[i] << "(N);\n";
415   OS << "  }\n";
416   OS << "}\n\n";
417   
418   // Emit CompletePattern matchers.
419   // FIXME: This should be const.
420   OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
421   OS << "      unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
422   OS << "  switch (PatternNo) {\n";
423   OS << "  default: assert(0 && \"Invalid pattern # in table?\");\n";
424   for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
425     const ComplexPattern &P = *ComplexPatterns[i];
426     unsigned NumOps = P.getNumOperands();
427
428     if (P.hasProperty(SDNPHasChain))
429       ++NumOps;  // Get the chained node too.
430     
431     OS << "  case " << i << ":\n";
432     OS << "    Result.resize(Result.size()+" << NumOps << ");\n";
433     OS << "    return "  << P.getSelectFunc();
434
435     // FIXME: Temporary hack until old isel dies.
436     if (P.hasProperty(SDNPHasChain))
437       OS << "XXX";
438     
439     OS << "(Root, N";
440     for (unsigned i = 0; i != NumOps; ++i)
441       OS << ", Result[Result.size()-" << (NumOps-i) << ']';
442     OS << ");\n";
443   }
444   OS << "  }\n";
445   OS << "}\n\n";
446   
447   // Emit SDNodeXForm handlers.
448   // FIXME: This should be const.
449   OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
450   OS << "  switch (XFormNo) {\n";
451   OS << "  default: assert(0 && \"Invalid xform # in table?\");\n";
452   
453   // FIXME: The node xform could take SDValue's instead of SDNode*'s.
454   for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i)
455     OS << "  case " << i << ": return Transform_" << NodeXForms[i]->getName()
456        << "(V.getNode());\n";
457   OS << "  }\n";
458   OS << "}\n\n";
459 }
460
461
462 void llvm::EmitMatcherTable(const MatcherNode *Matcher, raw_ostream &O) {
463   formatted_raw_ostream OS(O);
464   
465   OS << "// The main instruction selector code.\n";
466   OS << "SDNode *SelectCode2(SDNode *N) {\n";
467
468   MatcherTableEmitter MatcherEmitter;
469
470   OS << "  // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
471   OS << "  #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
472   OS << "  static const unsigned char MatcherTable[] = {\n";
473   unsigned TotalSize = MatcherEmitter.EmitMatcherList(Matcher, 5, 0, OS);
474   OS << "    0\n  }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
475   OS << "  #undef TARGET_OPCODE\n";
476   OS << "  return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
477   OS << "\n";
478   
479   // Next up, emit the function for node and pattern predicates:
480   MatcherEmitter.EmitPredicateFunctions(OS);
481 }