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