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