Missed a \n in previous commit.
[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     unsigned StartIdx = CurrentIdx;
266     const SwitchOpcodeMatcher *SOM = cast<SwitchOpcodeMatcher>(N);
267     OS << "OPC_SwitchOpcode ";
268     if (!OmitComments)
269       OS << "/*" << SOM->getNumCases() << " cases */";
270     OS << ", ";
271     ++CurrentIdx;
272     
273     // For each case we emit the size, then the opcode, then the matcher.
274     for (unsigned i = 0, e = SOM->getNumCases(); i != e; ++i) {
275       // We need to encode the opcode and the offset of the case code before
276       // emitting the case code.  Handle this by buffering the output into a
277       // string while we get the size.  Unfortunately, the offset of the
278       // children depends on the VBR size of the child, so for large children we
279       // have to iterate a bit.
280       SmallString<128> TmpBuf;
281       unsigned ChildSize = 0;
282       unsigned VBRSize = 0;
283       do {
284         VBRSize = GetVBRSize(ChildSize);
285         
286         TmpBuf.clear();
287         raw_svector_ostream OS(TmpBuf);
288         formatted_raw_ostream FOS(OS);
289         ChildSize = EmitMatcherList(SOM->getCaseMatcher(i),
290                                     Indent+1, CurrentIdx+VBRSize+1, FOS);
291       } while (GetVBRSize(ChildSize) != VBRSize);
292       
293       assert(ChildSize != 0 && "Should not have a zero-sized child!");
294       
295       if (i != 0) {
296         OS.PadToColumn(Indent*2);
297         if (!OmitComments)
298          OS << "/*SwitchOpcode*/ ";
299       }
300       
301       // Emit the VBR.
302       CurrentIdx += EmitVBRValue(ChildSize, OS);
303       
304       OS << " " << SOM->getCaseOpcode(i).getEnumName() << ",";
305       if (!OmitComments)
306         OS << "// ->" << CurrentIdx+ChildSize+1;
307       OS << '\n';
308       ++CurrentIdx;
309       OS << TmpBuf.str();
310       CurrentIdx += ChildSize;
311     }
312
313     // Emit the final zero to terminate the switch.
314     OS.PadToColumn(Indent*2) << "0, ";
315     if (!OmitComments)
316       OS << "// EndSwitchOpcode";
317     OS << '\n';
318     ++CurrentIdx;
319     return CurrentIdx-StartIdx;
320   }
321
322  case Matcher::CheckType:
323     OS << "OPC_CheckType, "
324        << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
325     return 2;
326   case Matcher::CheckChildType:
327     OS << "OPC_CheckChild"
328        << cast<CheckChildTypeMatcher>(N)->getChildNo() << "Type, "
329        << getEnumName(cast<CheckChildTypeMatcher>(N)->getType()) << ",\n";
330     return 2;
331       
332   case Matcher::CheckInteger:
333     OS << "OPC_CheckInteger, ";
334     return 1+EmitVBRValue(cast<CheckIntegerMatcher>(N)->getValue(), OS);
335   case Matcher::CheckCondCode:
336     OS << "OPC_CheckCondCode, ISD::"
337        << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
338     return 2;
339       
340   case Matcher::CheckValueType:
341     OS << "OPC_CheckValueType, MVT::"
342        << cast<CheckValueTypeMatcher>(N)->getTypeName() << ",\n";
343     return 2;
344
345   case Matcher::CheckComplexPat: {
346     const ComplexPattern &Pattern =
347       cast<CheckComplexPatMatcher>(N)->getPattern();
348     OS << "OPC_CheckComplexPat, " << getComplexPat(Pattern) << ',';
349     if (!OmitComments) {
350       OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
351       OS << ": " << Pattern.getNumOperands() << " operands";
352       if (Pattern.hasProperty(SDNPHasChain))
353         OS << " + chain result and input";
354     }
355     OS << '\n';
356     return 2;
357   }
358       
359   case Matcher::CheckAndImm:
360     OS << "OPC_CheckAndImm, ";
361     return 1+EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS);
362
363   case Matcher::CheckOrImm:
364     OS << "OPC_CheckOrImm, ";
365     return 1+EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS);
366       
367   case Matcher::CheckFoldableChainNode:
368     OS << "OPC_CheckFoldableChainNode,\n";
369     return 1;
370   case Matcher::CheckChainCompatible:
371     OS << "OPC_CheckChainCompatible, "
372        << cast<CheckChainCompatibleMatcher>(N)->getPreviousOp() << ",\n";
373     return 2;
374       
375   case Matcher::EmitInteger: {
376     int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
377     OS << "OPC_EmitInteger, "
378        << getEnumName(cast<EmitIntegerMatcher>(N)->getVT()) << ", ";
379     return 2+EmitVBRValue(Val, OS);
380   }
381   case Matcher::EmitStringInteger: {
382     const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
383     // These should always fit into one byte.
384     OS << "OPC_EmitInteger, "
385       << getEnumName(cast<EmitStringIntegerMatcher>(N)->getVT()) << ", "
386       << Val << ",\n";
387     return 3;
388   }
389       
390   case Matcher::EmitRegister:
391     OS << "OPC_EmitRegister, "
392        << getEnumName(cast<EmitRegisterMatcher>(N)->getVT()) << ", ";
393     if (Record *R = cast<EmitRegisterMatcher>(N)->getReg())
394       OS << getQualifiedName(R) << ",\n";
395     else {
396       OS << "0 ";
397       if (!OmitComments)
398         OS << "/*zero_reg*/";
399       OS << ",\n";
400     }
401     return 3;
402       
403   case Matcher::EmitConvertToTarget:
404     OS << "OPC_EmitConvertToTarget, "
405        << cast<EmitConvertToTargetMatcher>(N)->getSlot() << ",\n";
406     return 2;
407       
408   case Matcher::EmitMergeInputChains: {
409     const EmitMergeInputChainsMatcher *MN =
410       cast<EmitMergeInputChainsMatcher>(N);
411     OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
412     for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
413       OS << MN->getNode(i) << ", ";
414     OS << '\n';
415     return 2+MN->getNumNodes();
416   }
417   case Matcher::EmitCopyToReg:
418     OS << "OPC_EmitCopyToReg, "
419        << cast<EmitCopyToRegMatcher>(N)->getSrcSlot() << ", "
420        << getQualifiedName(cast<EmitCopyToRegMatcher>(N)->getDestPhysReg())
421        << ",\n";
422     return 3;
423   case Matcher::EmitNodeXForm: {
424     const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
425     OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
426        << XF->getSlot() << ',';
427     if (!OmitComments)
428       OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName();
429     OS <<'\n';
430     return 3;
431   }
432       
433   case Matcher::EmitNode:
434   case Matcher::MorphNodeTo: {
435     const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
436     OS << (isa<EmitNodeMatcher>(EN) ? "OPC_EmitNode" : "OPC_MorphNodeTo");
437     OS << ", TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
438     
439     if (EN->hasChain())   OS << "|OPFL_Chain";
440     if (EN->hasInFlag())  OS << "|OPFL_FlagInput";
441     if (EN->hasOutFlag()) OS << "|OPFL_FlagOutput";
442     if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
443     if (EN->getNumFixedArityOperands() != -1)
444       OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
445     OS << ",\n";
446     
447     OS.PadToColumn(Indent*2+4) << EN->getNumVTs();
448     if (!OmitComments)
449       OS << "/*#VTs*/";
450     OS << ", ";
451     for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
452       OS << getEnumName(EN->getVT(i)) << ", ";
453
454     OS << EN->getNumOperands();
455     if (!OmitComments)
456       OS << "/*#Ops*/";
457     OS << ", ";
458     unsigned NumOperandBytes = 0;
459     for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i) {
460       // We emit the operand numbers in VBR encoded format, in case the number
461       // is too large to represent with a byte.
462       NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
463     }
464     
465     if (!OmitComments) {
466       // Print the result #'s for EmitNode.
467       if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) {
468         if (unsigned NumResults = EN->getNumVTs()) {
469           OS.PadToColumn(CommentIndent) << "// Results = ";
470           unsigned First = E->getFirstResultSlot();
471           for (unsigned i = 0; i != NumResults; ++i)
472             OS << "#" << First+i << " ";
473         }
474       }
475       OS << '\n';
476
477       if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
478         OS.PadToColumn(Indent*2) << "// Src: "
479           << *SNT->getPattern().getSrcPattern() << '\n';
480         OS.PadToColumn(Indent*2) << "// Dst: "
481           << *SNT->getPattern().getDstPattern() << '\n';
482       }
483     } else
484       OS << '\n';
485     
486     return 6+EN->getNumVTs()+NumOperandBytes;
487   }
488   case Matcher::MarkFlagResults: {
489     const MarkFlagResultsMatcher *CFR = cast<MarkFlagResultsMatcher>(N);
490     OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", ";
491     unsigned NumOperandBytes = 0;
492     for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i)
493       NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS);
494     OS << '\n';
495     return 2+NumOperandBytes;
496   }
497   case Matcher::CompleteMatch: {
498     const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
499     OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
500     unsigned NumResultBytes = 0;
501     for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
502       NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
503     OS << '\n';
504     if (!OmitComments) {
505       OS.PadToColumn(Indent*2) << "// Src: "
506         << *CM->getPattern().getSrcPattern() << '\n';
507       OS.PadToColumn(Indent*2) << "// Dst: "
508         << *CM->getPattern().getDstPattern();
509     }
510     OS << '\n';
511     return 2 + NumResultBytes;
512   }
513   }
514   assert(0 && "Unreachable");
515   return 0;
516 }
517
518 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
519 unsigned MatcherTableEmitter::
520 EmitMatcherList(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
521                 formatted_raw_ostream &OS) {
522   unsigned Size = 0;
523   while (N) {
524     if (unsigned(N->getKind()) >= Histogram.size())
525       Histogram.resize(N->getKind()+1);
526     Histogram[N->getKind()]++;
527     if (!OmitComments)
528       OS << "/*" << CurrentIdx << "*/";
529     unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
530     Size += MatcherSize;
531     CurrentIdx += MatcherSize;
532     
533     // If there are other nodes in this list, iterate to them, otherwise we're
534     // done.
535     N = N->getNext();
536   }
537   return Size;
538 }
539
540 void MatcherTableEmitter::EmitPredicateFunctions(const CodeGenDAGPatterns &CGP,
541                                                  formatted_raw_ostream &OS) {
542   // FIXME: Don't build off the DAGISelEmitter's predicates, emit them directly
543   // here into the case stmts.
544   
545   // Emit pattern predicates.
546   if (!PatternPredicates.empty()) {
547     OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
548     OS << "  switch (PredNo) {\n";
549     OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
550     for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
551       OS << "  case " << i << ": return "  << PatternPredicates[i] << ";\n";
552     OS << "  }\n";
553     OS << "}\n\n";
554   }
555    
556   // Emit Node predicates.
557   // FIXME: Annoyingly, these are stored by name, which we never even emit. Yay?
558   StringMap<TreePattern*> PFsByName;
559   
560   for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
561        I != E; ++I)
562     PFsByName[I->first->getName()] = I->second;
563   
564   if (!NodePredicates.empty()) {
565     OS << "bool CheckNodePredicate(SDNode *Node, unsigned PredNo) const {\n";
566     OS << "  switch (PredNo) {\n";
567     OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
568     for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i) {
569       // FIXME: Storing this by name is horrible.
570       TreePattern *P =PFsByName[NodePredicates[i].substr(strlen("Predicate_"))];
571       assert(P && "Unknown name?");
572       
573       // Emit the predicate code corresponding to this pattern.
574       std::string Code = P->getRecord()->getValueAsCode("Predicate");
575       assert(!Code.empty() && "No code in this predicate");
576       OS << "  case " << i << ": { // " << NodePredicates[i] << '\n';
577       std::string ClassName;
578       if (P->getOnlyTree()->isLeaf())
579         ClassName = "SDNode";
580       else
581         ClassName =
582           CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
583       if (ClassName == "SDNode")
584         OS << "    SDNode *N = Node;\n";
585       else
586         OS << "    " << ClassName << "*N = cast<" << ClassName << ">(Node);\n";
587       OS << Code << "\n  }\n";
588     }
589     OS << "  }\n";
590     OS << "}\n\n";
591   }
592   
593   // Emit CompletePattern matchers.
594   // FIXME: This should be const.
595   if (!ComplexPatterns.empty()) {
596     OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
597     OS << "      unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
598     OS << "  switch (PatternNo) {\n";
599     OS << "  default: assert(0 && \"Invalid pattern # in table?\");\n";
600     for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
601       const ComplexPattern &P = *ComplexPatterns[i];
602       unsigned NumOps = P.getNumOperands();
603
604       if (P.hasProperty(SDNPHasChain))
605         ++NumOps;  // Get the chained node too.
606       
607       OS << "  case " << i << ":\n";
608       OS << "    Result.resize(Result.size()+" << NumOps << ");\n";
609       OS << "    return "  << P.getSelectFunc();
610
611       // FIXME: Temporary hack until old isel dies.
612       if (P.hasProperty(SDNPHasChain))
613         OS << "XXX";
614       
615       OS << "(Root, N";
616       for (unsigned i = 0; i != NumOps; ++i)
617         OS << ", Result[Result.size()-" << (NumOps-i) << ']';
618       OS << ");\n";
619     }
620     OS << "  }\n";
621     OS << "}\n\n";
622   }
623   
624   
625   // Emit SDNodeXForm handlers.
626   // FIXME: This should be const.
627   if (!NodeXForms.empty()) {
628     OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
629     OS << "  switch (XFormNo) {\n";
630     OS << "  default: assert(0 && \"Invalid xform # in table?\");\n";
631     
632     // FIXME: The node xform could take SDValue's instead of SDNode*'s.
633     for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i) {
634       const CodeGenDAGPatterns::NodeXForm &Entry =
635         CGP.getSDNodeTransform(NodeXForms[i]);
636       
637       Record *SDNode = Entry.first;
638       const std::string &Code = Entry.second;
639       
640       OS << "  case " << i << ": {  ";
641       if (!OmitComments)
642         OS << "// " << NodeXForms[i]->getName();
643       OS << '\n';
644       
645       std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
646       if (ClassName == "SDNode")
647         OS << "    SDNode *N = V.getNode();\n";
648       else
649         OS << "    " << ClassName << " *N = cast<" << ClassName
650            << ">(V.getNode());\n";
651       OS << Code << "\n  }\n";
652     }
653     OS << "  }\n";
654     OS << "}\n\n";
655   }
656 }
657
658 void MatcherTableEmitter::EmitHistogram(formatted_raw_ostream &OS) {
659   if (OmitComments)
660     return;
661   OS << "  // Opcode Histogram:\n";
662   for (unsigned i = 0, e = Histogram.size(); i != e; ++i) {
663     OS << "  // #";
664     switch ((Matcher::KindTy)i) {
665     case Matcher::Scope: OS << "OPC_Scope"; break; 
666     case Matcher::RecordNode: OS << "OPC_RecordNode"; break; 
667     case Matcher::RecordChild: OS << "OPC_RecordChild"; break;
668     case Matcher::RecordMemRef: OS << "OPC_RecordMemRef"; break;
669     case Matcher::CaptureFlagInput: OS << "OPC_CaptureFlagInput"; break;
670     case Matcher::MoveChild: OS << "OPC_MoveChild"; break;
671     case Matcher::MoveParent: OS << "OPC_MoveParent"; break;
672     case Matcher::CheckSame: OS << "OPC_CheckSame"; break;
673     case Matcher::CheckPatternPredicate:
674       OS << "OPC_CheckPatternPredicate"; break;
675     case Matcher::CheckPredicate: OS << "OPC_CheckPredicate"; break;
676     case Matcher::CheckOpcode: OS << "OPC_CheckOpcode"; break;
677     case Matcher::SwitchOpcode: OS << "OPC_SwitchOpcode"; break;
678     case Matcher::CheckType: OS << "OPC_CheckType"; break;
679     case Matcher::CheckChildType: OS << "OPC_CheckChildType"; break;
680     case Matcher::CheckInteger: OS << "OPC_CheckInteger"; break;
681     case Matcher::CheckCondCode: OS << "OPC_CheckCondCode"; break;
682     case Matcher::CheckValueType: OS << "OPC_CheckValueType"; break;
683     case Matcher::CheckComplexPat: OS << "OPC_CheckComplexPat"; break;
684     case Matcher::CheckAndImm: OS << "OPC_CheckAndImm"; break;
685     case Matcher::CheckOrImm: OS << "OPC_CheckOrImm"; break;
686     case Matcher::CheckFoldableChainNode:
687       OS << "OPC_CheckFoldableChainNode"; break;
688     case Matcher::CheckChainCompatible: OS << "OPC_CheckChainCompatible"; break;
689     case Matcher::EmitInteger: OS << "OPC_EmitInteger"; break;
690     case Matcher::EmitStringInteger: OS << "OPC_EmitStringInteger"; break;
691     case Matcher::EmitRegister: OS << "OPC_EmitRegister"; break;
692     case Matcher::EmitConvertToTarget: OS << "OPC_EmitConvertToTarget"; break;
693     case Matcher::EmitMergeInputChains: OS << "OPC_EmitMergeInputChains"; break;
694     case Matcher::EmitCopyToReg: OS << "OPC_EmitCopyToReg"; break;
695     case Matcher::EmitNode: OS << "OPC_EmitNode"; break;
696     case Matcher::MorphNodeTo: OS << "OPC_MorphNodeTo"; break;
697     case Matcher::EmitNodeXForm: OS << "OPC_EmitNodeXForm"; break;
698     case Matcher::MarkFlagResults: OS << "OPC_MarkFlagResults"; break;
699     case Matcher::CompleteMatch: OS << "OPC_CompleteMatch"; break;    
700     }
701     
702     OS.PadToColumn(40) << " = " << Histogram[i] << '\n';
703   }
704   OS << '\n';
705 }
706
707
708 void llvm::EmitMatcherTable(const Matcher *TheMatcher,
709                             const CodeGenDAGPatterns &CGP, raw_ostream &O) {
710   formatted_raw_ostream OS(O);
711   
712   OS << "// The main instruction selector code.\n";
713   OS << "SDNode *SelectCode(SDNode *N) {\n";
714
715   MatcherTableEmitter MatcherEmitter;
716
717   OS << "  // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
718   OS << "  #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
719   OS << "  static const unsigned char MatcherTable[] = {\n";
720   unsigned TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 5, 0, OS);
721   OS << "    0\n  }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
722   
723   MatcherEmitter.EmitHistogram(OS);
724   
725   OS << "  #undef TARGET_OPCODE\n";
726   OS << "  return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
727   OS << '\n';
728   
729   // Next up, emit the function for node and pattern predicates:
730   MatcherEmitter.EmitPredicateFunctions(CGP, OS);
731 }