emit table indexes before each row so that it is debuggable.
[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::CheckType:
185     OS << "OPC_CheckType, "
186        << getEnumName(cast<CheckTypeMatcherNode>(N)->getType()) << ",\n";
187     return 2;
188
189   case MatcherNode::CheckInteger: {
190     int64_t Val = cast<CheckIntegerMatcherNode>(N)->getValue();
191     OS << "OPC_CheckInteger" << ClassifyInt(Val) << ", ";
192     return EmitInt(Val, OS)+1;
193   }   
194   case MatcherNode::CheckCondCode:
195     OS << "OPC_CheckCondCode, ISD::"
196        << cast<CheckCondCodeMatcherNode>(N)->getCondCodeName() << ",\n";
197     return 2;
198       
199   case MatcherNode::CheckValueType:
200     OS << "OPC_CheckValueType, MVT::"
201        << cast<CheckValueTypeMatcherNode>(N)->getTypeName() << ",\n";
202     return 2;
203
204   case MatcherNode::CheckComplexPat: {
205     const ComplexPattern &Pattern =
206       cast<CheckComplexPatMatcherNode>(N)->getPattern();
207     OS << "OPC_CheckComplexPat, " << getComplexPat(Pattern) << ',';
208     OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
209     OS << ": " << Pattern.getNumOperands() << " operands";
210     if (Pattern.hasProperty(SDNPHasChain))
211       OS << " + chain result and input";
212     OS << '\n';
213     return 2;
214   }
215       
216   case MatcherNode::CheckAndImm: {
217     int64_t Val = cast<CheckAndImmMatcherNode>(N)->getValue();
218     OS << "OPC_CheckAndImm" << ClassifyInt(Val) << ", ";
219     return EmitInt(Val, OS)+1;
220   }
221
222   case MatcherNode::CheckOrImm: {
223     int64_t Val = cast<CheckOrImmMatcherNode>(N)->getValue();
224     OS << "OPC_CheckOrImm" << ClassifyInt(Val) << ", ";
225     return EmitInt(Val, OS)+1;
226   }
227   case MatcherNode::CheckFoldableChainNode:
228     OS << "OPC_CheckFoldableChainNode,\n";
229     return 1;
230   case MatcherNode::CheckChainCompatible:
231     OS << "OPC_CheckChainCompatible, "
232        << cast<CheckChainCompatibleMatcherNode>(N)->getPreviousOp() << ",\n";
233     return 2;
234       
235   case MatcherNode::EmitInteger: {
236     int64_t Val = cast<EmitIntegerMatcherNode>(N)->getValue();
237     OS << "OPC_EmitInteger" << ClassifyInt(Val) << ", "
238        << getEnumName(cast<EmitIntegerMatcherNode>(N)->getVT()) << ", ";
239     return EmitInt(Val, OS)+2;
240   }
241   case MatcherNode::EmitStringInteger: {
242     const std::string &Val = cast<EmitStringIntegerMatcherNode>(N)->getValue();
243     // These should always fit into one byte.
244     OS << "OPC_EmitInteger1, "
245       << getEnumName(cast<EmitStringIntegerMatcherNode>(N)->getVT()) << ", "
246       << Val << ",\n";
247     return 3;
248   }
249       
250   case MatcherNode::EmitRegister:
251     OS << "OPC_EmitRegister, "
252        << getEnumName(cast<EmitRegisterMatcherNode>(N)->getVT()) << ", ";
253     if (Record *R = cast<EmitRegisterMatcherNode>(N)->getReg())
254       OS << getQualifiedName(R) << ",\n";
255     else
256       OS << "0 /*zero_reg*/,\n";
257     return 3;
258       
259   case MatcherNode::EmitConvertToTarget:
260     OS << "OPC_EmitConvertToTarget, "
261        << cast<EmitConvertToTargetMatcherNode>(N)->getSlot() << ",\n";
262     return 2;
263       
264   case MatcherNode::EmitMergeInputChains: {
265     const EmitMergeInputChainsMatcherNode *MN =
266       cast<EmitMergeInputChainsMatcherNode>(N);
267     OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
268     for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
269       OS << MN->getNode(i) << ", ";
270     OS << '\n';
271     return 2+MN->getNumNodes();
272   }
273   case MatcherNode::EmitCopyToReg:
274     OS << "OPC_EmitCopyToReg, "
275        << cast<EmitCopyToRegMatcherNode>(N)->getSrcSlot() << ", "
276        << getQualifiedName(cast<EmitCopyToRegMatcherNode>(N)->getDestPhysReg())
277        << ",\n";
278     return 3;
279   case MatcherNode::EmitNodeXForm: {
280     const EmitNodeXFormMatcherNode *XF = cast<EmitNodeXFormMatcherNode>(N);
281     OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
282        << XF->getSlot() << ',';
283     OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName()<<'\n';
284     return 3;
285   }
286       
287   case MatcherNode::EmitNode: {
288     const EmitNodeMatcherNode *EN = cast<EmitNodeMatcherNode>(N);
289     OS << "OPC_EmitNode, TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
290     
291     if (EN->hasChain())   OS << "|OPFL_Chain";
292     if (EN->hasFlag())    OS << "|OPFL_Flag";
293     if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
294     if (EN->getNumFixedArityOperands() != -1)
295       OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
296     OS << ",\n";
297     
298     OS.PadToColumn(Indent*2+4) << EN->getNumVTs() << "/*#VTs*/, ";
299     for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
300       OS << getEnumName(EN->getVT(i)) << ", ";
301
302     OS << EN->getNumOperands() << "/*#Ops*/, ";
303     for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
304       OS << EN->getOperand(i) << ", ";
305     OS << '\n';
306     return 6+EN->getNumVTs()+EN->getNumOperands();
307   }
308   case MatcherNode::CompleteMatch: {
309     const CompleteMatchMatcherNode *CM = cast<CompleteMatchMatcherNode>(N);
310     OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
311     for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
312       OS << CM->getResult(i) << ", ";
313     OS << '\n';
314     OS.PadToColumn(Indent*2) << "// Src: "
315       << *CM->getPattern().getSrcPattern() << '\n';
316     OS.PadToColumn(Indent*2) << "// Dst: " 
317       << *CM->getPattern().getDstPattern() << '\n';
318     return 2+CM->getNumResults();
319   }
320   }
321   assert(0 && "Unreachable");
322   return 0;
323 }
324
325 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
326 unsigned MatcherTableEmitter::
327 EmitMatcherList(const MatcherNode *N, unsigned Indent, unsigned CurrentIdx,
328                 formatted_raw_ostream &OS) {
329   unsigned Size = 0;
330   while (N) {
331     // Push is a special case since it is binary.
332     if (const PushMatcherNode *PMN = dyn_cast<PushMatcherNode>(N)) {
333       // We need to encode the child and the offset of the failure code before
334       // emitting either of them.  Handle this by buffering the output into a
335       // string while we get the size.
336       SmallString<128> TmpBuf;
337       unsigned NextSize;
338       {
339         raw_svector_ostream OS(TmpBuf);
340         formatted_raw_ostream FOS(OS);
341         NextSize = EmitMatcherList(cast<PushMatcherNode>(N)->getNext(),
342                                    Indent+1, CurrentIdx+2, FOS);
343       }
344       
345       if (NextSize > 255) {
346         errs() <<
347           "Tblgen internal error: can't handle predicate this complex yet\n";
348         // FIXME: exit(1);
349       }
350       
351       OS << "/*" << CurrentIdx << "*/";
352       OS.PadToColumn(Indent*2);
353       OS << "OPC_Push, " << NextSize << ",\n";
354       OS << TmpBuf.str();
355       
356       Size += 2+NextSize;
357       CurrentIdx += 2+NextSize;
358       N = PMN->getFailure();
359       continue;
360     }
361   
362     OS << "/*" << CurrentIdx << "*/";
363     unsigned MatcherSize = EmitMatcher(N, Indent, OS);
364     Size += MatcherSize;
365     CurrentIdx += MatcherSize;
366     
367     // If there are other nodes in this list, iterate to them, otherwise we're
368     // done.
369     N = N->getNext();
370   }
371   return Size;
372 }
373
374 void MatcherTableEmitter::EmitPredicateFunctions(formatted_raw_ostream &OS) {
375   // FIXME: Don't build off the DAGISelEmitter's predicates, emit them directly
376   // here into the case stmts.
377   
378   // Emit pattern predicates.
379   OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
380   OS << "  switch (PredNo) {\n";
381   OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
382   for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
383     OS << "  case " << i << ": return "  << PatternPredicates[i] << ";\n";
384   OS << "  }\n";
385   OS << "}\n\n";
386
387   // Emit Node predicates.
388   OS << "bool CheckNodePredicate(SDNode *N, unsigned PredNo) const {\n";
389   OS << "  switch (PredNo) {\n";
390   OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
391   for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i)
392     OS << "  case " << i << ": return "  << NodePredicates[i] << "(N);\n";
393   OS << "  }\n";
394   OS << "}\n\n";
395   
396   // Emit CompletePattern matchers.
397   // FIXME: This should be const.
398   OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
399   OS << "      unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
400   OS << "  switch (PatternNo) {\n";
401   OS << "  default: assert(0 && \"Invalid pattern # in table?\");\n";
402   for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
403     const ComplexPattern &P = *ComplexPatterns[i];
404     unsigned NumOps = P.getNumOperands();
405
406     if (P.hasProperty(SDNPHasChain))
407       ++NumOps;  // Get the chained node too.
408     
409     OS << "  case " << i << ":\n";
410     OS << "    Result.resize(Result.size()+" << NumOps << ");\n";
411     OS << "    return "  << P.getSelectFunc();
412
413     // FIXME: Temporary hack until old isel dies.
414     if (P.hasProperty(SDNPHasChain))
415       OS << "XXX";
416     
417     OS << "(Root, N";
418     for (unsigned i = 0; i != NumOps; ++i)
419       OS << ", Result[Result.size()-" << (NumOps-i) << ']';
420     OS << ");\n";
421   }
422   OS << "  }\n";
423   OS << "}\n\n";
424   
425   // Emit SDNodeXForm handlers.
426   // FIXME: This should be const.
427   OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
428   OS << "  switch (XFormNo) {\n";
429   OS << "  default: assert(0 && \"Invalid xform # in table?\");\n";
430   
431   // FIXME: The node xform could take SDValue's instead of SDNode*'s.
432   for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i)
433     OS << "  case " << i << ": return Transform_" << NodeXForms[i]->getName()
434        << "(V.getNode());\n";
435   OS << "  }\n";
436   OS << "}\n\n";
437 }
438
439
440 void llvm::EmitMatcherTable(const MatcherNode *Matcher, raw_ostream &O) {
441   formatted_raw_ostream OS(O);
442   
443   OS << "// The main instruction selector code.\n";
444   OS << "SDNode *SelectCode2(SDNode *N) {\n";
445
446   MatcherTableEmitter MatcherEmitter;
447
448   OS << "  // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
449   OS << "  #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
450   OS << "  static const unsigned char MatcherTable[] = {\n";
451   unsigned TotalSize = MatcherEmitter.EmitMatcherList(Matcher, 5, 0, OS);
452   OS << "    0\n  }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
453   OS << "  #undef TARGET_OPCODE\n";
454   OS << "  return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
455   OS << "\n";
456   
457   // Next up, emit the function for node and pattern predicates:
458   MatcherEmitter.EmitPredicateFunctions(OS);
459 }