The new isel was not properly handling patterns that covered
[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 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
131 /// bytes emitted.
132 static unsigned EmitVBRValue(unsigned Val, raw_ostream &OS) {
133   if (Val <= 127) {
134     OS << Val << ", ";
135     return 1;
136   }
137   
138   unsigned InVal = Val;
139   unsigned NumBytes = 0;
140   while (Val >= 128) {
141     OS << (Val&127) << "|128,";
142     Val >>= 7;
143     ++NumBytes;
144   }
145   OS << Val << "/*" << InVal << "*/, ";
146   return NumBytes+1;
147 }
148
149 /// EmitMatcherOpcodes - Emit bytes for the specified matcher and return
150 /// the number of bytes emitted.
151 unsigned MatcherTableEmitter::
152 EmitMatcher(const MatcherNode *N, unsigned Indent, formatted_raw_ostream &OS) {
153   OS.PadToColumn(Indent*2);
154   
155   switch (N->getKind()) {
156   case MatcherNode::Push: assert(0 && "Should be handled by caller");
157   case MatcherNode::RecordNode:
158     OS << "OPC_RecordNode,";
159     OS.PadToColumn(CommentIndent) << "// "
160        << cast<RecordMatcherNode>(N)->getWhatFor() << '\n';
161     return 1;
162       
163   case MatcherNode::RecordMemRef:
164     OS << "OPC_RecordMemRef,\n";
165     return 1;
166       
167   case MatcherNode::CaptureFlagInput:
168     OS << "OPC_CaptureFlagInput,\n";
169     return 1;
170       
171   case MatcherNode::MoveChild:
172     OS << "OPC_MoveChild, "
173        << cast<MoveChildMatcherNode>(N)->getChildNo() << ",\n";
174     return 2;
175       
176   case MatcherNode::MoveParent:
177     OS << "OPC_MoveParent,\n";
178     return 1;
179       
180   case MatcherNode::CheckSame:
181     OS << "OPC_CheckSame, "
182        << cast<CheckSameMatcherNode>(N)->getMatchNumber() << ",\n";
183     return 2;
184
185   case MatcherNode::CheckPatternPredicate: {
186     StringRef Pred = cast<CheckPatternPredicateMatcherNode>(N)->getPredicate();
187     OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
188     OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
189     return 2;
190   }
191   case MatcherNode::CheckPredicate: {
192     StringRef Pred = cast<CheckPredicateMatcherNode>(N)->getPredicateName();
193     OS << "OPC_CheckPredicate, " << getNodePredicate(Pred) << ',';
194     OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
195     return 2;
196   }
197
198   case MatcherNode::CheckOpcode:
199     OS << "OPC_CheckOpcode, "
200        << cast<CheckOpcodeMatcherNode>(N)->getOpcodeName() << ",\n";
201     return 2;
202       
203   case MatcherNode::CheckMultiOpcode: {
204     const CheckMultiOpcodeMatcherNode *CMO=cast<CheckMultiOpcodeMatcherNode>(N);
205     OS << "OPC_CheckMultiOpcode, " << CMO->getNumOpcodeNames() << ", ";
206     for (unsigned i = 0, e = CMO->getNumOpcodeNames(); i != e; ++i)
207       OS << CMO->getOpcodeName(i) << ", ";
208     OS << '\n';
209     return 2 + CMO->getNumOpcodeNames();
210   }
211       
212   case MatcherNode::CheckType:
213     OS << "OPC_CheckType, "
214        << getEnumName(cast<CheckTypeMatcherNode>(N)->getType()) << ",\n";
215     return 2;
216
217   case MatcherNode::CheckInteger: {
218     int64_t Val = cast<CheckIntegerMatcherNode>(N)->getValue();
219     OS << "OPC_CheckInteger" << ClassifyInt(Val) << ", ";
220     return EmitInt(Val, OS)+1;
221   }   
222   case MatcherNode::CheckCondCode:
223     OS << "OPC_CheckCondCode, ISD::"
224        << cast<CheckCondCodeMatcherNode>(N)->getCondCodeName() << ",\n";
225     return 2;
226       
227   case MatcherNode::CheckValueType:
228     OS << "OPC_CheckValueType, MVT::"
229        << cast<CheckValueTypeMatcherNode>(N)->getTypeName() << ",\n";
230     return 2;
231
232   case MatcherNode::CheckComplexPat: {
233     const ComplexPattern &Pattern =
234       cast<CheckComplexPatMatcherNode>(N)->getPattern();
235     OS << "OPC_CheckComplexPat, " << getComplexPat(Pattern) << ',';
236     OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
237     OS << ": " << Pattern.getNumOperands() << " operands";
238     if (Pattern.hasProperty(SDNPHasChain))
239       OS << " + chain result and input";
240     OS << '\n';
241     return 2;
242   }
243       
244   case MatcherNode::CheckAndImm: {
245     int64_t Val = cast<CheckAndImmMatcherNode>(N)->getValue();
246     OS << "OPC_CheckAndImm" << ClassifyInt(Val) << ", ";
247     return EmitInt(Val, OS)+1;
248   }
249
250   case MatcherNode::CheckOrImm: {
251     int64_t Val = cast<CheckOrImmMatcherNode>(N)->getValue();
252     OS << "OPC_CheckOrImm" << ClassifyInt(Val) << ", ";
253     return EmitInt(Val, OS)+1;
254   }
255   case MatcherNode::CheckFoldableChainNode:
256     OS << "OPC_CheckFoldableChainNode,\n";
257     return 1;
258   case MatcherNode::CheckChainCompatible:
259     OS << "OPC_CheckChainCompatible, "
260        << cast<CheckChainCompatibleMatcherNode>(N)->getPreviousOp() << ",\n";
261     return 2;
262       
263   case MatcherNode::EmitInteger: {
264     int64_t Val = cast<EmitIntegerMatcherNode>(N)->getValue();
265     OS << "OPC_EmitInteger" << ClassifyInt(Val) << ", "
266        << getEnumName(cast<EmitIntegerMatcherNode>(N)->getVT()) << ", ";
267     return EmitInt(Val, OS)+2;
268   }
269   case MatcherNode::EmitStringInteger: {
270     const std::string &Val = cast<EmitStringIntegerMatcherNode>(N)->getValue();
271     // These should always fit into one byte.
272     OS << "OPC_EmitInteger1, "
273       << getEnumName(cast<EmitStringIntegerMatcherNode>(N)->getVT()) << ", "
274       << Val << ",\n";
275     return 3;
276   }
277       
278   case MatcherNode::EmitRegister:
279     OS << "OPC_EmitRegister, "
280        << getEnumName(cast<EmitRegisterMatcherNode>(N)->getVT()) << ", ";
281     if (Record *R = cast<EmitRegisterMatcherNode>(N)->getReg())
282       OS << getQualifiedName(R) << ",\n";
283     else
284       OS << "0 /*zero_reg*/,\n";
285     return 3;
286       
287   case MatcherNode::EmitConvertToTarget:
288     OS << "OPC_EmitConvertToTarget, "
289        << cast<EmitConvertToTargetMatcherNode>(N)->getSlot() << ",\n";
290     return 2;
291       
292   case MatcherNode::EmitMergeInputChains: {
293     const EmitMergeInputChainsMatcherNode *MN =
294       cast<EmitMergeInputChainsMatcherNode>(N);
295     OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
296     for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
297       OS << MN->getNode(i) << ", ";
298     OS << '\n';
299     return 2+MN->getNumNodes();
300   }
301   case MatcherNode::EmitCopyToReg:
302     OS << "OPC_EmitCopyToReg, "
303        << cast<EmitCopyToRegMatcherNode>(N)->getSrcSlot() << ", "
304        << getQualifiedName(cast<EmitCopyToRegMatcherNode>(N)->getDestPhysReg())
305        << ",\n";
306     return 3;
307   case MatcherNode::EmitNodeXForm: {
308     const EmitNodeXFormMatcherNode *XF = cast<EmitNodeXFormMatcherNode>(N);
309     OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
310        << XF->getSlot() << ',';
311     OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName()<<'\n';
312     return 3;
313   }
314       
315   case MatcherNode::EmitNode: {
316     const EmitNodeMatcherNode *EN = cast<EmitNodeMatcherNode>(N);
317     OS << "OPC_EmitNode, TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
318     
319     if (EN->hasChain())   OS << "|OPFL_Chain";
320     if (EN->hasFlag())    OS << "|OPFL_Flag";
321     if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
322     if (EN->getNumFixedArityOperands() != -1)
323       OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
324     OS << ",\n";
325     
326     OS.PadToColumn(Indent*2+4) << EN->getNumVTs() << "/*#VTs*/, ";
327     for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
328       OS << getEnumName(EN->getVT(i)) << ", ";
329
330     OS << EN->getNumOperands() << "/*#Ops*/, ";
331     unsigned NumOperandBytes = 0;
332     for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i) {
333       // We emit the operand numbers in VBR encoded format, in case the number
334       // is too large to represent with a byte.
335       NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
336     }
337     OS << '\n';
338     return 6+EN->getNumVTs()+NumOperandBytes;
339   }
340   case MatcherNode::MarkFlagResults: {
341     const MarkFlagResultsMatcherNode *CFR = cast<MarkFlagResultsMatcherNode>(N);
342     OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", ";
343     unsigned NumOperandBytes = 0;
344     for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i)
345       NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS);
346     OS << '\n';
347     return 2+NumOperandBytes;
348   }
349   case MatcherNode::CompleteMatch: {
350     const CompleteMatchMatcherNode *CM = cast<CompleteMatchMatcherNode>(N);
351     OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
352     unsigned NumResultBytes = 0;
353     for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
354       NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
355     OS << '\n';
356     OS.PadToColumn(Indent*2) << "// Src: "
357       << *CM->getPattern().getSrcPattern() << '\n';
358     OS.PadToColumn(Indent*2) << "// Dst: " 
359       << *CM->getPattern().getDstPattern() << '\n';
360     return 2 + NumResultBytes;
361   }
362   }
363   assert(0 && "Unreachable");
364   return 0;
365 }
366
367 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
368 unsigned MatcherTableEmitter::
369 EmitMatcherList(const MatcherNode *N, unsigned Indent, unsigned CurrentIdx,
370                 formatted_raw_ostream &OS) {
371   unsigned Size = 0;
372   while (N) {
373     // Push is a special case since it is binary.
374     if (const PushMatcherNode *PMN = dyn_cast<PushMatcherNode>(N)) {
375       // We need to encode the child and the offset of the failure code before
376       // emitting either of them.  Handle this by buffering the output into a
377       // string while we get the size.
378       SmallString<128> TmpBuf;
379       unsigned NextSize;
380       {
381         raw_svector_ostream OS(TmpBuf);
382         formatted_raw_ostream FOS(OS);
383         NextSize = EmitMatcherList(cast<PushMatcherNode>(N)->getNext(),
384                                    Indent+1, CurrentIdx+2, FOS);
385       }
386
387       // In the unlikely event that we have something too big to emit with a
388       // one byte offset, regenerate it with a two-byte one.
389       if (NextSize > 255) {
390         TmpBuf.clear();
391         raw_svector_ostream OS(TmpBuf);
392         formatted_raw_ostream FOS(OS);
393         NextSize = EmitMatcherList(cast<PushMatcherNode>(N)->getNext(),
394                                    Indent+1, CurrentIdx+3, FOS);
395         if (NextSize > 65535) {
396           errs() <<
397             "Tblgen internal error: can't handle pattern this complex yet\n";
398           exit(1);
399         }
400       }
401       
402       OS << "/*" << CurrentIdx << "*/";
403       OS.PadToColumn(Indent*2);
404       
405       if (NextSize < 256)
406         OS << "OPC_Push, " << NextSize << ",\n";
407       else
408         OS << "OPC_Push2, " << (NextSize&255) << ", " << (NextSize>>8) << ",\n";
409       OS << TmpBuf.str();
410       
411       Size += 2+NextSize;
412       CurrentIdx += 2+NextSize;
413       N = PMN->getFailure();
414       continue;
415     }
416   
417     OS << "/*" << CurrentIdx << "*/";
418     unsigned MatcherSize = EmitMatcher(N, Indent, OS);
419     Size += MatcherSize;
420     CurrentIdx += MatcherSize;
421     
422     // If there are other nodes in this list, iterate to them, otherwise we're
423     // done.
424     N = N->getNext();
425   }
426   return Size;
427 }
428
429 void MatcherTableEmitter::EmitPredicateFunctions(formatted_raw_ostream &OS) {
430   // FIXME: Don't build off the DAGISelEmitter's predicates, emit them directly
431   // here into the case stmts.
432   
433   // Emit pattern predicates.
434   OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
435   OS << "  switch (PredNo) {\n";
436   OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
437   for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
438     OS << "  case " << i << ": return "  << PatternPredicates[i] << ";\n";
439   OS << "  }\n";
440   OS << "}\n\n";
441
442   // Emit Node predicates.
443   OS << "bool CheckNodePredicate(SDNode *N, unsigned PredNo) const {\n";
444   OS << "  switch (PredNo) {\n";
445   OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
446   for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i)
447     OS << "  case " << i << ": return "  << NodePredicates[i] << "(N);\n";
448   OS << "  }\n";
449   OS << "}\n\n";
450   
451   // Emit CompletePattern matchers.
452   // FIXME: This should be const.
453   OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
454   OS << "      unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
455   OS << "  switch (PatternNo) {\n";
456   OS << "  default: assert(0 && \"Invalid pattern # in table?\");\n";
457   for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
458     const ComplexPattern &P = *ComplexPatterns[i];
459     unsigned NumOps = P.getNumOperands();
460
461     if (P.hasProperty(SDNPHasChain))
462       ++NumOps;  // Get the chained node too.
463     
464     OS << "  case " << i << ":\n";
465     OS << "    Result.resize(Result.size()+" << NumOps << ");\n";
466     OS << "    return "  << P.getSelectFunc();
467
468     // FIXME: Temporary hack until old isel dies.
469     if (P.hasProperty(SDNPHasChain))
470       OS << "XXX";
471     
472     OS << "(Root, N";
473     for (unsigned i = 0; i != NumOps; ++i)
474       OS << ", Result[Result.size()-" << (NumOps-i) << ']';
475     OS << ");\n";
476   }
477   OS << "  }\n";
478   OS << "}\n\n";
479   
480   // Emit SDNodeXForm handlers.
481   // FIXME: This should be const.
482   OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
483   OS << "  switch (XFormNo) {\n";
484   OS << "  default: assert(0 && \"Invalid xform # in table?\");\n";
485   
486   // FIXME: The node xform could take SDValue's instead of SDNode*'s.
487   for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i)
488     OS << "  case " << i << ": return Transform_" << NodeXForms[i]->getName()
489        << "(V.getNode());\n";
490   OS << "  }\n";
491   OS << "}\n\n";
492 }
493
494
495 void llvm::EmitMatcherTable(const MatcherNode *Matcher, raw_ostream &O) {
496   formatted_raw_ostream OS(O);
497   
498   OS << "// The main instruction selector code.\n";
499   OS << "SDNode *SelectCode2(SDNode *N) {\n";
500
501   MatcherTableEmitter MatcherEmitter;
502
503   OS << "  // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
504   OS << "  #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
505   OS << "  static const unsigned char MatcherTable[] = {\n";
506   unsigned TotalSize = MatcherEmitter.EmitMatcherList(Matcher, 5, 0, OS);
507   OS << "    0\n  }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
508   OS << "  #undef TARGET_OPCODE\n";
509   OS << "  return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
510   OS << "\n";
511   
512   // Next up, emit the function for node and pattern predicates:
513   MatcherEmitter.EmitPredicateFunctions(OS);
514 }