1 //===- DAGISelMatcherEmitter.cpp - Matcher Emitter ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains code to generate C++ code a matcher.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelMatcher.h"
15 #include "CodeGenDAGPatterns.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/Support/FormattedStream.h"
28 class MatcherTableEmitter {
29 StringMap<unsigned> NodePredicateMap, PatternPredicateMap;
30 std::vector<std::string> NodePredicates, PatternPredicates;
32 DenseMap<const ComplexPattern*, unsigned> ComplexPatternMap;
33 std::vector<const ComplexPattern*> ComplexPatterns;
36 DenseMap<Record*, unsigned> NodeXFormMap;
37 std::vector<const Record*> NodeXForms;
39 // Per opcode frequence count.
40 std::vector<unsigned> Histogram;
42 MatcherTableEmitter() {}
44 unsigned EmitMatcherList(const Matcher *N, unsigned Indent,
45 unsigned StartIdx, formatted_raw_ostream &OS);
47 void EmitPredicateFunctions(formatted_raw_ostream &OS);
49 void EmitHistogram(formatted_raw_ostream &OS);
51 unsigned EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
52 formatted_raw_ostream &OS);
54 unsigned getNodePredicate(StringRef PredName) {
55 unsigned &Entry = NodePredicateMap[PredName];
57 NodePredicates.push_back(PredName.str());
58 Entry = NodePredicates.size();
62 unsigned getPatternPredicate(StringRef PredName) {
63 unsigned &Entry = PatternPredicateMap[PredName];
65 PatternPredicates.push_back(PredName.str());
66 Entry = PatternPredicates.size();
71 unsigned getComplexPat(const ComplexPattern &P) {
72 unsigned &Entry = ComplexPatternMap[&P];
74 ComplexPatterns.push_back(&P);
75 Entry = ComplexPatterns.size();
80 unsigned getNodeXFormID(Record *Rec) {
81 unsigned &Entry = NodeXFormMap[Rec];
83 NodeXForms.push_back(Rec);
84 Entry = NodeXForms.size();
90 } // end anonymous namespace.
92 static unsigned GetVBRSize(unsigned Val) {
93 if (Val <= 127) return 1;
95 unsigned NumBytes = 0;
103 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
105 static uint64_t EmitVBRValue(uint64_t Val, raw_ostream &OS) {
111 uint64_t InVal = Val;
112 unsigned NumBytes = 0;
114 OS << (Val&127) << "|128,";
118 OS << Val << "/*" << InVal << "*/, ";
122 /// EmitMatcherOpcodes - Emit bytes for the specified matcher and return
123 /// the number of bytes emitted.
124 unsigned MatcherTableEmitter::
125 EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
126 formatted_raw_ostream &OS) {
127 OS.PadToColumn(Indent*2);
129 switch (N->getKind()) {
130 case Matcher::Scope: {
131 const ScopeMatcher *SM = cast<ScopeMatcher>(N);
132 assert(SM->getNext() == 0 && "Shouldn't have next after scope");
134 unsigned StartIdx = CurrentIdx;
136 // Emit all of the children.
137 for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
142 OS << "/*" << CurrentIdx << "*/";
143 OS.PadToColumn(Indent*2) << "/*Scope*/ ";
146 // We need to encode the child and the offset of the failure code before
147 // emitting either of them. Handle this by buffering the output into a
148 // string while we get the size. Unfortunately, the offset of the
149 // children depends on the VBR size of the child, so for large children we
150 // have to iterate a bit.
151 SmallString<128> TmpBuf;
152 unsigned ChildSize = 0;
153 unsigned VBRSize = 0;
155 VBRSize = GetVBRSize(ChildSize);
158 raw_svector_ostream OS(TmpBuf);
159 formatted_raw_ostream FOS(OS);
160 ChildSize = EmitMatcherList(cast<ScopeMatcher>(N)->getChild(i),
161 Indent+1, CurrentIdx+VBRSize, FOS);
162 } while (GetVBRSize(ChildSize) != VBRSize);
164 assert(ChildSize != 0 && "Should not have a zero-sized child!");
166 CurrentIdx += EmitVBRValue(ChildSize, OS);
167 OS << "/*->" << CurrentIdx+ChildSize << "*/";
170 OS.PadToColumn(CommentIndent) << "// " << SM->getNumChildren()
171 << " children in Scope";
173 OS << '\n' << TmpBuf.str();
174 CurrentIdx += ChildSize;
177 // Emit a zero as a sentinel indicating end of 'Scope'.
178 OS << "/*" << CurrentIdx << "*/";
179 OS.PadToColumn(Indent*2) << "0, /*End of Scope*/\n";
180 return CurrentIdx - StartIdx + 1;
183 case Matcher::RecordNode:
184 OS << "OPC_RecordNode,";
185 OS.PadToColumn(CommentIndent) << "// "
186 << cast<RecordMatcher>(N)->getWhatFor() << '\n';
189 case Matcher::RecordChild:
190 OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo()
192 OS.PadToColumn(CommentIndent) << "// "
193 << cast<RecordChildMatcher>(N)->getWhatFor() << '\n';
196 case Matcher::RecordMemRef:
197 OS << "OPC_RecordMemRef,\n";
200 case Matcher::CaptureFlagInput:
201 OS << "OPC_CaptureFlagInput,\n";
204 case Matcher::MoveChild:
205 OS << "OPC_MoveChild, " << cast<MoveChildMatcher>(N)->getChildNo() << ",\n";
208 case Matcher::MoveParent:
209 OS << "OPC_MoveParent,\n";
212 case Matcher::CheckSame:
213 OS << "OPC_CheckSame, "
214 << cast<CheckSameMatcher>(N)->getMatchNumber() << ",\n";
217 case Matcher::CheckPatternPredicate: {
218 StringRef Pred = cast<CheckPatternPredicateMatcher>(N)->getPredicate();
219 OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
220 OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
223 case Matcher::CheckPredicate: {
224 StringRef Pred = cast<CheckPredicateMatcher>(N)->getPredicateName();
225 OS << "OPC_CheckPredicate, " << getNodePredicate(Pred) << ',';
226 OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
230 case Matcher::CheckOpcode:
231 OS << "OPC_CheckOpcode, "
232 << cast<CheckOpcodeMatcher>(N)->getOpcode().getEnumName() << ",\n";
235 case Matcher::CheckMultiOpcode: {
236 const CheckMultiOpcodeMatcher *CMO = cast<CheckMultiOpcodeMatcher>(N);
237 OS << "OPC_CheckMultiOpcode, " << CMO->getNumOpcodes() << ", ";
238 for (unsigned i = 0, e = CMO->getNumOpcodes(); i != e; ++i)
239 OS << CMO->getOpcode(i).getEnumName() << ", ";
241 return 2 + CMO->getNumOpcodes();
244 case Matcher::CheckType:
245 OS << "OPC_CheckType, "
246 << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
248 case Matcher::CheckChildType:
249 OS << "OPC_CheckChild"
250 << cast<CheckChildTypeMatcher>(N)->getChildNo() << "Type, "
251 << getEnumName(cast<CheckChildTypeMatcher>(N)->getType()) << ",\n";
254 case Matcher::CheckInteger:
255 OS << "OPC_CheckInteger, ";
256 return 1+EmitVBRValue(cast<CheckIntegerMatcher>(N)->getValue(), OS);
257 case Matcher::CheckCondCode:
258 OS << "OPC_CheckCondCode, ISD::"
259 << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
262 case Matcher::CheckValueType:
263 OS << "OPC_CheckValueType, MVT::"
264 << cast<CheckValueTypeMatcher>(N)->getTypeName() << ",\n";
267 case Matcher::CheckComplexPat: {
268 const ComplexPattern &Pattern =
269 cast<CheckComplexPatMatcher>(N)->getPattern();
270 OS << "OPC_CheckComplexPat, " << getComplexPat(Pattern) << ',';
271 OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
272 OS << ": " << Pattern.getNumOperands() << " operands";
273 if (Pattern.hasProperty(SDNPHasChain))
274 OS << " + chain result and input";
279 case Matcher::CheckAndImm:
280 OS << "OPC_CheckAndImm, ";
281 return 1+EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS);
283 case Matcher::CheckOrImm:
284 OS << "OPC_CheckOrImm, ";
285 return 1+EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS);
287 case Matcher::CheckFoldableChainNode:
288 OS << "OPC_CheckFoldableChainNode,\n";
290 case Matcher::CheckChainCompatible:
291 OS << "OPC_CheckChainCompatible, "
292 << cast<CheckChainCompatibleMatcher>(N)->getPreviousOp() << ",\n";
295 case Matcher::EmitInteger: {
296 int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
297 OS << "OPC_EmitInteger, "
298 << getEnumName(cast<EmitIntegerMatcher>(N)->getVT()) << ", ";
299 return 2+EmitVBRValue(Val, OS);
301 case Matcher::EmitStringInteger: {
302 const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
303 // These should always fit into one byte.
304 OS << "OPC_EmitInteger, "
305 << getEnumName(cast<EmitStringIntegerMatcher>(N)->getVT()) << ", "
310 case Matcher::EmitRegister:
311 OS << "OPC_EmitRegister, "
312 << getEnumName(cast<EmitRegisterMatcher>(N)->getVT()) << ", ";
313 if (Record *R = cast<EmitRegisterMatcher>(N)->getReg())
314 OS << getQualifiedName(R) << ",\n";
316 OS << "0 /*zero_reg*/,\n";
319 case Matcher::EmitConvertToTarget:
320 OS << "OPC_EmitConvertToTarget, "
321 << cast<EmitConvertToTargetMatcher>(N)->getSlot() << ",\n";
324 case Matcher::EmitMergeInputChains: {
325 const EmitMergeInputChainsMatcher *MN =
326 cast<EmitMergeInputChainsMatcher>(N);
327 OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
328 for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
329 OS << MN->getNode(i) << ", ";
331 return 2+MN->getNumNodes();
333 case Matcher::EmitCopyToReg:
334 OS << "OPC_EmitCopyToReg, "
335 << cast<EmitCopyToRegMatcher>(N)->getSrcSlot() << ", "
336 << getQualifiedName(cast<EmitCopyToRegMatcher>(N)->getDestPhysReg())
339 case Matcher::EmitNodeXForm: {
340 const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
341 OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
342 << XF->getSlot() << ',';
343 OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName()<<'\n';
347 case Matcher::EmitNode:
348 case Matcher::MorphNodeTo: {
349 const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
350 OS << (isa<EmitNodeMatcher>(EN) ? "OPC_EmitNode" : "OPC_MorphNodeTo");
351 OS << ", TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
353 if (EN->hasChain()) OS << "|OPFL_Chain";
354 if (EN->hasInFlag()) OS << "|OPFL_FlagInput";
355 if (EN->hasOutFlag()) OS << "|OPFL_FlagOutput";
356 if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
357 if (EN->getNumFixedArityOperands() != -1)
358 OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
361 OS.PadToColumn(Indent*2+4) << EN->getNumVTs() << "/*#VTs*/, ";
362 for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
363 OS << getEnumName(EN->getVT(i)) << ", ";
365 OS << EN->getNumOperands() << "/*#Ops*/, ";
366 unsigned NumOperandBytes = 0;
367 for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i) {
368 // We emit the operand numbers in VBR encoded format, in case the number
369 // is too large to represent with a byte.
370 NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
373 // Print the result #'s for EmitNode.
374 if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) {
375 if (unsigned NumResults = EN->getNumNonChainFlagVTs()) {
376 OS.PadToColumn(CommentIndent) << "// Results = ";
377 unsigned First = E->getFirstResultSlot();
378 for (unsigned i = 0; i != NumResults; ++i)
379 OS << "#" << First+i << " ";
384 if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
385 OS.PadToColumn(Indent*2) << "// Src: "
386 << *SNT->getPattern().getSrcPattern() << '\n';
387 OS.PadToColumn(Indent*2) << "// Dst: "
388 << *SNT->getPattern().getDstPattern() << '\n';
392 return 6+EN->getNumVTs()+NumOperandBytes;
394 case Matcher::MarkFlagResults: {
395 const MarkFlagResultsMatcher *CFR = cast<MarkFlagResultsMatcher>(N);
396 OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", ";
397 unsigned NumOperandBytes = 0;
398 for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i)
399 NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS);
401 return 2+NumOperandBytes;
403 case Matcher::CompleteMatch: {
404 const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
405 OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
406 unsigned NumResultBytes = 0;
407 for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
408 NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
410 OS.PadToColumn(Indent*2) << "// Src: "
411 << *CM->getPattern().getSrcPattern() << '\n';
412 OS.PadToColumn(Indent*2) << "// Dst: "
413 << *CM->getPattern().getDstPattern() << '\n';
414 return 2 + NumResultBytes;
417 assert(0 && "Unreachable");
421 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
422 unsigned MatcherTableEmitter::
423 EmitMatcherList(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
424 formatted_raw_ostream &OS) {
427 if (unsigned(N->getKind()) >= Histogram.size())
428 Histogram.resize(N->getKind()+1);
429 Histogram[N->getKind()]++;
431 OS << "/*" << CurrentIdx << "*/";
432 unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
434 CurrentIdx += MatcherSize;
436 // If there are other nodes in this list, iterate to them, otherwise we're
443 void MatcherTableEmitter::EmitPredicateFunctions(formatted_raw_ostream &OS) {
444 // FIXME: Don't build off the DAGISelEmitter's predicates, emit them directly
445 // here into the case stmts.
447 // Emit pattern predicates.
448 if (!PatternPredicates.empty()) {
449 OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
450 OS << " switch (PredNo) {\n";
451 OS << " default: assert(0 && \"Invalid predicate in table?\");\n";
452 for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
453 OS << " case " << i << ": return " << PatternPredicates[i] << ";\n";
459 // Emit Node predicates.
460 if (!NodePredicates.empty()) {
461 OS << "bool CheckNodePredicate(SDNode *N, unsigned PredNo) const {\n";
462 OS << " switch (PredNo) {\n";
463 OS << " default: assert(0 && \"Invalid predicate in table?\");\n";
464 for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i)
465 OS << " case " << i << ": return " << NodePredicates[i] << "(N);\n";
470 // Emit CompletePattern matchers.
471 // FIXME: This should be const.
472 if (!ComplexPatterns.empty()) {
473 OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
474 OS << " unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
475 OS << " switch (PatternNo) {\n";
476 OS << " default: assert(0 && \"Invalid pattern # in table?\");\n";
477 for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
478 const ComplexPattern &P = *ComplexPatterns[i];
479 unsigned NumOps = P.getNumOperands();
481 if (P.hasProperty(SDNPHasChain))
482 ++NumOps; // Get the chained node too.
484 OS << " case " << i << ":\n";
485 OS << " Result.resize(Result.size()+" << NumOps << ");\n";
486 OS << " return " << P.getSelectFunc();
488 // FIXME: Temporary hack until old isel dies.
489 if (P.hasProperty(SDNPHasChain))
493 for (unsigned i = 0; i != NumOps; ++i)
494 OS << ", Result[Result.size()-" << (NumOps-i) << ']';
501 // Emit SDNodeXForm handlers.
502 // FIXME: This should be const.
503 if (!NodeXForms.empty()) {
504 OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
505 OS << " switch (XFormNo) {\n";
506 OS << " default: assert(0 && \"Invalid xform # in table?\");\n";
508 // FIXME: The node xform could take SDValue's instead of SDNode*'s.
509 for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i)
510 OS << " case " << i << ": return Transform_" << NodeXForms[i]->getName()
511 << "(V.getNode());\n";
517 void MatcherTableEmitter::EmitHistogram(formatted_raw_ostream &OS) {
518 OS << " // Opcode Histogram:\n";
519 for (unsigned i = 0, e = Histogram.size(); i != e; ++i) {
521 switch ((Matcher::KindTy)i) {
522 case Matcher::Scope: OS << "OPC_Scope"; break;
523 case Matcher::RecordNode: OS << "OPC_RecordNode"; break;
524 case Matcher::RecordChild: OS << "OPC_RecordChild"; break;
525 case Matcher::RecordMemRef: OS << "OPC_RecordMemRef"; break;
526 case Matcher::CaptureFlagInput: OS << "OPC_CaptureFlagInput"; break;
527 case Matcher::MoveChild: OS << "OPC_MoveChild"; break;
528 case Matcher::MoveParent: OS << "OPC_MoveParent"; break;
529 case Matcher::CheckSame: OS << "OPC_CheckSame"; break;
530 case Matcher::CheckPatternPredicate:
531 OS << "OPC_CheckPatternPredicate"; break;
532 case Matcher::CheckPredicate: OS << "OPC_CheckPredicate"; break;
533 case Matcher::CheckOpcode: OS << "OPC_CheckOpcode"; break;
534 case Matcher::CheckMultiOpcode: OS << "OPC_CheckMultiOpcode"; break;
535 case Matcher::CheckType: OS << "OPC_CheckType"; break;
536 case Matcher::CheckChildType: OS << "OPC_CheckChildType"; break;
537 case Matcher::CheckInteger: OS << "OPC_CheckInteger"; break;
538 case Matcher::CheckCondCode: OS << "OPC_CheckCondCode"; break;
539 case Matcher::CheckValueType: OS << "OPC_CheckValueType"; break;
540 case Matcher::CheckComplexPat: OS << "OPC_CheckComplexPat"; break;
541 case Matcher::CheckAndImm: OS << "OPC_CheckAndImm"; break;
542 case Matcher::CheckOrImm: OS << "OPC_CheckOrImm"; break;
543 case Matcher::CheckFoldableChainNode:
544 OS << "OPC_CheckFoldableChainNode"; break;
545 case Matcher::CheckChainCompatible: OS << "OPC_CheckChainCompatible"; break;
546 case Matcher::EmitInteger: OS << "OPC_EmitInteger"; break;
547 case Matcher::EmitStringInteger: OS << "OPC_EmitStringInteger"; break;
548 case Matcher::EmitRegister: OS << "OPC_EmitRegister"; break;
549 case Matcher::EmitConvertToTarget: OS << "OPC_EmitConvertToTarget"; break;
550 case Matcher::EmitMergeInputChains: OS << "OPC_EmitMergeInputChains"; break;
551 case Matcher::EmitCopyToReg: OS << "OPC_EmitCopyToReg"; break;
552 case Matcher::EmitNode: OS << "OPC_EmitNode"; break;
553 case Matcher::MorphNodeTo: OS << "OPC_MorphNodeTo"; break;
554 case Matcher::EmitNodeXForm: OS << "OPC_EmitNodeXForm"; break;
555 case Matcher::MarkFlagResults: OS << "OPC_MarkFlagResults"; break;
556 case Matcher::CompleteMatch: OS << "OPC_CompleteMatch"; break;
559 OS.PadToColumn(40) << " = " << Histogram[i] << '\n';
565 void llvm::EmitMatcherTable(const Matcher *TheMatcher, raw_ostream &O) {
566 formatted_raw_ostream OS(O);
568 OS << "// The main instruction selector code.\n";
569 OS << "SDNode *SelectCode(SDNode *N) {\n";
571 MatcherTableEmitter MatcherEmitter;
573 OS << " // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
574 OS << " #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
575 OS << " static const unsigned char MatcherTable[] = {\n";
576 unsigned TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 5, 0, OS);
577 OS << " 0\n }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
579 MatcherEmitter.EmitHistogram(OS);
581 OS << " #undef TARGET_OPCODE\n";
582 OS << " return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
585 // Next up, emit the function for node and pattern predicates:
586 MatcherEmitter.EmitPredicateFunctions(OS);