xref: /freebsd-src/contrib/llvm-project/llvm/utils/TableGen/DAGISelMatcherEmitter.cpp (revision 46c59ea9b61755455ff6bf9f3e7b834e1af634ea)
1 //===- DAGISelMatcherEmitter.cpp - Matcher Emitter ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains code to generate C++ code for a matcher.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenDAGPatterns.h"
14 #include "CodeGenInstruction.h"
15 #include "CodeGenRegisters.h"
16 #include "CodeGenTarget.h"
17 #include "DAGISelMatcher.h"
18 #include "SDNodeProperties.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/TinyPtrVector.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/TableGen/Error.h"
27 #include "llvm/TableGen/Record.h"
28 
29 using namespace llvm;
30 
31 enum {
32   IndexWidth = 6,
33   FullIndexWidth = IndexWidth + 4,
34   HistOpcWidth = 40,
35 };
36 
37 cl::OptionCategory DAGISelCat("Options for -gen-dag-isel");
38 
39 // To reduce generated source code size.
40 static cl::opt<bool> OmitComments("omit-comments",
41                                   cl::desc("Do not generate comments"),
42                                   cl::init(false), cl::cat(DAGISelCat));
43 
44 static cl::opt<bool> InstrumentCoverage(
45     "instrument-coverage",
46     cl::desc("Generates tables to help identify patterns matched"),
47     cl::init(false), cl::cat(DAGISelCat));
48 
49 namespace {
50 class MatcherTableEmitter {
51   const CodeGenDAGPatterns &CGP;
52 
53   SmallVector<unsigned, Matcher::HighestKind+1> OpcodeCounts;
54 
55   DenseMap<TreePattern *, unsigned> NodePredicateMap;
56   std::vector<TreePredicateFn> NodePredicates;
57   std::vector<TreePredicateFn> NodePredicatesWithOperands;
58 
59   // We de-duplicate the predicates by code string, and use this map to track
60   // all the patterns with "identical" predicates.
61   StringMap<TinyPtrVector<TreePattern *>> NodePredicatesByCodeToRun;
62 
63   std::vector<std::string> PatternPredicates;
64 
65   std::vector<const ComplexPattern*> ComplexPatterns;
66 
67 
68   DenseMap<Record*, unsigned> NodeXFormMap;
69   std::vector<Record*> NodeXForms;
70 
71   std::vector<std::string> VecIncludeStrings;
72   MapVector<std::string, unsigned, StringMap<unsigned> > VecPatterns;
73 
74   unsigned getPatternIdxFromTable(std::string &&P, std::string &&include_loc) {
75     const auto It = VecPatterns.find(P);
76     if (It == VecPatterns.end()) {
77       VecPatterns.insert(make_pair(std::move(P), VecPatterns.size()));
78       VecIncludeStrings.push_back(std::move(include_loc));
79       return VecIncludeStrings.size() - 1;
80     }
81     return It->second;
82   }
83 
84 public:
85   MatcherTableEmitter(const Matcher *TheMatcher, const CodeGenDAGPatterns &cgp)
86       : CGP(cgp), OpcodeCounts(Matcher::HighestKind + 1, 0) {
87     // Record the usage of ComplexPattern.
88     DenseMap<const ComplexPattern *, unsigned> ComplexPatternUsage;
89     // Record the usage of PatternPredicate.
90     std::map<StringRef, unsigned> PatternPredicateUsage;
91 
92     // Iterate the whole MatcherTable once and do some statistics.
93     std::function<void(const Matcher *)> Statistic = [&](const Matcher *N) {
94       while (N) {
95         if (auto *SM = dyn_cast<ScopeMatcher>(N))
96           for (unsigned I = 0; I < SM->getNumChildren(); I++)
97             Statistic(SM->getChild(I));
98         else if (auto *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
99           for (unsigned I = 0; I < SOM->getNumCases(); I++)
100             Statistic(SOM->getCaseMatcher(I));
101         else if (auto *STM = dyn_cast<SwitchTypeMatcher>(N))
102           for (unsigned I = 0; I < STM->getNumCases(); I++)
103             Statistic(STM->getCaseMatcher(I));
104         else if (auto *CPM = dyn_cast<CheckComplexPatMatcher>(N))
105           ++ComplexPatternUsage[&CPM->getPattern()];
106         else if (auto *CPPM = dyn_cast<CheckPatternPredicateMatcher>(N))
107           ++PatternPredicateUsage[CPPM->getPredicate()];
108         N = N->getNext();
109       }
110     };
111     Statistic(TheMatcher);
112 
113     // Sort ComplexPatterns by usage.
114     std::vector<std::pair<const ComplexPattern *, unsigned>> ComplexPatternList(
115         ComplexPatternUsage.begin(), ComplexPatternUsage.end());
116     sort(ComplexPatternList,
117          [](const auto &A, const auto &B) { return A.second > B.second; });
118     for (const auto &ComplexPattern : ComplexPatternList)
119       ComplexPatterns.push_back(ComplexPattern.first);
120 
121     // Sort PatternPredicates by usage.
122     std::vector<std::pair<std::string, unsigned>> PatternPredicateList(
123         PatternPredicateUsage.begin(), PatternPredicateUsage.end());
124     sort(PatternPredicateList,
125          [](const auto &A, const auto &B) { return A.second > B.second; });
126     for (const auto &PatternPredicate : PatternPredicateList)
127       PatternPredicates.push_back(PatternPredicate.first);
128   }
129 
130   unsigned EmitMatcherList(const Matcher *N, const unsigned Indent,
131                            unsigned StartIdx, raw_ostream &OS);
132 
133   unsigned SizeMatcherList(Matcher *N, raw_ostream &OS);
134 
135   void EmitPredicateFunctions(raw_ostream &OS);
136 
137   void EmitHistogram(const Matcher *N, raw_ostream &OS);
138 
139   void EmitPatternMatchTable(raw_ostream &OS);
140 
141 private:
142   void EmitNodePredicatesFunction(const std::vector<TreePredicateFn> &Preds,
143                                   StringRef Decl, raw_ostream &OS);
144 
145   unsigned SizeMatcher(Matcher *N, raw_ostream &OS);
146 
147   unsigned EmitMatcher(const Matcher *N, const unsigned Indent, unsigned CurrentIdx,
148                        raw_ostream &OS);
149 
150   unsigned getNodePredicate(TreePredicateFn Pred) {
151     TreePattern *TP = Pred.getOrigPatFragRecord();
152     unsigned &Entry = NodePredicateMap[TP];
153     if (Entry == 0) {
154       TinyPtrVector<TreePattern *> &SameCodePreds =
155           NodePredicatesByCodeToRun[Pred.getCodeToRunOnSDNode()];
156       if (SameCodePreds.empty()) {
157         // We've never seen a predicate with the same code: allocate an entry.
158         if (Pred.usesOperands()) {
159           NodePredicatesWithOperands.push_back(Pred);
160           Entry = NodePredicatesWithOperands.size();
161         } else {
162           NodePredicates.push_back(Pred);
163           Entry = NodePredicates.size();
164         }
165       } else {
166         // We did see an identical predicate: re-use it.
167         Entry = NodePredicateMap[SameCodePreds.front()];
168         assert(Entry != 0);
169         assert(TreePredicateFn(SameCodePreds.front()).usesOperands() ==
170                Pred.usesOperands() &&
171                "PatFrags with some code must have same usesOperands setting");
172       }
173       // In both cases, we've never seen this particular predicate before, so
174       // mark it in the list of predicates sharing the same code.
175       SameCodePreds.push_back(TP);
176     }
177     return Entry-1;
178   }
179 
180   unsigned getPatternPredicate(StringRef PredName) {
181     return llvm::find(PatternPredicates, PredName) - PatternPredicates.begin();
182   }
183   unsigned getComplexPat(const ComplexPattern &P) {
184     return llvm::find(ComplexPatterns, &P) - ComplexPatterns.begin();
185   }
186 
187   unsigned getNodeXFormID(Record *Rec) {
188     unsigned &Entry = NodeXFormMap[Rec];
189     if (Entry == 0) {
190       NodeXForms.push_back(Rec);
191       Entry = NodeXForms.size();
192     }
193     return Entry-1;
194   }
195 
196 };
197 } // end anonymous namespace.
198 
199 static std::string GetPatFromTreePatternNode(const TreePatternNode *N) {
200   std::string str;
201   raw_string_ostream Stream(str);
202   Stream << *N;
203   return str;
204 }
205 
206 static unsigned GetVBRSize(unsigned Val) {
207   if (Val <= 127) return 1;
208 
209   unsigned NumBytes = 0;
210   while (Val >= 128) {
211     Val >>= 7;
212     ++NumBytes;
213   }
214   return NumBytes+1;
215 }
216 
217 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
218 /// bytes emitted.
219 static unsigned EmitVBRValue(uint64_t Val, raw_ostream &OS) {
220   if (Val <= 127) {
221     OS << Val << ", ";
222     return 1;
223   }
224 
225   uint64_t InVal = Val;
226   unsigned NumBytes = 0;
227   while (Val >= 128) {
228     OS << (Val&127) << "|128,";
229     Val >>= 7;
230     ++NumBytes;
231   }
232   OS << Val;
233   if (!OmitComments)
234     OS << "/*" << InVal << "*/";
235   OS << ", ";
236   return NumBytes+1;
237 }
238 
239 /// Emit the specified signed value as a VBR. To improve compression we encode
240 /// positive numbers shifted left by 1 and negative numbers negated and shifted
241 /// left by 1 with bit 0 set.
242 static unsigned EmitSignedVBRValue(uint64_t Val, raw_ostream &OS) {
243   if ((int64_t)Val >= 0)
244     Val = Val << 1;
245   else
246     Val = (-Val << 1) | 1;
247 
248   return EmitVBRValue(Val, OS);
249 }
250 
251 // This is expensive and slow.
252 static std::string getIncludePath(const Record *R) {
253   std::string str;
254   raw_string_ostream Stream(str);
255   auto Locs = R->getLoc();
256   SMLoc L;
257   if (Locs.size() > 1) {
258     // Get where the pattern prototype was instantiated
259     L = Locs[1];
260   } else if (Locs.size() == 1) {
261     L = Locs[0];
262   }
263   unsigned CurBuf = SrcMgr.FindBufferContainingLoc(L);
264   assert(CurBuf && "Invalid or unspecified location!");
265 
266   Stream << SrcMgr.getBufferInfo(CurBuf).Buffer->getBufferIdentifier() << ":"
267          << SrcMgr.FindLineNumber(L, CurBuf);
268   return str;
269 }
270 
271 /// This function traverses the matcher tree and sizes all the nodes
272 /// that are children of the three kinds of nodes that have them.
273 unsigned MatcherTableEmitter::
274 SizeMatcherList(Matcher *N, raw_ostream &OS) {
275   unsigned Size = 0;
276   while (N) {
277     Size += SizeMatcher(N, OS);
278     N = N->getNext();
279   }
280   return Size;
281 }
282 
283 /// This function sizes the children of the three kinds of nodes that
284 /// have them. It does so by using special cases for those three
285 /// nodes, but sharing the code in EmitMatcher() for the other kinds.
286 unsigned MatcherTableEmitter::
287 SizeMatcher(Matcher *N, raw_ostream &OS) {
288   unsigned Idx = 0;
289 
290   ++OpcodeCounts[N->getKind()];
291   switch (N->getKind()) {
292   // The Scope matcher has its kind, a series of child size + child,
293   // and a trailing zero.
294   case Matcher::Scope: {
295     ScopeMatcher *SM = cast<ScopeMatcher>(N);
296     assert(SM->getNext() == nullptr && "Scope matcher should not have next");
297     unsigned Size = 1; // Count the kind.
298     for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
299       const unsigned ChildSize = SizeMatcherList(SM->getChild(i), OS);
300       assert(ChildSize != 0 && "Matcher cannot have child of size 0");
301       SM->getChild(i)->setSize(ChildSize);
302       Size += GetVBRSize(ChildSize) + ChildSize; // Count VBR and child size.
303     }
304     ++Size; // Count the zero sentinel.
305     return Size;
306   }
307 
308   // SwitchOpcode and SwitchType have their kind, a series of child size +
309   // opcode/type + child, and a trailing zero.
310   case Matcher::SwitchOpcode:
311   case Matcher::SwitchType: {
312     unsigned Size = 1; // Count the kind.
313     unsigned NumCases;
314     if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
315       NumCases = SOM->getNumCases();
316     else
317       NumCases = cast<SwitchTypeMatcher>(N)->getNumCases();
318     for (unsigned i = 0, e = NumCases; i != e; ++i) {
319       Matcher *Child;
320       if (SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
321         Child = SOM->getCaseMatcher(i);
322         Size += 2; // Count the child's opcode.
323       } else {
324         Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i);
325         ++Size; // Count the child's type.
326       }
327       const unsigned ChildSize = SizeMatcherList(Child, OS);
328       assert(ChildSize != 0 && "Matcher cannot have child of size 0");
329       Child->setSize(ChildSize);
330       Size += GetVBRSize(ChildSize) + ChildSize; // Count VBR and child size.
331     }
332     ++Size; // Count the zero sentinel.
333     return Size;
334   }
335 
336   default:
337     // Employ the matcher emitter to size other matchers.
338     return EmitMatcher(N, 0, Idx, OS);
339   }
340   llvm_unreachable("Unreachable");
341 }
342 
343 static void BeginEmitFunction(raw_ostream &OS, StringRef RetType,
344                               StringRef Decl, bool AddOverride) {
345   OS << "#ifdef GET_DAGISEL_DECL\n";
346   OS << RetType << ' ' << Decl;
347   if (AddOverride)
348     OS << " override";
349   OS << ";\n"
350         "#endif\n"
351         "#if defined(GET_DAGISEL_BODY) || DAGISEL_INLINE\n";
352   OS << RetType << " DAGISEL_CLASS_COLONCOLON " << Decl << "\n";
353   if (AddOverride) {
354     OS << "#if DAGISEL_INLINE\n"
355           "  override\n"
356           "#endif\n";
357   }
358 }
359 
360 static void EndEmitFunction(raw_ostream &OS) {
361   OS << "#endif // GET_DAGISEL_BODY\n\n";
362 }
363 
364 void MatcherTableEmitter::EmitPatternMatchTable(raw_ostream &OS) {
365 
366   assert(isUInt<16>(VecPatterns.size()) &&
367          "Using only 16 bits to encode offset into Pattern Table");
368   assert(VecPatterns.size() == VecIncludeStrings.size() &&
369          "The sizes of Pattern and include vectors should be the same");
370 
371   BeginEmitFunction(OS, "StringRef", "getPatternForIndex(unsigned Index)",
372                     true/*AddOverride*/);
373   OS << "{\n";
374   OS << "static const char *PATTERN_MATCH_TABLE[] = {\n";
375 
376   for (const auto &It : VecPatterns) {
377     OS << "\"" << It.first << "\",\n";
378   }
379 
380   OS << "\n};";
381   OS << "\nreturn StringRef(PATTERN_MATCH_TABLE[Index]);";
382   OS << "\n}\n";
383   EndEmitFunction(OS);
384 
385   BeginEmitFunction(OS, "StringRef", "getIncludePathForIndex(unsigned Index)",
386                     true/*AddOverride*/);
387   OS << "{\n";
388   OS << "static const char *INCLUDE_PATH_TABLE[] = {\n";
389 
390   for (const auto &It : VecIncludeStrings) {
391     OS << "\"" << It << "\",\n";
392   }
393 
394   OS << "\n};";
395   OS << "\nreturn StringRef(INCLUDE_PATH_TABLE[Index]);";
396   OS << "\n}\n";
397   EndEmitFunction(OS);
398 }
399 
400 /// EmitMatcher - Emit bytes for the specified matcher and return
401 /// the number of bytes emitted.
402 unsigned MatcherTableEmitter::
403 EmitMatcher(const Matcher *N, const unsigned Indent, unsigned CurrentIdx,
404             raw_ostream &OS) {
405   OS.indent(Indent);
406 
407   switch (N->getKind()) {
408   case Matcher::Scope: {
409     const ScopeMatcher *SM = cast<ScopeMatcher>(N);
410     unsigned StartIdx = CurrentIdx;
411 
412     // Emit all of the children.
413     for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
414       if (i == 0) {
415         OS << "OPC_Scope, ";
416         ++CurrentIdx;
417       } else  {
418         if (!OmitComments) {
419           OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
420           OS.indent(Indent) << "/*Scope*/ ";
421         } else
422           OS.indent(Indent);
423       }
424 
425       unsigned ChildSize = SM->getChild(i)->getSize();
426       unsigned VBRSize = EmitVBRValue(ChildSize, OS);
427       if (!OmitComments) {
428         OS << "/*->" << CurrentIdx + VBRSize + ChildSize << "*/";
429         if (i == 0)
430           OS << " // " << SM->getNumChildren() << " children in Scope";
431       }
432       OS << '\n';
433 
434       ChildSize = EmitMatcherList(SM->getChild(i), Indent+1,
435                                   CurrentIdx + VBRSize, OS);
436       assert(ChildSize == SM->getChild(i)->getSize() &&
437              "Emitted child size does not match calculated size");
438       CurrentIdx += VBRSize + ChildSize;
439     }
440 
441     // Emit a zero as a sentinel indicating end of 'Scope'.
442     if (!OmitComments)
443       OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
444     OS.indent(Indent) << "0, ";
445     if (!OmitComments)
446       OS << "/*End of Scope*/";
447     OS << '\n';
448     return CurrentIdx - StartIdx + 1;
449   }
450 
451   case Matcher::RecordNode:
452     OS << "OPC_RecordNode,";
453     if (!OmitComments)
454       OS << " // #"
455          << cast<RecordMatcher>(N)->getResultNo() << " = "
456          << cast<RecordMatcher>(N)->getWhatFor();
457     OS << '\n';
458     return 1;
459 
460   case Matcher::RecordChild:
461     OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo()
462        << ',';
463     if (!OmitComments)
464       OS << " // #"
465          << cast<RecordChildMatcher>(N)->getResultNo() << " = "
466          << cast<RecordChildMatcher>(N)->getWhatFor();
467     OS << '\n';
468     return 1;
469 
470   case Matcher::RecordMemRef:
471     OS << "OPC_RecordMemRef,\n";
472     return 1;
473 
474   case Matcher::CaptureGlueInput:
475     OS << "OPC_CaptureGlueInput,\n";
476     return 1;
477 
478   case Matcher::MoveChild: {
479     const auto *MCM = cast<MoveChildMatcher>(N);
480 
481     OS << "OPC_MoveChild";
482     // Handle the specialized forms.
483     if (MCM->getChildNo() >= 8)
484       OS << ", ";
485     OS << MCM->getChildNo() << ",\n";
486     return (MCM->getChildNo() >= 8) ? 2 : 1;
487   }
488 
489   case Matcher::MoveSibling: {
490     const auto *MSM = cast<MoveSiblingMatcher>(N);
491 
492     OS << "OPC_MoveSibling";
493     // Handle the specialized forms.
494     if (MSM->getSiblingNo() >= 8)
495       OS << ", ";
496     OS << MSM->getSiblingNo() << ",\n";
497     return (MSM->getSiblingNo() >= 8) ? 2 : 1;
498   }
499 
500   case Matcher::MoveParent:
501     OS << "OPC_MoveParent,\n";
502     return 1;
503 
504   case Matcher::CheckSame:
505     OS << "OPC_CheckSame, "
506        << cast<CheckSameMatcher>(N)->getMatchNumber() << ",\n";
507     return 2;
508 
509   case Matcher::CheckChildSame:
510     OS << "OPC_CheckChild"
511        << cast<CheckChildSameMatcher>(N)->getChildNo() << "Same, "
512        << cast<CheckChildSameMatcher>(N)->getMatchNumber() << ",\n";
513     return 2;
514 
515   case Matcher::CheckPatternPredicate: {
516     StringRef Pred = cast<CheckPatternPredicateMatcher>(N)->getPredicate();
517     unsigned PredNo = getPatternPredicate(Pred);
518     if (PredNo > 255)
519       OS << "OPC_CheckPatternPredicateTwoByte, TARGET_VAL(" << PredNo << "),";
520     else if (PredNo < 8)
521       OS << "OPC_CheckPatternPredicate" << PredNo << ',';
522     else
523       OS << "OPC_CheckPatternPredicate, " << PredNo << ',';
524     if (!OmitComments)
525       OS << " // " << Pred;
526     OS << '\n';
527     return 2 + (PredNo > 255) - (PredNo < 8);
528   }
529   case Matcher::CheckPredicate: {
530     TreePredicateFn Pred = cast<CheckPredicateMatcher>(N)->getPredicate();
531     unsigned OperandBytes = 0;
532 
533     if (Pred.usesOperands()) {
534       unsigned NumOps = cast<CheckPredicateMatcher>(N)->getNumOperands();
535       OS << "OPC_CheckPredicateWithOperands, " << NumOps << "/*#Ops*/, ";
536       for (unsigned i = 0; i < NumOps; ++i)
537         OS << cast<CheckPredicateMatcher>(N)->getOperandNo(i) << ", ";
538       OperandBytes = 1 + NumOps;
539     } else {
540       OS << "OPC_CheckPredicate, ";
541     }
542 
543     OS << getNodePredicate(Pred) << ',';
544     if (!OmitComments)
545       OS << " // " << Pred.getFnName();
546     OS << '\n';
547     return 2 + OperandBytes;
548   }
549 
550   case Matcher::CheckOpcode:
551     OS << "OPC_CheckOpcode, TARGET_VAL("
552        << cast<CheckOpcodeMatcher>(N)->getOpcode().getEnumName() << "),\n";
553     return 3;
554 
555   case Matcher::SwitchOpcode:
556   case Matcher::SwitchType: {
557     unsigned StartIdx = CurrentIdx;
558 
559     unsigned NumCases;
560     if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
561       OS << "OPC_SwitchOpcode ";
562       NumCases = SOM->getNumCases();
563     } else {
564       OS << "OPC_SwitchType ";
565       NumCases = cast<SwitchTypeMatcher>(N)->getNumCases();
566     }
567 
568     if (!OmitComments)
569       OS << "/*" << NumCases << " cases */";
570     OS << ", ";
571     ++CurrentIdx;
572 
573     // For each case we emit the size, then the opcode, then the matcher.
574     for (unsigned i = 0, e = NumCases; i != e; ++i) {
575       const Matcher *Child;
576       unsigned IdxSize;
577       if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
578         Child = SOM->getCaseMatcher(i);
579         IdxSize = 2;  // size of opcode in table is 2 bytes.
580       } else {
581         Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i);
582         IdxSize = 1;  // size of type in table is 1 byte.
583       }
584 
585       if (i != 0) {
586         if (!OmitComments)
587           OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
588         OS.indent(Indent);
589         if (!OmitComments)
590           OS << (isa<SwitchOpcodeMatcher>(N) ?
591                      "/*SwitchOpcode*/ " : "/*SwitchType*/ ");
592       }
593 
594       unsigned ChildSize = Child->getSize();
595       CurrentIdx += EmitVBRValue(ChildSize, OS) + IdxSize;
596       if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
597         OS << "TARGET_VAL(" << SOM->getCaseOpcode(i).getEnumName() << "),";
598       else
599         OS << getEnumName(cast<SwitchTypeMatcher>(N)->getCaseType(i)) << ',';
600       if (!OmitComments)
601         OS << "// ->" << CurrentIdx + ChildSize;
602       OS << '\n';
603 
604       ChildSize = EmitMatcherList(Child, Indent+1, CurrentIdx, OS);
605       assert(ChildSize == Child->getSize() &&
606              "Emitted child size does not match calculated size");
607       CurrentIdx += ChildSize;
608     }
609 
610     // Emit the final zero to terminate the switch.
611     if (!OmitComments)
612       OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
613     OS.indent(Indent) << "0,";
614     if (!OmitComments)
615       OS << (isa<SwitchOpcodeMatcher>(N) ?
616              " // EndSwitchOpcode" : " // EndSwitchType");
617 
618     OS << '\n';
619     return CurrentIdx - StartIdx + 1;
620   }
621 
622   case Matcher::CheckType:
623     if (cast<CheckTypeMatcher>(N)->getResNo() == 0) {
624       MVT::SimpleValueType VT = cast<CheckTypeMatcher>(N)->getType();
625       switch (VT) {
626       case MVT::i32:
627       case MVT::i64:
628         OS << "OPC_CheckTypeI" << MVT(VT).getSizeInBits() << ",\n";
629         return 1;
630       default:
631         OS << "OPC_CheckType, " << getEnumName(VT) << ",\n";
632         return 2;
633       }
634     }
635     OS << "OPC_CheckTypeRes, " << cast<CheckTypeMatcher>(N)->getResNo() << ", "
636        << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
637     return 3;
638 
639   case Matcher::CheckChildType: {
640     MVT::SimpleValueType VT = cast<CheckChildTypeMatcher>(N)->getType();
641     switch (VT) {
642     case MVT::i32:
643     case MVT::i64:
644       OS << "OPC_CheckChild" << cast<CheckChildTypeMatcher>(N)->getChildNo()
645          << "TypeI" << MVT(VT).getSizeInBits() << ",\n";
646       return 1;
647     default:
648       OS << "OPC_CheckChild" << cast<CheckChildTypeMatcher>(N)->getChildNo()
649          << "Type, " << getEnumName(VT) << ",\n";
650       return 2;
651     }
652   }
653 
654   case Matcher::CheckInteger: {
655     OS << "OPC_CheckInteger, ";
656     unsigned Bytes =
657         1 + EmitSignedVBRValue(cast<CheckIntegerMatcher>(N)->getValue(), OS);
658     OS << '\n';
659     return Bytes;
660   }
661   case Matcher::CheckChildInteger: {
662     OS << "OPC_CheckChild" << cast<CheckChildIntegerMatcher>(N)->getChildNo()
663        << "Integer, ";
664     unsigned Bytes = 1 + EmitSignedVBRValue(
665                              cast<CheckChildIntegerMatcher>(N)->getValue(), OS);
666     OS << '\n';
667     return Bytes;
668   }
669   case Matcher::CheckCondCode:
670     OS << "OPC_CheckCondCode, ISD::"
671        << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
672     return 2;
673 
674   case Matcher::CheckChild2CondCode:
675     OS << "OPC_CheckChild2CondCode, ISD::"
676        << cast<CheckChild2CondCodeMatcher>(N)->getCondCodeName() << ",\n";
677     return 2;
678 
679   case Matcher::CheckValueType:
680     OS << "OPC_CheckValueType, MVT::"
681        << cast<CheckValueTypeMatcher>(N)->getTypeName() << ",\n";
682     return 2;
683 
684   case Matcher::CheckComplexPat: {
685     const CheckComplexPatMatcher *CCPM = cast<CheckComplexPatMatcher>(N);
686     const ComplexPattern &Pattern = CCPM->getPattern();
687     unsigned PatternNo = getComplexPat(Pattern);
688     if (PatternNo < 8)
689       OS << "OPC_CheckComplexPat" << PatternNo << ", /*#*/"
690          << CCPM->getMatchNumber() << ',';
691     else
692       OS << "OPC_CheckComplexPat, /*CP*/" << PatternNo << ", /*#*/"
693          << CCPM->getMatchNumber() << ',';
694 
695     if (!OmitComments) {
696       OS << " // " << Pattern.getSelectFunc();
697       OS << ":$" << CCPM->getName();
698       for (unsigned i = 0, e = Pattern.getNumOperands(); i != e; ++i)
699         OS << " #" << CCPM->getFirstResult()+i;
700 
701       if (Pattern.hasProperty(SDNPHasChain))
702         OS << " + chain result";
703     }
704     OS << '\n';
705     return PatternNo < 8 ? 2 : 3;
706   }
707 
708   case Matcher::CheckAndImm: {
709     OS << "OPC_CheckAndImm, ";
710     unsigned Bytes=1+EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS);
711     OS << '\n';
712     return Bytes;
713   }
714 
715   case Matcher::CheckOrImm: {
716     OS << "OPC_CheckOrImm, ";
717     unsigned Bytes = 1+EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS);
718     OS << '\n';
719     return Bytes;
720   }
721 
722   case Matcher::CheckFoldableChainNode:
723     OS << "OPC_CheckFoldableChainNode,\n";
724     return 1;
725 
726   case Matcher::CheckImmAllOnesV:
727     OS << "OPC_CheckImmAllOnesV,\n";
728     return 1;
729 
730   case Matcher::CheckImmAllZerosV:
731     OS << "OPC_CheckImmAllZerosV,\n";
732     return 1;
733 
734   case Matcher::EmitInteger: {
735     int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
736     MVT::SimpleValueType VT = cast<EmitIntegerMatcher>(N)->getVT();
737     unsigned OpBytes;
738     switch (VT) {
739     case MVT::i8:
740     case MVT::i16:
741     case MVT::i32:
742     case MVT::i64:
743       OpBytes = 1;
744       OS << "OPC_EmitInteger" << MVT(VT).getSizeInBits() << ", ";
745       break;
746     default:
747       OpBytes = 2;
748       OS << "OPC_EmitInteger, " << getEnumName(VT) << ", ";
749       break;
750     }
751     unsigned Bytes = OpBytes + EmitSignedVBRValue(Val, OS);
752     OS << '\n';
753     return Bytes;
754   }
755   case Matcher::EmitStringInteger: {
756     const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
757     MVT::SimpleValueType VT = cast<EmitStringIntegerMatcher>(N)->getVT();
758     // These should always fit into 7 bits.
759     unsigned OpBytes;
760     switch (VT) {
761     case MVT::i32:
762       OpBytes = 1;
763       OS << "OPC_EmitStringInteger" << MVT(VT).getSizeInBits() << ", ";
764       break;
765     default:
766       OpBytes = 2;
767       OS << "OPC_EmitStringInteger, " << getEnumName(VT) << ", ";
768       break;
769     }
770     OS << Val << ",\n";
771     return OpBytes + 1;
772   }
773 
774   case Matcher::EmitRegister: {
775     const EmitRegisterMatcher *Matcher = cast<EmitRegisterMatcher>(N);
776     const CodeGenRegister *Reg = Matcher->getReg();
777     MVT::SimpleValueType VT = Matcher->getVT();
778     // If the enum value of the register is larger than one byte can handle,
779     // use EmitRegister2.
780     if (Reg && Reg->EnumValue > 255) {
781       OS << "OPC_EmitRegister2, " << getEnumName(VT) << ", ";
782       OS << "TARGET_VAL(" << getQualifiedName(Reg->TheDef) << "),\n";
783       return 4;
784     }
785     unsigned OpBytes;
786     switch (VT) {
787     case MVT::i32:
788     case MVT::i64:
789       OpBytes = 1;
790       OS << "OPC_EmitRegisterI" << MVT(VT).getSizeInBits() << ", ";
791       break;
792     default:
793       OpBytes = 2;
794       OS << "OPC_EmitRegister, " << getEnumName(VT) << ", ";
795       break;
796     }
797     if (Reg) {
798       OS << getQualifiedName(Reg->TheDef) << ",\n";
799     } else {
800       OS << "0 ";
801       if (!OmitComments)
802         OS << "/*zero_reg*/";
803       OS << ",\n";
804     }
805     return OpBytes + 1;
806   }
807 
808   case Matcher::EmitConvertToTarget: {
809     unsigned Slot = cast<EmitConvertToTargetMatcher>(N)->getSlot();
810     if (Slot < 8) {
811       OS << "OPC_EmitConvertToTarget" << Slot << ",\n";
812       return 1;
813     }
814     OS << "OPC_EmitConvertToTarget, " << Slot << ",\n";
815     return 2;
816   }
817 
818   case Matcher::EmitMergeInputChains: {
819     const EmitMergeInputChainsMatcher *MN =
820       cast<EmitMergeInputChainsMatcher>(N);
821 
822     // Handle the specialized forms OPC_EmitMergeInputChains1_0, 1_1, and 1_2.
823     if (MN->getNumNodes() == 1 && MN->getNode(0) < 3) {
824       OS << "OPC_EmitMergeInputChains1_" << MN->getNode(0) << ",\n";
825       return 1;
826     }
827 
828     OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
829     for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
830       OS << MN->getNode(i) << ", ";
831     OS << '\n';
832     return 2+MN->getNumNodes();
833   }
834   case Matcher::EmitCopyToReg: {
835     const auto *C2RMatcher = cast<EmitCopyToRegMatcher>(N);
836     int Bytes = 3;
837     const CodeGenRegister *Reg = C2RMatcher->getDestPhysReg();
838     unsigned Slot = C2RMatcher->getSrcSlot();
839     if (Reg->EnumValue > 255) {
840       assert(isUInt<16>(Reg->EnumValue) && "not handled");
841       OS << "OPC_EmitCopyToRegTwoByte, " << Slot << ", "
842          << "TARGET_VAL(" << getQualifiedName(Reg->TheDef) << "),\n";
843       ++Bytes;
844     } else {
845       if (Slot < 8) {
846         OS << "OPC_EmitCopyToReg" << Slot << ", "
847            << getQualifiedName(Reg->TheDef) << ",\n";
848         --Bytes;
849       } else
850         OS << "OPC_EmitCopyToReg, " << Slot << ", "
851            << getQualifiedName(Reg->TheDef) << ",\n";
852     }
853 
854     return Bytes;
855   }
856   case Matcher::EmitNodeXForm: {
857     const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
858     OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
859        << XF->getSlot() << ',';
860     if (!OmitComments)
861       OS << " // "<<XF->getNodeXForm()->getName();
862     OS <<'\n';
863     return 3;
864   }
865 
866   case Matcher::EmitNode:
867   case Matcher::MorphNodeTo: {
868     auto NumCoveredBytes = 0;
869     if (InstrumentCoverage) {
870       if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
871         NumCoveredBytes = 3;
872         OS << "OPC_Coverage, ";
873         std::string src =
874             GetPatFromTreePatternNode(SNT->getPattern().getSrcPattern());
875         std::string dst =
876             GetPatFromTreePatternNode(SNT->getPattern().getDstPattern());
877         Record *PatRecord = SNT->getPattern().getSrcRecord();
878         std::string include_src = getIncludePath(PatRecord);
879         unsigned Offset =
880             getPatternIdxFromTable(src + " -> " + dst, std::move(include_src));
881         OS << "TARGET_VAL(" << Offset << "),\n";
882         OS.indent(FullIndexWidth + Indent);
883       }
884     }
885     const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
886     bool IsEmitNode = isa<EmitNodeMatcher>(EN);
887     OS << (IsEmitNode ? "OPC_EmitNode" : "OPC_MorphNodeTo");
888     bool CompressVTs = EN->getNumVTs() < 3;
889     bool CompressNodeInfo = false;
890     if (CompressVTs) {
891       OS << EN->getNumVTs();
892       if (!EN->hasChain() && !EN->hasInGlue() && !EN->hasOutGlue() &&
893           !EN->hasMemRefs() && EN->getNumFixedArityOperands() == -1) {
894         CompressNodeInfo = true;
895         OS << "None";
896       } else if (EN->hasChain() && !EN->hasInGlue() && !EN->hasOutGlue() &&
897                  !EN->hasMemRefs() && EN->getNumFixedArityOperands() == -1) {
898         CompressNodeInfo = true;
899         OS << "Chain";
900       } else if (!IsEmitNode && !EN->hasChain() && EN->hasInGlue() &&
901                  !EN->hasOutGlue() && !EN->hasMemRefs() &&
902                  EN->getNumFixedArityOperands() == -1) {
903         CompressNodeInfo = true;
904         OS << "GlueInput";
905       } else if (!IsEmitNode && !EN->hasChain() && !EN->hasInGlue() &&
906                  EN->hasOutGlue() && !EN->hasMemRefs() &&
907                  EN->getNumFixedArityOperands() == -1) {
908         CompressNodeInfo = true;
909         OS << "GlueOutput";
910       }
911     }
912 
913     const CodeGenInstruction &CGI = EN->getInstruction();
914     OS << ", TARGET_VAL(" << CGI.Namespace << "::" << CGI.TheDef->getName()
915        << ")";
916 
917     if (!CompressNodeInfo) {
918       OS << ", 0";
919       if (EN->hasChain())
920         OS << "|OPFL_Chain";
921       if (EN->hasInGlue())
922         OS << "|OPFL_GlueInput";
923       if (EN->hasOutGlue())
924         OS << "|OPFL_GlueOutput";
925       if (EN->hasMemRefs())
926         OS << "|OPFL_MemRefs";
927       if (EN->getNumFixedArityOperands() != -1)
928         OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
929     }
930     OS << ",\n";
931 
932     OS.indent(FullIndexWidth + Indent+4);
933     if (!CompressVTs) {
934       OS << EN->getNumVTs();
935       if (!OmitComments)
936         OS << "/*#VTs*/";
937       OS << ", ";
938     }
939     for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
940       OS << getEnumName(EN->getVT(i)) << ", ";
941 
942     OS << EN->getNumOperands();
943     if (!OmitComments)
944       OS << "/*#Ops*/";
945     OS << ", ";
946     unsigned NumOperandBytes = 0;
947     for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
948       NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
949 
950     if (!OmitComments) {
951       // Print the result #'s for EmitNode.
952       if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) {
953         if (unsigned NumResults = EN->getNumVTs()) {
954           OS << " // Results =";
955           unsigned First = E->getFirstResultSlot();
956           for (unsigned i = 0; i != NumResults; ++i)
957             OS << " #" << First+i;
958         }
959       }
960       OS << '\n';
961 
962       if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
963         OS.indent(FullIndexWidth + Indent) << "// Src: "
964           << *SNT->getPattern().getSrcPattern() << " - Complexity = "
965           << SNT->getPattern().getPatternComplexity(CGP) << '\n';
966         OS.indent(FullIndexWidth + Indent) << "// Dst: "
967           << *SNT->getPattern().getDstPattern() << '\n';
968       }
969     } else
970       OS << '\n';
971 
972     return 4 + !CompressVTs + !CompressNodeInfo + EN->getNumVTs() +
973            NumOperandBytes + NumCoveredBytes;
974   }
975   case Matcher::CompleteMatch: {
976     const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
977     auto NumCoveredBytes = 0;
978     if (InstrumentCoverage) {
979       NumCoveredBytes = 3;
980       OS << "OPC_Coverage, ";
981       std::string src =
982           GetPatFromTreePatternNode(CM->getPattern().getSrcPattern());
983       std::string dst =
984           GetPatFromTreePatternNode(CM->getPattern().getDstPattern());
985       Record *PatRecord = CM->getPattern().getSrcRecord();
986       std::string include_src = getIncludePath(PatRecord);
987       unsigned Offset =
988           getPatternIdxFromTable(src + " -> " + dst, std::move(include_src));
989       OS << "TARGET_VAL(" << Offset << "),\n";
990       OS.indent(FullIndexWidth + Indent);
991     }
992     OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
993     unsigned NumResultBytes = 0;
994     for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
995       NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
996     OS << '\n';
997     if (!OmitComments) {
998       OS.indent(FullIndexWidth + Indent) << " // Src: "
999         << *CM->getPattern().getSrcPattern() << " - Complexity = "
1000         << CM->getPattern().getPatternComplexity(CGP) << '\n';
1001       OS.indent(FullIndexWidth + Indent) << " // Dst: "
1002         << *CM->getPattern().getDstPattern();
1003     }
1004     OS << '\n';
1005     return 2 + NumResultBytes + NumCoveredBytes;
1006   }
1007   }
1008   llvm_unreachable("Unreachable");
1009 }
1010 
1011 /// This function traverses the matcher tree and emits all the nodes.
1012 /// The nodes have already been sized.
1013 unsigned MatcherTableEmitter::
1014 EmitMatcherList(const Matcher *N, const unsigned Indent, unsigned CurrentIdx,
1015                 raw_ostream &OS) {
1016   unsigned Size = 0;
1017   while (N) {
1018     if (!OmitComments)
1019       OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
1020     unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
1021     Size += MatcherSize;
1022     CurrentIdx += MatcherSize;
1023 
1024     // If there are other nodes in this list, iterate to them, otherwise we're
1025     // done.
1026     N = N->getNext();
1027   }
1028   return Size;
1029 }
1030 
1031 void MatcherTableEmitter::EmitNodePredicatesFunction(
1032     const std::vector<TreePredicateFn> &Preds, StringRef Decl,
1033     raw_ostream &OS) {
1034   if (Preds.empty())
1035     return;
1036 
1037   BeginEmitFunction(OS, "bool", Decl, true/*AddOverride*/);
1038   OS << "{\n";
1039   OS << "  switch (PredNo) {\n";
1040   OS << "  default: llvm_unreachable(\"Invalid predicate in table?\");\n";
1041   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1042     // Emit the predicate code corresponding to this pattern.
1043     const TreePredicateFn PredFn = Preds[i];
1044     assert(!PredFn.isAlwaysTrue() && "No code in this predicate");
1045     std::string PredFnCodeStr = PredFn.getCodeToRunOnSDNode();
1046 
1047     OS << "  case " << i << ": {\n";
1048     for (auto *SimilarPred : NodePredicatesByCodeToRun[PredFnCodeStr])
1049       OS << "    // " << TreePredicateFn(SimilarPred).getFnName() << '\n';
1050     OS << PredFnCodeStr << "\n  }\n";
1051   }
1052   OS << "  }\n";
1053   OS << "}\n";
1054   EndEmitFunction(OS);
1055 }
1056 
1057 void MatcherTableEmitter::EmitPredicateFunctions(raw_ostream &OS) {
1058   // Emit pattern predicates.
1059   if (!PatternPredicates.empty()) {
1060     BeginEmitFunction(OS, "bool",
1061           "CheckPatternPredicate(unsigned PredNo) const", true/*AddOverride*/);
1062     OS << "{\n";
1063     OS << "  switch (PredNo) {\n";
1064     OS << "  default: llvm_unreachable(\"Invalid predicate in table?\");\n";
1065     for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
1066       OS << "  case " << i << ": return "  << PatternPredicates[i] << ";\n";
1067     OS << "  }\n";
1068     OS << "}\n";
1069     EndEmitFunction(OS);
1070   }
1071 
1072   // Emit Node predicates.
1073   EmitNodePredicatesFunction(
1074       NodePredicates, "CheckNodePredicate(SDNode *Node, unsigned PredNo) const",
1075       OS);
1076   EmitNodePredicatesFunction(
1077       NodePredicatesWithOperands,
1078       "CheckNodePredicateWithOperands(SDNode *Node, unsigned PredNo, "
1079       "const SmallVectorImpl<SDValue> &Operands) const",
1080       OS);
1081 
1082   // Emit CompletePattern matchers.
1083   // FIXME: This should be const.
1084   if (!ComplexPatterns.empty()) {
1085     BeginEmitFunction(OS, "bool",
1086           "CheckComplexPattern(SDNode *Root, SDNode *Parent,\n"
1087           "      SDValue N, unsigned PatternNo,\n"
1088           "      SmallVectorImpl<std::pair<SDValue, SDNode *>> &Result)",
1089           true/*AddOverride*/);
1090     OS << "{\n";
1091     OS << "  unsigned NextRes = Result.size();\n";
1092     OS << "  switch (PatternNo) {\n";
1093     OS << "  default: llvm_unreachable(\"Invalid pattern # in table?\");\n";
1094     for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
1095       const ComplexPattern &P = *ComplexPatterns[i];
1096       unsigned NumOps = P.getNumOperands();
1097 
1098       if (P.hasProperty(SDNPHasChain))
1099         ++NumOps;  // Get the chained node too.
1100 
1101       OS << "  case " << i << ":\n";
1102       if (InstrumentCoverage)
1103         OS << "  {\n";
1104       OS << "    Result.resize(NextRes+" << NumOps << ");\n";
1105       if (InstrumentCoverage)
1106         OS << "    bool Succeeded = " << P.getSelectFunc();
1107       else
1108         OS << "  return " << P.getSelectFunc();
1109 
1110       OS << "(";
1111       // If the complex pattern wants the root of the match, pass it in as the
1112       // first argument.
1113       if (P.hasProperty(SDNPWantRoot))
1114         OS << "Root, ";
1115 
1116       // If the complex pattern wants the parent of the operand being matched,
1117       // pass it in as the next argument.
1118       if (P.hasProperty(SDNPWantParent))
1119         OS << "Parent, ";
1120 
1121       OS << "N";
1122       for (unsigned i = 0; i != NumOps; ++i)
1123         OS << ", Result[NextRes+" << i << "].first";
1124       OS << ");\n";
1125       if (InstrumentCoverage) {
1126         OS << "    if (Succeeded)\n";
1127         OS << "       dbgs() << \"\\nCOMPLEX_PATTERN: " << P.getSelectFunc()
1128            << "\\n\" ;\n";
1129         OS << "    return Succeeded;\n";
1130         OS << "    }\n";
1131       }
1132     }
1133     OS << "  }\n";
1134     OS << "}\n";
1135     EndEmitFunction(OS);
1136   }
1137 
1138 
1139   // Emit SDNodeXForm handlers.
1140   // FIXME: This should be const.
1141   if (!NodeXForms.empty()) {
1142     BeginEmitFunction(OS, "SDValue",
1143           "RunSDNodeXForm(SDValue V, unsigned XFormNo)", true/*AddOverride*/);
1144     OS << "{\n";
1145     OS << "  switch (XFormNo) {\n";
1146     OS << "  default: llvm_unreachable(\"Invalid xform # in table?\");\n";
1147 
1148     // FIXME: The node xform could take SDValue's instead of SDNode*'s.
1149     for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i) {
1150       const CodeGenDAGPatterns::NodeXForm &Entry =
1151         CGP.getSDNodeTransform(NodeXForms[i]);
1152 
1153       Record *SDNode = Entry.first;
1154       const std::string &Code = Entry.second;
1155 
1156       OS << "  case " << i << ": {  ";
1157       if (!OmitComments)
1158         OS << "// " << NodeXForms[i]->getName();
1159       OS << '\n';
1160 
1161       std::string ClassName =
1162           std::string(CGP.getSDNodeInfo(SDNode).getSDClassName());
1163       if (ClassName == "SDNode")
1164         OS << "    SDNode *N = V.getNode();\n";
1165       else
1166         OS << "    " << ClassName << " *N = cast<" << ClassName
1167            << ">(V.getNode());\n";
1168       OS << Code << "\n  }\n";
1169     }
1170     OS << "  }\n";
1171     OS << "}\n";
1172     EndEmitFunction(OS);
1173   }
1174 }
1175 
1176 static StringRef getOpcodeString(Matcher::KindTy Kind) {
1177   switch (Kind) {
1178   case Matcher::Scope:
1179     return "OPC_Scope";
1180   case Matcher::RecordNode:
1181     return "OPC_RecordNode";
1182   case Matcher::RecordChild:
1183     return "OPC_RecordChild";
1184   case Matcher::RecordMemRef:
1185     return "OPC_RecordMemRef";
1186   case Matcher::CaptureGlueInput:
1187     return "OPC_CaptureGlueInput";
1188   case Matcher::MoveChild:
1189     return "OPC_MoveChild";
1190   case Matcher::MoveSibling:
1191     return "OPC_MoveSibling";
1192   case Matcher::MoveParent:
1193     return "OPC_MoveParent";
1194   case Matcher::CheckSame:
1195     return "OPC_CheckSame";
1196   case Matcher::CheckChildSame:
1197     return "OPC_CheckChildSame";
1198   case Matcher::CheckPatternPredicate:
1199     return "OPC_CheckPatternPredicate";
1200   case Matcher::CheckPredicate:
1201     return "OPC_CheckPredicate";
1202   case Matcher::CheckOpcode:
1203     return "OPC_CheckOpcode";
1204   case Matcher::SwitchOpcode:
1205     return "OPC_SwitchOpcode";
1206   case Matcher::CheckType:
1207     return "OPC_CheckType";
1208   case Matcher::SwitchType:
1209     return "OPC_SwitchType";
1210   case Matcher::CheckChildType:
1211     return "OPC_CheckChildType";
1212   case Matcher::CheckInteger:
1213     return "OPC_CheckInteger";
1214   case Matcher::CheckChildInteger:
1215     return "OPC_CheckChildInteger";
1216   case Matcher::CheckCondCode:
1217     return "OPC_CheckCondCode";
1218   case Matcher::CheckChild2CondCode:
1219     return "OPC_CheckChild2CondCode";
1220   case Matcher::CheckValueType:
1221     return "OPC_CheckValueType";
1222   case Matcher::CheckComplexPat:
1223     return "OPC_CheckComplexPat";
1224   case Matcher::CheckAndImm:
1225     return "OPC_CheckAndImm";
1226   case Matcher::CheckOrImm:
1227     return "OPC_CheckOrImm";
1228   case Matcher::CheckFoldableChainNode:
1229     return "OPC_CheckFoldableChainNode";
1230   case Matcher::CheckImmAllOnesV:
1231     return "OPC_CheckImmAllOnesV";
1232   case Matcher::CheckImmAllZerosV:
1233     return "OPC_CheckImmAllZerosV";
1234   case Matcher::EmitInteger:
1235     return "OPC_EmitInteger";
1236   case Matcher::EmitStringInteger:
1237     return "OPC_EmitStringInteger";
1238   case Matcher::EmitRegister:
1239     return "OPC_EmitRegister";
1240   case Matcher::EmitConvertToTarget:
1241     return "OPC_EmitConvertToTarget";
1242   case Matcher::EmitMergeInputChains:
1243     return "OPC_EmitMergeInputChains";
1244   case Matcher::EmitCopyToReg:
1245     return "OPC_EmitCopyToReg";
1246   case Matcher::EmitNode:
1247     return "OPC_EmitNode";
1248   case Matcher::MorphNodeTo:
1249     return "OPC_MorphNodeTo";
1250   case Matcher::EmitNodeXForm:
1251     return "OPC_EmitNodeXForm";
1252   case Matcher::CompleteMatch:
1253     return "OPC_CompleteMatch";
1254   }
1255 
1256   llvm_unreachable("Unhandled opcode?");
1257 }
1258 
1259 void MatcherTableEmitter::EmitHistogram(const Matcher *M,
1260                                         raw_ostream &OS) {
1261   if (OmitComments)
1262     return;
1263 
1264   OS << "  // Opcode Histogram:\n";
1265   for (unsigned i = 0, e = OpcodeCounts.size(); i != e; ++i) {
1266     OS << "  // #"
1267        << left_justify(getOpcodeString((Matcher::KindTy)i), HistOpcWidth)
1268        << " = " << OpcodeCounts[i] << '\n';
1269   }
1270   OS << '\n';
1271 }
1272 
1273 
1274 void llvm::EmitMatcherTable(Matcher *TheMatcher,
1275                             const CodeGenDAGPatterns &CGP,
1276                             raw_ostream &OS) {
1277   OS << "#if defined(GET_DAGISEL_DECL) && defined(GET_DAGISEL_BODY)\n";
1278   OS << "#error GET_DAGISEL_DECL and GET_DAGISEL_BODY cannot be both defined, ";
1279   OS << "undef both for inline definitions\n";
1280   OS << "#endif\n\n";
1281 
1282   // Emit a check for omitted class name.
1283   OS << "#ifdef GET_DAGISEL_BODY\n";
1284   OS << "#define LOCAL_DAGISEL_STRINGIZE(X) LOCAL_DAGISEL_STRINGIZE_(X)\n";
1285   OS << "#define LOCAL_DAGISEL_STRINGIZE_(X) #X\n";
1286   OS << "static_assert(sizeof(LOCAL_DAGISEL_STRINGIZE(GET_DAGISEL_BODY)) > 1,"
1287         "\n";
1288   OS << "   \"GET_DAGISEL_BODY is empty: it should be defined with the class "
1289         "name\");\n";
1290   OS << "#undef LOCAL_DAGISEL_STRINGIZE_\n";
1291   OS << "#undef LOCAL_DAGISEL_STRINGIZE\n";
1292   OS << "#endif\n\n";
1293 
1294   OS << "#if !defined(GET_DAGISEL_DECL) && !defined(GET_DAGISEL_BODY)\n";
1295   OS << "#define DAGISEL_INLINE 1\n";
1296   OS << "#else\n";
1297   OS << "#define DAGISEL_INLINE 0\n";
1298   OS << "#endif\n\n";
1299 
1300   OS << "#if !DAGISEL_INLINE\n";
1301   OS << "#define DAGISEL_CLASS_COLONCOLON GET_DAGISEL_BODY ::\n";
1302   OS << "#else\n";
1303   OS << "#define DAGISEL_CLASS_COLONCOLON\n";
1304   OS << "#endif\n\n";
1305 
1306   BeginEmitFunction(OS, "void", "SelectCode(SDNode *N)", false/*AddOverride*/);
1307   MatcherTableEmitter MatcherEmitter(TheMatcher, CGP);
1308 
1309   // First we size all the children of the three kinds of matchers that have
1310   // them. This is done by sharing the code in EmitMatcher(). but we don't
1311   // want to emit anything, so we turn off comments and use a null stream.
1312   bool SaveOmitComments = OmitComments;
1313   OmitComments = true;
1314   raw_null_ostream NullOS;
1315   unsigned TotalSize = MatcherEmitter.SizeMatcherList(TheMatcher, NullOS);
1316   OmitComments = SaveOmitComments;
1317 
1318   // Now that the matchers are sized, we can emit the code for them to the
1319   // final stream.
1320   OS << "{\n";
1321   OS << "  // Some target values are emitted as 2 bytes, TARGET_VAL handles\n";
1322   OS << "  // this.\n";
1323   OS << "  #define TARGET_VAL(X) X & 255, unsigned(X) >> 8\n";
1324   OS << "  static const unsigned char MatcherTable[] = {\n";
1325   TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 1, 0, OS);
1326   OS << "    0\n  }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
1327 
1328   MatcherEmitter.EmitHistogram(TheMatcher, OS);
1329 
1330   OS << "  #undef TARGET_VAL\n";
1331   OS << "  SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n";
1332   OS << "}\n";
1333   EndEmitFunction(OS);
1334 
1335   // Next up, emit the function for node and pattern predicates:
1336   MatcherEmitter.EmitPredicateFunctions(OS);
1337 
1338   if (InstrumentCoverage)
1339     MatcherEmitter.EmitPatternMatchTable(OS);
1340 
1341   // Clean up the preprocessor macros.
1342   OS << "\n";
1343   OS << "#ifdef DAGISEL_INLINE\n";
1344   OS << "#undef DAGISEL_INLINE\n";
1345   OS << "#endif\n";
1346   OS << "#ifdef DAGISEL_CLASS_COLONCOLON\n";
1347   OS << "#undef DAGISEL_CLASS_COLONCOLON\n";
1348   OS << "#endif\n";
1349   OS << "#ifdef GET_DAGISEL_DECL\n";
1350   OS << "#undef GET_DAGISEL_DECL\n";
1351   OS << "#endif\n";
1352   OS << "#ifdef GET_DAGISEL_BODY\n";
1353   OS << "#undef GET_DAGISEL_BODY\n";
1354   OS << "#endif\n";
1355 }
1356