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