change the new isel matcher to emit ComplexPattern matches
[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/CommandLine.h"
21 #include "llvm/Support/FormattedStream.h"
22 using namespace llvm;
23
24 enum {
25   CommentIndent = 30
26 };
27
28 // To reduce generated source code size.
29 static cl::opt<bool>
30 OmitComments("omit-comments", cl::desc("Do not generate comments"),
31              cl::init(false));
32
33 namespace {
34 class MatcherTableEmitter {
35   StringMap<unsigned> NodePredicateMap, PatternPredicateMap;
36   std::vector<std::string> NodePredicates, PatternPredicates;
37
38   DenseMap<const ComplexPattern*, unsigned> ComplexPatternMap;
39   std::vector<const ComplexPattern*> ComplexPatterns;
40
41
42   DenseMap<Record*, unsigned> NodeXFormMap;
43   std::vector<Record*> NodeXForms;
44
45   // Per opcode frequence count. 
46   std::vector<unsigned> Histogram;
47 public:
48   MatcherTableEmitter() {}
49
50   unsigned EmitMatcherList(const Matcher *N, unsigned Indent,
51                            unsigned StartIdx, formatted_raw_ostream &OS);
52   
53   void EmitPredicateFunctions(const CodeGenDAGPatterns &CGP,
54                               formatted_raw_ostream &OS);
55   
56   void EmitHistogram(formatted_raw_ostream &OS);
57 private:
58   unsigned EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
59                        formatted_raw_ostream &OS);
60   
61   unsigned getNodePredicate(StringRef PredName) {
62     unsigned &Entry = NodePredicateMap[PredName];
63     if (Entry == 0) {
64       NodePredicates.push_back(PredName.str());
65       Entry = NodePredicates.size();
66     }
67     return Entry-1;
68   }
69   unsigned getPatternPredicate(StringRef PredName) {
70     unsigned &Entry = PatternPredicateMap[PredName];
71     if (Entry == 0) {
72       PatternPredicates.push_back(PredName.str());
73       Entry = PatternPredicates.size();
74     }
75     return Entry-1;
76   }
77   
78   unsigned getComplexPat(const ComplexPattern &P) {
79     unsigned &Entry = ComplexPatternMap[&P];
80     if (Entry == 0) {
81       ComplexPatterns.push_back(&P);
82       Entry = ComplexPatterns.size();
83     }
84     return Entry-1;
85   }
86   
87   unsigned getNodeXFormID(Record *Rec) {
88     unsigned &Entry = NodeXFormMap[Rec];
89     if (Entry == 0) {
90       NodeXForms.push_back(Rec);
91       Entry = NodeXForms.size();
92     }
93     return Entry-1;
94   }
95   
96 };
97 } // end anonymous namespace.
98
99 static unsigned GetVBRSize(unsigned Val) {
100   if (Val <= 127) return 1;
101   
102   unsigned NumBytes = 0;
103   while (Val >= 128) {
104     Val >>= 7;
105     ++NumBytes;
106   }
107   return NumBytes+1;
108 }
109
110 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
111 /// bytes emitted.
112 static uint64_t EmitVBRValue(uint64_t Val, raw_ostream &OS) {
113   if (Val <= 127) {
114     OS << Val << ", ";
115     return 1;
116   }
117   
118   uint64_t InVal = Val;
119   unsigned NumBytes = 0;
120   while (Val >= 128) {
121     OS << (Val&127) << "|128,";
122     Val >>= 7;
123     ++NumBytes;
124   }
125   OS << Val;
126   if (!OmitComments)
127     OS << "/*" << InVal << "*/";
128   OS << ", ";
129   return NumBytes+1;
130 }
131
132 /// EmitMatcherOpcodes - Emit bytes for the specified matcher and return
133 /// the number of bytes emitted.
134 unsigned MatcherTableEmitter::
135 EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
136             formatted_raw_ostream &OS) {
137   OS.PadToColumn(Indent*2);
138   
139   switch (N->getKind()) {
140   case Matcher::Scope: {
141     const ScopeMatcher *SM = cast<ScopeMatcher>(N);
142     assert(SM->getNext() == 0 && "Shouldn't have next after scope");
143     
144     unsigned StartIdx = CurrentIdx;
145     
146     // Emit all of the children.
147     for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
148       if (i == 0) {
149         OS << "OPC_Scope, ";
150         ++CurrentIdx;
151       } else  {
152         if (!OmitComments) {
153           OS << "/*" << CurrentIdx << "*/";
154           OS.PadToColumn(Indent*2) << "/*Scope*/ ";
155         } else
156           OS.PadToColumn(Indent*2);
157       }
158
159       // We need to encode the child and the offset of the failure code before
160       // emitting either of them.  Handle this by buffering the output into a
161       // string while we get the size.  Unfortunately, the offset of the
162       // children depends on the VBR size of the child, so for large children we
163       // have to iterate a bit.
164       SmallString<128> TmpBuf;
165       unsigned ChildSize = 0;
166       unsigned VBRSize = 0;
167       do {
168         VBRSize = GetVBRSize(ChildSize);
169         
170         TmpBuf.clear();
171         raw_svector_ostream OS(TmpBuf);
172         formatted_raw_ostream FOS(OS);
173         ChildSize = EmitMatcherList(SM->getChild(i), Indent+1,
174                                     CurrentIdx+VBRSize, FOS);
175       } while (GetVBRSize(ChildSize) != VBRSize);
176       
177       assert(ChildSize != 0 && "Should not have a zero-sized child!");
178     
179       CurrentIdx += EmitVBRValue(ChildSize, OS);
180       if (!OmitComments) {
181         OS << "/*->" << CurrentIdx+ChildSize << "*/";
182       
183         if (i == 0)
184           OS.PadToColumn(CommentIndent) << "// " << SM->getNumChildren()
185             << " children in Scope";
186       }
187       
188       OS << '\n' << TmpBuf.str();
189       CurrentIdx += ChildSize;
190     }
191     
192     // Emit a zero as a sentinel indicating end of 'Scope'.
193     if (!OmitComments)
194       OS << "/*" << CurrentIdx << "*/";
195     OS.PadToColumn(Indent*2) << "0, ";
196     if (!OmitComments)
197       OS << "/*End of Scope*/";
198     OS << '\n';
199     return CurrentIdx - StartIdx + 1;
200   }
201       
202   case Matcher::RecordNode:
203     OS << "OPC_RecordNode,";
204     if (!OmitComments)
205       OS.PadToColumn(CommentIndent) << "// #"
206         << cast<RecordMatcher>(N)->getResultNo() << " = "
207         << cast<RecordMatcher>(N)->getWhatFor();
208     OS << '\n';
209     return 1;
210
211   case Matcher::RecordChild:
212     OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo()
213        << ',';
214     if (!OmitComments)
215       OS.PadToColumn(CommentIndent) << "// #"
216         << cast<RecordChildMatcher>(N)->getResultNo() << " = "
217         << cast<RecordChildMatcher>(N)->getWhatFor();
218     OS << '\n';
219     return 1;
220       
221   case Matcher::RecordMemRef:
222     OS << "OPC_RecordMemRef,\n";
223     return 1;
224       
225   case Matcher::CaptureFlagInput:
226     OS << "OPC_CaptureFlagInput,\n";
227     return 1;
228       
229   case Matcher::MoveChild:
230     OS << "OPC_MoveChild, " << cast<MoveChildMatcher>(N)->getChildNo() << ",\n";
231     return 2;
232       
233   case Matcher::MoveParent:
234     OS << "OPC_MoveParent,\n";
235     return 1;
236       
237   case Matcher::CheckSame:
238     OS << "OPC_CheckSame, "
239        << cast<CheckSameMatcher>(N)->getMatchNumber() << ",\n";
240     return 2;
241
242   case Matcher::CheckPatternPredicate: {
243     StringRef Pred = cast<CheckPatternPredicateMatcher>(N)->getPredicate();
244     OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
245     if (!OmitComments)
246       OS.PadToColumn(CommentIndent) << "// " << Pred;
247     OS << '\n';
248     return 2;
249   }
250   case Matcher::CheckPredicate: {
251     StringRef Pred = cast<CheckPredicateMatcher>(N)->getPredicateName();
252     OS << "OPC_CheckPredicate, " << getNodePredicate(Pred) << ',';
253     if (!OmitComments)
254       OS.PadToColumn(CommentIndent) << "// " << Pred;
255     OS << '\n';
256     return 2;
257   }
258
259   case Matcher::CheckOpcode:
260     OS << "OPC_CheckOpcode, "
261        << cast<CheckOpcodeMatcher>(N)->getOpcode().getEnumName() << ",\n";
262     return 2;
263       
264   case Matcher::SwitchOpcode:
265   case Matcher::SwitchType: {
266     unsigned StartIdx = CurrentIdx;
267     
268     unsigned NumCases;
269     if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
270       OS << "OPC_SwitchOpcode ";
271       NumCases = SOM->getNumCases();
272     } else {
273       OS << "OPC_SwitchType ";
274       NumCases = cast<SwitchTypeMatcher>(N)->getNumCases();
275     }
276
277     if (!OmitComments)
278       OS << "/*" << NumCases << " cases */";
279     OS << ", ";
280     ++CurrentIdx;
281     
282     // For each case we emit the size, then the opcode, then the matcher.
283     for (unsigned i = 0, e = NumCases; i != e; ++i) {
284       const Matcher *Child;
285       if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
286         Child = SOM->getCaseMatcher(i);
287       else
288         Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i);
289       
290       // We need to encode the opcode and the offset of the case code before
291       // emitting the case code.  Handle this by buffering the output into a
292       // string while we get the size.  Unfortunately, the offset of the
293       // children depends on the VBR size of the child, so for large children we
294       // have to iterate a bit.
295       SmallString<128> TmpBuf;
296       unsigned ChildSize = 0;
297       unsigned VBRSize = 0;
298       do {
299         VBRSize = GetVBRSize(ChildSize);
300         
301         TmpBuf.clear();
302         raw_svector_ostream OS(TmpBuf);
303         formatted_raw_ostream FOS(OS);
304         ChildSize = EmitMatcherList(Child, Indent+1, CurrentIdx+VBRSize+1, FOS);
305       } while (GetVBRSize(ChildSize) != VBRSize);
306       
307       assert(ChildSize != 0 && "Should not have a zero-sized child!");
308       
309       if (i != 0) {
310         OS.PadToColumn(Indent*2);
311         if (!OmitComments)
312         OS << (isa<SwitchOpcodeMatcher>(N) ?
313                    "/*SwitchOpcode*/ " : "/*SwitchType*/ ");
314       }
315       
316       // Emit the VBR.
317       CurrentIdx += EmitVBRValue(ChildSize, OS);
318       
319       OS << ' ';
320       if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
321         OS << SOM->getCaseOpcode(i).getEnumName();
322       else
323         OS << getEnumName(cast<SwitchTypeMatcher>(N)->getCaseType(i));
324       OS << ',';
325       
326       if (!OmitComments)
327         OS << "// ->" << CurrentIdx+ChildSize+1;
328       OS << '\n';
329       ++CurrentIdx;
330       OS << TmpBuf.str();
331       CurrentIdx += ChildSize;
332     }
333
334     // Emit the final zero to terminate the switch.
335     OS.PadToColumn(Indent*2) << "0, ";
336     if (!OmitComments)
337       OS << (isa<SwitchOpcodeMatcher>(N) ?
338              "// EndSwitchOpcode" : "// EndSwitchType");
339
340     OS << '\n';
341     ++CurrentIdx;
342     return CurrentIdx-StartIdx;
343   }
344
345  case Matcher::CheckType:
346     OS << "OPC_CheckType, "
347        << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
348     return 2;
349       
350   case Matcher::CheckChildType:
351     OS << "OPC_CheckChild"
352        << cast<CheckChildTypeMatcher>(N)->getChildNo() << "Type, "
353        << getEnumName(cast<CheckChildTypeMatcher>(N)->getType()) << ",\n";
354     return 2;
355       
356   case Matcher::CheckInteger: {
357     OS << "OPC_CheckInteger, ";
358     unsigned Bytes=1+EmitVBRValue(cast<CheckIntegerMatcher>(N)->getValue(), OS);
359     OS << '\n';
360     return Bytes;
361   }
362   case Matcher::CheckCondCode:
363     OS << "OPC_CheckCondCode, ISD::"
364        << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
365     return 2;
366       
367   case Matcher::CheckValueType:
368     OS << "OPC_CheckValueType, MVT::"
369        << cast<CheckValueTypeMatcher>(N)->getTypeName() << ",\n";
370     return 2;
371
372   case Matcher::CheckComplexPat: {
373     const CheckComplexPatMatcher *CCPM = cast<CheckComplexPatMatcher>(N);
374     const ComplexPattern &Pattern = CCPM->getPattern();
375     OS << "OPC_CheckComplexPat, /*CP*/" << getComplexPat(Pattern) << ", /*#*/"
376        << CCPM->getMatchNumber() << ',';
377     
378     if (!OmitComments) {
379       OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
380       OS << ":$" << CCPM->getName();
381       for (unsigned i = 0, e = Pattern.getNumOperands(); i != e; ++i)
382         OS << " #" << CCPM->getFirstResult()+i;
383            
384       if (Pattern.hasProperty(SDNPHasChain))
385         OS << " + chain result";
386     }
387     OS << '\n';
388     return 3;
389   }
390       
391   case Matcher::CheckAndImm: {
392     OS << "OPC_CheckAndImm, ";
393     unsigned Bytes=1+EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS);
394     OS << '\n';
395     return Bytes;
396   }
397
398   case Matcher::CheckOrImm: {
399     OS << "OPC_CheckOrImm, ";
400     unsigned Bytes = 1+EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS);
401     OS << '\n';
402     return Bytes;
403   }
404       
405   case Matcher::CheckFoldableChainNode:
406     OS << "OPC_CheckFoldableChainNode,\n";
407     return 1;
408       
409   case Matcher::EmitInteger: {
410     int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
411     OS << "OPC_EmitInteger, "
412        << getEnumName(cast<EmitIntegerMatcher>(N)->getVT()) << ", ";
413     unsigned Bytes = 2+EmitVBRValue(Val, OS);
414     OS << '\n';
415     return Bytes;
416   }
417   case Matcher::EmitStringInteger: {
418     const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
419     // These should always fit into one byte.
420     OS << "OPC_EmitInteger, "
421       << getEnumName(cast<EmitStringIntegerMatcher>(N)->getVT()) << ", "
422       << Val << ",\n";
423     return 3;
424   }
425       
426   case Matcher::EmitRegister:
427     OS << "OPC_EmitRegister, "
428        << getEnumName(cast<EmitRegisterMatcher>(N)->getVT()) << ", ";
429     if (Record *R = cast<EmitRegisterMatcher>(N)->getReg())
430       OS << getQualifiedName(R) << ",\n";
431     else {
432       OS << "0 ";
433       if (!OmitComments)
434         OS << "/*zero_reg*/";
435       OS << ",\n";
436     }
437     return 3;
438       
439   case Matcher::EmitConvertToTarget:
440     OS << "OPC_EmitConvertToTarget, "
441        << cast<EmitConvertToTargetMatcher>(N)->getSlot() << ",\n";
442     return 2;
443       
444   case Matcher::EmitMergeInputChains: {
445     const EmitMergeInputChainsMatcher *MN =
446       cast<EmitMergeInputChainsMatcher>(N);
447     OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
448     for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
449       OS << MN->getNode(i) << ", ";
450     OS << '\n';
451     return 2+MN->getNumNodes();
452   }
453   case Matcher::EmitCopyToReg:
454     OS << "OPC_EmitCopyToReg, "
455        << cast<EmitCopyToRegMatcher>(N)->getSrcSlot() << ", "
456        << getQualifiedName(cast<EmitCopyToRegMatcher>(N)->getDestPhysReg())
457        << ",\n";
458     return 3;
459   case Matcher::EmitNodeXForm: {
460     const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
461     OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
462        << XF->getSlot() << ',';
463     if (!OmitComments)
464       OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName();
465     OS <<'\n';
466     return 3;
467   }
468       
469   case Matcher::EmitNode:
470   case Matcher::MorphNodeTo: {
471     const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
472     OS << (isa<EmitNodeMatcher>(EN) ? "OPC_EmitNode" : "OPC_MorphNodeTo");
473     OS << ", TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
474     
475     if (EN->hasChain())   OS << "|OPFL_Chain";
476     if (EN->hasInFlag())  OS << "|OPFL_FlagInput";
477     if (EN->hasOutFlag()) OS << "|OPFL_FlagOutput";
478     if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
479     if (EN->getNumFixedArityOperands() != -1)
480       OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
481     OS << ",\n";
482     
483     OS.PadToColumn(Indent*2+4) << EN->getNumVTs();
484     if (!OmitComments)
485       OS << "/*#VTs*/";
486     OS << ", ";
487     for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
488       OS << getEnumName(EN->getVT(i)) << ", ";
489
490     OS << EN->getNumOperands();
491     if (!OmitComments)
492       OS << "/*#Ops*/";
493     OS << ", ";
494     unsigned NumOperandBytes = 0;
495     for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
496       NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
497     
498     if (!OmitComments) {
499       // Print the result #'s for EmitNode.
500       if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) {
501         if (unsigned NumResults = EN->getNumVTs()) {
502           OS.PadToColumn(CommentIndent) << "// Results = ";
503           unsigned First = E->getFirstResultSlot();
504           for (unsigned i = 0; i != NumResults; ++i)
505             OS << "#" << First+i << " ";
506         }
507       }
508       OS << '\n';
509
510       if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
511         OS.PadToColumn(Indent*2) << "// Src: "
512           << *SNT->getPattern().getSrcPattern() << '\n';
513         OS.PadToColumn(Indent*2) << "// Dst: "
514           << *SNT->getPattern().getDstPattern() << '\n';
515       }
516     } else
517       OS << '\n';
518     
519     return 6+EN->getNumVTs()+NumOperandBytes;
520   }
521   case Matcher::MarkFlagResults: {
522     const MarkFlagResultsMatcher *CFR = cast<MarkFlagResultsMatcher>(N);
523     OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", ";
524     unsigned NumOperandBytes = 0;
525     for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i)
526       NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS);
527     OS << '\n';
528     return 2+NumOperandBytes;
529   }
530   case Matcher::CompleteMatch: {
531     const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
532     OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
533     unsigned NumResultBytes = 0;
534     for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
535       NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
536     OS << '\n';
537     if (!OmitComments) {
538       OS.PadToColumn(Indent*2) << "// Src: "
539         << *CM->getPattern().getSrcPattern() << '\n';
540       OS.PadToColumn(Indent*2) << "// Dst: "
541         << *CM->getPattern().getDstPattern();
542     }
543     OS << '\n';
544     return 2 + NumResultBytes;
545   }
546   }
547   assert(0 && "Unreachable");
548   return 0;
549 }
550
551 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
552 unsigned MatcherTableEmitter::
553 EmitMatcherList(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
554                 formatted_raw_ostream &OS) {
555   unsigned Size = 0;
556   while (N) {
557     if (unsigned(N->getKind()) >= Histogram.size())
558       Histogram.resize(N->getKind()+1);
559     Histogram[N->getKind()]++;
560     if (!OmitComments)
561       OS << "/*" << CurrentIdx << "*/";
562     unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
563     Size += MatcherSize;
564     CurrentIdx += MatcherSize;
565     
566     // If there are other nodes in this list, iterate to them, otherwise we're
567     // done.
568     N = N->getNext();
569   }
570   return Size;
571 }
572
573 void MatcherTableEmitter::EmitPredicateFunctions(const CodeGenDAGPatterns &CGP,
574                                                  formatted_raw_ostream &OS) {
575   // Emit pattern predicates.
576   if (!PatternPredicates.empty()) {
577     OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
578     OS << "  switch (PredNo) {\n";
579     OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
580     for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
581       OS << "  case " << i << ": return "  << PatternPredicates[i] << ";\n";
582     OS << "  }\n";
583     OS << "}\n\n";
584   }
585    
586   // Emit Node predicates.
587   // FIXME: Annoyingly, these are stored by name, which we never even emit. Yay?
588   StringMap<TreePattern*> PFsByName;
589   
590   for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
591        I != E; ++I)
592     PFsByName[I->first->getName()] = I->second;
593   
594   if (!NodePredicates.empty()) {
595     OS << "bool CheckNodePredicate(SDNode *Node, unsigned PredNo) const {\n";
596     OS << "  switch (PredNo) {\n";
597     OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
598     for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i) {
599       // FIXME: Storing this by name is horrible.
600       TreePattern *P =PFsByName[NodePredicates[i].substr(strlen("Predicate_"))];
601       assert(P && "Unknown name?");
602       
603       // Emit the predicate code corresponding to this pattern.
604       std::string Code = P->getRecord()->getValueAsCode("Predicate");
605       assert(!Code.empty() && "No code in this predicate");
606       OS << "  case " << i << ": { // " << NodePredicates[i] << '\n';
607       std::string ClassName;
608       if (P->getOnlyTree()->isLeaf())
609         ClassName = "SDNode";
610       else
611         ClassName =
612           CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
613       if (ClassName == "SDNode")
614         OS << "    SDNode *N = Node;\n";
615       else
616         OS << "    " << ClassName << "*N = cast<" << ClassName << ">(Node);\n";
617       OS << Code << "\n  }\n";
618     }
619     OS << "  }\n";
620     OS << "}\n\n";
621   }
622   
623   // Emit CompletePattern matchers.
624   // FIXME: This should be const.
625   if (!ComplexPatterns.empty()) {
626     OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
627     OS << "      unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
628     OS << "  switch (PatternNo) {\n";
629     OS << "  default: assert(0 && \"Invalid pattern # in table?\");\n";
630     for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
631       const ComplexPattern &P = *ComplexPatterns[i];
632       unsigned NumOps = P.getNumOperands();
633
634       if (P.hasProperty(SDNPHasChain))
635         ++NumOps;  // Get the chained node too.
636       
637       OS << "  case " << i << ":\n";
638       OS << "    Result.resize(Result.size()+" << NumOps << ");\n";
639       OS << "    return "  << P.getSelectFunc();
640
641       OS << "(Root, N";
642       for (unsigned i = 0; i != NumOps; ++i)
643         OS << ", Result[Result.size()-" << (NumOps-i) << ']';
644       OS << ");\n";
645     }
646     OS << "  }\n";
647     OS << "}\n\n";
648   }
649   
650   
651   // Emit SDNodeXForm handlers.
652   // FIXME: This should be const.
653   if (!NodeXForms.empty()) {
654     OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
655     OS << "  switch (XFormNo) {\n";
656     OS << "  default: assert(0 && \"Invalid xform # in table?\");\n";
657     
658     // FIXME: The node xform could take SDValue's instead of SDNode*'s.
659     for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i) {
660       const CodeGenDAGPatterns::NodeXForm &Entry =
661         CGP.getSDNodeTransform(NodeXForms[i]);
662       
663       Record *SDNode = Entry.first;
664       const std::string &Code = Entry.second;
665       
666       OS << "  case " << i << ": {  ";
667       if (!OmitComments)
668         OS << "// " << NodeXForms[i]->getName();
669       OS << '\n';
670       
671       std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
672       if (ClassName == "SDNode")
673         OS << "    SDNode *N = V.getNode();\n";
674       else
675         OS << "    " << ClassName << " *N = cast<" << ClassName
676            << ">(V.getNode());\n";
677       OS << Code << "\n  }\n";
678     }
679     OS << "  }\n";
680     OS << "}\n\n";
681   }
682 }
683
684 void MatcherTableEmitter::EmitHistogram(formatted_raw_ostream &OS) {
685   if (OmitComments)
686     return;
687   OS << "  // Opcode Histogram:\n";
688   for (unsigned i = 0, e = Histogram.size(); i != e; ++i) {
689     OS << "  // #";
690     switch ((Matcher::KindTy)i) {
691     case Matcher::Scope: OS << "OPC_Scope"; break; 
692     case Matcher::RecordNode: OS << "OPC_RecordNode"; break; 
693     case Matcher::RecordChild: OS << "OPC_RecordChild"; break;
694     case Matcher::RecordMemRef: OS << "OPC_RecordMemRef"; break;
695     case Matcher::CaptureFlagInput: OS << "OPC_CaptureFlagInput"; break;
696     case Matcher::MoveChild: OS << "OPC_MoveChild"; break;
697     case Matcher::MoveParent: OS << "OPC_MoveParent"; break;
698     case Matcher::CheckSame: OS << "OPC_CheckSame"; break;
699     case Matcher::CheckPatternPredicate:
700       OS << "OPC_CheckPatternPredicate"; break;
701     case Matcher::CheckPredicate: OS << "OPC_CheckPredicate"; break;
702     case Matcher::CheckOpcode: OS << "OPC_CheckOpcode"; break;
703     case Matcher::SwitchOpcode: OS << "OPC_SwitchOpcode"; break;
704     case Matcher::CheckType: OS << "OPC_CheckType"; break;
705     case Matcher::SwitchType: OS << "OPC_SwitchType"; break;
706     case Matcher::CheckChildType: OS << "OPC_CheckChildType"; break;
707     case Matcher::CheckInteger: OS << "OPC_CheckInteger"; break;
708     case Matcher::CheckCondCode: OS << "OPC_CheckCondCode"; break;
709     case Matcher::CheckValueType: OS << "OPC_CheckValueType"; break;
710     case Matcher::CheckComplexPat: OS << "OPC_CheckComplexPat"; break;
711     case Matcher::CheckAndImm: OS << "OPC_CheckAndImm"; break;
712     case Matcher::CheckOrImm: OS << "OPC_CheckOrImm"; break;
713     case Matcher::CheckFoldableChainNode:
714       OS << "OPC_CheckFoldableChainNode"; break;
715     case Matcher::EmitInteger: OS << "OPC_EmitInteger"; break;
716     case Matcher::EmitStringInteger: OS << "OPC_EmitStringInteger"; break;
717     case Matcher::EmitRegister: OS << "OPC_EmitRegister"; break;
718     case Matcher::EmitConvertToTarget: OS << "OPC_EmitConvertToTarget"; break;
719     case Matcher::EmitMergeInputChains: OS << "OPC_EmitMergeInputChains"; break;
720     case Matcher::EmitCopyToReg: OS << "OPC_EmitCopyToReg"; break;
721     case Matcher::EmitNode: OS << "OPC_EmitNode"; break;
722     case Matcher::MorphNodeTo: OS << "OPC_MorphNodeTo"; break;
723     case Matcher::EmitNodeXForm: OS << "OPC_EmitNodeXForm"; break;
724     case Matcher::MarkFlagResults: OS << "OPC_MarkFlagResults"; break;
725     case Matcher::CompleteMatch: OS << "OPC_CompleteMatch"; break;    
726     }
727     
728     OS.PadToColumn(40) << " = " << Histogram[i] << '\n';
729   }
730   OS << '\n';
731 }
732
733
734 void llvm::EmitMatcherTable(const Matcher *TheMatcher,
735                             const CodeGenDAGPatterns &CGP, raw_ostream &O) {
736   formatted_raw_ostream OS(O);
737   
738   OS << "// The main instruction selector code.\n";
739   OS << "SDNode *SelectCode(SDNode *N) {\n";
740
741   MatcherTableEmitter MatcherEmitter;
742
743   OS << "  // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
744   OS << "  #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
745   OS << "  static const unsigned char MatcherTable[] = {\n";
746   unsigned TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 5, 0, OS);
747   OS << "    0\n  }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
748   
749   MatcherEmitter.EmitHistogram(OS);
750   
751   OS << "  #undef TARGET_OPCODE\n";
752   OS << "  return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
753   OS << '\n';
754   
755   // Next up, emit the function for node and pattern predicates:
756   MatcherEmitter.EmitPredicateFunctions(CGP, OS);
757 }