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"
27 /// ClassifyInt - Classify an integer by size, return '1','2','4','8' if this
28 /// fits in 1, 2, 4, or 8 sign extended bytes.
29 static char ClassifyInt(int64_t Val) {
30 if (Val == int8_t(Val)) return '1';
31 if (Val == int16_t(Val)) return '2';
32 if (Val == int32_t(Val)) return '4';
36 /// EmitInt - Emit the specified integer, returning the number of bytes emitted.
37 static unsigned EmitInt(int64_t Val, formatted_raw_ostream &OS) {
38 unsigned BytesEmitted = 1;
39 OS << (int)(unsigned char)Val << ", ";
40 if (Val == int8_t(Val)) {
45 OS << (int)(unsigned char)(Val >> 8) << ", ";
48 if (Val != int16_t(Val)) {
49 OS << (int)(unsigned char)(Val >> 16) << ", "
50 << (int)(unsigned char)(Val >> 24) << ", ";
53 if (Val != int32_t(Val)) {
54 OS << (int)(unsigned char)(Val >> 32) << ", "
55 << (int)(unsigned char)(Val >> 40) << ", "
56 << (int)(unsigned char)(Val >> 48) << ", "
57 << (int)(unsigned char)(Val >> 56) << ", ";
62 OS.PadToColumn(CommentIndent) << "// " << Val << " aka 0x";
63 OS.write_hex(Val) << '\n';
68 class MatcherTableEmitter {
69 StringMap<unsigned> NodePredicateMap, PatternPredicateMap;
70 std::vector<std::string> NodePredicates, PatternPredicates;
72 DenseMap<const ComplexPattern*, unsigned> ComplexPatternMap;
73 std::vector<const ComplexPattern*> ComplexPatterns;
76 DenseMap<Record*, unsigned> NodeXFormMap;
77 std::vector<const Record*> NodeXForms;
79 // Per opcode frequence count.
80 std::vector<unsigned> Histogram;
82 MatcherTableEmitter() {}
84 unsigned EmitMatcherList(const Matcher *N, unsigned Indent,
85 unsigned StartIdx, formatted_raw_ostream &OS);
87 void EmitPredicateFunctions(formatted_raw_ostream &OS);
89 void EmitHistogram(formatted_raw_ostream &OS);
91 unsigned EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
92 formatted_raw_ostream &OS);
94 unsigned getNodePredicate(StringRef PredName) {
95 unsigned &Entry = NodePredicateMap[PredName];
97 NodePredicates.push_back(PredName.str());
98 Entry = NodePredicates.size();
102 unsigned getPatternPredicate(StringRef PredName) {
103 unsigned &Entry = PatternPredicateMap[PredName];
105 PatternPredicates.push_back(PredName.str());
106 Entry = PatternPredicates.size();
111 unsigned getComplexPat(const ComplexPattern &P) {
112 unsigned &Entry = ComplexPatternMap[&P];
114 ComplexPatterns.push_back(&P);
115 Entry = ComplexPatterns.size();
120 unsigned getNodeXFormID(Record *Rec) {
121 unsigned &Entry = NodeXFormMap[Rec];
123 NodeXForms.push_back(Rec);
124 Entry = NodeXForms.size();
130 } // end anonymous namespace.
132 static unsigned GetVBRSize(unsigned Val) {
133 if (Val <= 127) return 1;
135 unsigned NumBytes = 0;
143 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
145 static unsigned EmitVBRValue(unsigned Val, raw_ostream &OS) {
151 unsigned InVal = Val;
152 unsigned NumBytes = 0;
154 OS << (Val&127) << "|128,";
158 OS << Val << "/*" << InVal << "*/, ";
162 /// EmitMatcherOpcodes - Emit bytes for the specified matcher and return
163 /// the number of bytes emitted.
164 unsigned MatcherTableEmitter::
165 EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
166 formatted_raw_ostream &OS) {
167 OS.PadToColumn(Indent*2);
169 switch (N->getKind()) {
170 case Matcher::Scope: {
171 const ScopeMatcher *SM = cast<ScopeMatcher>(N);
172 assert(SM->getNext() == 0 && "Shouldn't have next after scope");
174 unsigned StartIdx = CurrentIdx;
176 // Emit all of the children.
177 for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
182 OS << "/*" << CurrentIdx << "*/";
183 OS.PadToColumn(Indent*2) << "/*Scope*/ ";
186 // We need to encode the child and the offset of the failure code before
187 // emitting either of them. Handle this by buffering the output into a
188 // string while we get the size. Unfortunately, the offset of the
189 // children depends on the VBR size of the child, so for large children we
190 // have to iterate a bit.
191 SmallString<128> TmpBuf;
192 unsigned ChildSize = 0;
193 unsigned VBRSize = 0;
195 VBRSize = GetVBRSize(ChildSize);
198 raw_svector_ostream OS(TmpBuf);
199 formatted_raw_ostream FOS(OS);
200 ChildSize = EmitMatcherList(cast<ScopeMatcher>(N)->getChild(i),
201 Indent+1, CurrentIdx+VBRSize, FOS);
202 } while (GetVBRSize(ChildSize) != VBRSize);
204 assert(ChildSize != 0 && "Should not have a zero-sized child!");
206 CurrentIdx += EmitVBRValue(ChildSize, OS);
207 OS << '\n' << TmpBuf.str();
208 CurrentIdx += ChildSize;
211 // Emit a zero as a sentinel indicating end of 'Scope'.
212 OS << "/*" << CurrentIdx << "*/";
213 OS.PadToColumn(Indent*2) << "0, /*End of Scope*/\n";
214 return CurrentIdx - StartIdx + 1;
217 case Matcher::RecordNode:
218 OS << "OPC_RecordNode,";
219 OS.PadToColumn(CommentIndent) << "// "
220 << cast<RecordMatcher>(N)->getWhatFor() << '\n';
223 case Matcher::RecordChild:
224 OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo()
226 OS.PadToColumn(CommentIndent) << "// "
227 << cast<RecordChildMatcher>(N)->getWhatFor() << '\n';
230 case Matcher::RecordMemRef:
231 OS << "OPC_RecordMemRef,\n";
234 case Matcher::CaptureFlagInput:
235 OS << "OPC_CaptureFlagInput,\n";
238 case Matcher::MoveChild:
239 OS << "OPC_MoveChild, " << cast<MoveChildMatcher>(N)->getChildNo() << ",\n";
242 case Matcher::MoveParent:
243 OS << "OPC_MoveParent,\n";
246 case Matcher::CheckSame:
247 OS << "OPC_CheckSame, "
248 << cast<CheckSameMatcher>(N)->getMatchNumber() << ",\n";
251 case Matcher::CheckPatternPredicate: {
252 StringRef Pred = cast<CheckPatternPredicateMatcher>(N)->getPredicate();
253 OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
254 OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
257 case Matcher::CheckPredicate: {
258 StringRef Pred = cast<CheckPredicateMatcher>(N)->getPredicateName();
259 OS << "OPC_CheckPredicate, " << getNodePredicate(Pred) << ',';
260 OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
264 case Matcher::CheckOpcode:
265 OS << "OPC_CheckOpcode, "
266 << cast<CheckOpcodeMatcher>(N)->getOpcodeName() << ",\n";
269 case Matcher::CheckMultiOpcode: {
270 const CheckMultiOpcodeMatcher *CMO = cast<CheckMultiOpcodeMatcher>(N);
271 OS << "OPC_CheckMultiOpcode, " << CMO->getNumOpcodeNames() << ", ";
272 for (unsigned i = 0, e = CMO->getNumOpcodeNames(); i != e; ++i)
273 OS << CMO->getOpcodeName(i) << ", ";
275 return 2 + CMO->getNumOpcodeNames();
278 case Matcher::CheckType:
279 OS << "OPC_CheckType, "
280 << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
282 case Matcher::CheckChildType:
283 OS << "OPC_CheckChild"
284 << cast<CheckChildTypeMatcher>(N)->getChildNo() << "Type, "
285 << getEnumName(cast<CheckChildTypeMatcher>(N)->getType()) << ",\n";
288 case Matcher::CheckInteger: {
289 int64_t Val = cast<CheckIntegerMatcher>(N)->getValue();
290 OS << "OPC_CheckInteger" << ClassifyInt(Val) << ", ";
291 return EmitInt(Val, OS)+1;
293 case Matcher::CheckCondCode:
294 OS << "OPC_CheckCondCode, ISD::"
295 << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
298 case Matcher::CheckValueType:
299 OS << "OPC_CheckValueType, MVT::"
300 << cast<CheckValueTypeMatcher>(N)->getTypeName() << ",\n";
303 case Matcher::CheckComplexPat: {
304 const ComplexPattern &Pattern =
305 cast<CheckComplexPatMatcher>(N)->getPattern();
306 OS << "OPC_CheckComplexPat, " << getComplexPat(Pattern) << ',';
307 OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
308 OS << ": " << Pattern.getNumOperands() << " operands";
309 if (Pattern.hasProperty(SDNPHasChain))
310 OS << " + chain result and input";
315 case Matcher::CheckAndImm: {
316 int64_t Val = cast<CheckAndImmMatcher>(N)->getValue();
317 OS << "OPC_CheckAndImm" << ClassifyInt(Val) << ", ";
318 return EmitInt(Val, OS)+1;
321 case Matcher::CheckOrImm: {
322 int64_t Val = cast<CheckOrImmMatcher>(N)->getValue();
323 OS << "OPC_CheckOrImm" << ClassifyInt(Val) << ", ";
324 return EmitInt(Val, OS)+1;
326 case Matcher::CheckFoldableChainNode:
327 OS << "OPC_CheckFoldableChainNode,\n";
329 case Matcher::CheckChainCompatible:
330 OS << "OPC_CheckChainCompatible, "
331 << cast<CheckChainCompatibleMatcher>(N)->getPreviousOp() << ",\n";
334 case Matcher::EmitInteger: {
335 int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
336 OS << "OPC_EmitInteger" << ClassifyInt(Val) << ", "
337 << getEnumName(cast<EmitIntegerMatcher>(N)->getVT()) << ", ";
338 return EmitInt(Val, OS)+2;
340 case Matcher::EmitStringInteger: {
341 const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
342 // These should always fit into one byte.
343 OS << "OPC_EmitInteger1, "
344 << getEnumName(cast<EmitStringIntegerMatcher>(N)->getVT()) << ", "
349 case Matcher::EmitRegister:
350 OS << "OPC_EmitRegister, "
351 << getEnumName(cast<EmitRegisterMatcher>(N)->getVT()) << ", ";
352 if (Record *R = cast<EmitRegisterMatcher>(N)->getReg())
353 OS << getQualifiedName(R) << ",\n";
355 OS << "0 /*zero_reg*/,\n";
358 case Matcher::EmitConvertToTarget:
359 OS << "OPC_EmitConvertToTarget, "
360 << cast<EmitConvertToTargetMatcher>(N)->getSlot() << ",\n";
363 case Matcher::EmitMergeInputChains: {
364 const EmitMergeInputChainsMatcher *MN =
365 cast<EmitMergeInputChainsMatcher>(N);
366 OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
367 for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
368 OS << MN->getNode(i) << ", ";
370 return 2+MN->getNumNodes();
372 case Matcher::EmitCopyToReg:
373 OS << "OPC_EmitCopyToReg, "
374 << cast<EmitCopyToRegMatcher>(N)->getSrcSlot() << ", "
375 << getQualifiedName(cast<EmitCopyToRegMatcher>(N)->getDestPhysReg())
378 case Matcher::EmitNodeXForm: {
379 const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
380 OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
381 << XF->getSlot() << ',';
382 OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName()<<'\n';
386 case Matcher::EmitNode: {
387 const EmitNodeMatcher *EN = cast<EmitNodeMatcher>(N);
388 OS << "OPC_EmitNode, TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
390 if (EN->hasChain()) OS << "|OPFL_Chain";
391 if (EN->hasFlag()) OS << "|OPFL_Flag";
392 if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
393 if (EN->getNumFixedArityOperands() != -1)
394 OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
397 OS.PadToColumn(Indent*2+4) << EN->getNumVTs() << "/*#VTs*/, ";
398 for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
399 OS << getEnumName(EN->getVT(i)) << ", ";
401 OS << EN->getNumOperands() << "/*#Ops*/, ";
402 unsigned NumOperandBytes = 0;
403 for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i) {
404 // We emit the operand numbers in VBR encoded format, in case the number
405 // is too large to represent with a byte.
406 NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
409 return 6+EN->getNumVTs()+NumOperandBytes;
411 case Matcher::MarkFlagResults: {
412 const MarkFlagResultsMatcher *CFR = cast<MarkFlagResultsMatcher>(N);
413 OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", ";
414 unsigned NumOperandBytes = 0;
415 for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i)
416 NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS);
418 return 2+NumOperandBytes;
420 case Matcher::CompleteMatch: {
421 const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
422 OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
423 unsigned NumResultBytes = 0;
424 for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
425 NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
427 OS.PadToColumn(Indent*2) << "// Src: "
428 << *CM->getPattern().getSrcPattern() << '\n';
429 OS.PadToColumn(Indent*2) << "// Dst: "
430 << *CM->getPattern().getDstPattern() << '\n';
431 return 2 + NumResultBytes;
434 assert(0 && "Unreachable");
438 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
439 unsigned MatcherTableEmitter::
440 EmitMatcherList(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
441 formatted_raw_ostream &OS) {
444 if (unsigned(N->getKind()) >= Histogram.size())
445 Histogram.resize(N->getKind()+1);
446 Histogram[N->getKind()]++;
448 OS << "/*" << CurrentIdx << "*/";
449 unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
451 CurrentIdx += MatcherSize;
453 // If there are other nodes in this list, iterate to them, otherwise we're
460 void MatcherTableEmitter::EmitPredicateFunctions(formatted_raw_ostream &OS) {
461 // FIXME: Don't build off the DAGISelEmitter's predicates, emit them directly
462 // here into the case stmts.
464 // Emit pattern predicates.
465 OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
466 OS << " switch (PredNo) {\n";
467 OS << " default: assert(0 && \"Invalid predicate in table?\");\n";
468 for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
469 OS << " case " << i << ": return " << PatternPredicates[i] << ";\n";
473 // Emit Node predicates.
474 OS << "bool CheckNodePredicate(SDNode *N, unsigned PredNo) const {\n";
475 OS << " switch (PredNo) {\n";
476 OS << " default: assert(0 && \"Invalid predicate in table?\");\n";
477 for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i)
478 OS << " case " << i << ": return " << NodePredicates[i] << "(N);\n";
482 // Emit CompletePattern matchers.
483 // FIXME: This should be const.
484 OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
485 OS << " unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
486 OS << " switch (PatternNo) {\n";
487 OS << " default: assert(0 && \"Invalid pattern # in table?\");\n";
488 for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
489 const ComplexPattern &P = *ComplexPatterns[i];
490 unsigned NumOps = P.getNumOperands();
492 if (P.hasProperty(SDNPHasChain))
493 ++NumOps; // Get the chained node too.
495 OS << " case " << i << ":\n";
496 OS << " Result.resize(Result.size()+" << NumOps << ");\n";
497 OS << " return " << P.getSelectFunc();
499 // FIXME: Temporary hack until old isel dies.
500 if (P.hasProperty(SDNPHasChain))
504 for (unsigned i = 0; i != NumOps; ++i)
505 OS << ", Result[Result.size()-" << (NumOps-i) << ']';
511 // Emit SDNodeXForm handlers.
512 // FIXME: This should be const.
513 OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
514 OS << " switch (XFormNo) {\n";
515 OS << " default: assert(0 && \"Invalid xform # in table?\");\n";
517 // FIXME: The node xform could take SDValue's instead of SDNode*'s.
518 for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i)
519 OS << " case " << i << ": return Transform_" << NodeXForms[i]->getName()
520 << "(V.getNode());\n";
525 void MatcherTableEmitter::EmitHistogram(formatted_raw_ostream &OS) {
526 OS << " // Opcode Histogram:\n";
527 for (unsigned i = 0, e = Histogram.size(); i != e; ++i) {
529 switch ((Matcher::KindTy)i) {
530 case Matcher::Scope: OS << "OPC_Scope"; break;
531 case Matcher::RecordNode: OS << "OPC_RecordNode"; break;
532 case Matcher::RecordChild: OS << "OPC_RecordChild"; break;
533 case Matcher::RecordMemRef: OS << "OPC_RecordMemRef"; break;
534 case Matcher::CaptureFlagInput: OS << "OPC_CaptureFlagInput"; break;
535 case Matcher::MoveChild: OS << "OPC_MoveChild"; break;
536 case Matcher::MoveParent: OS << "OPC_MoveParent"; break;
537 case Matcher::CheckSame: OS << "OPC_CheckSame"; break;
538 case Matcher::CheckPatternPredicate:
539 OS << "OPC_CheckPatternPredicate"; break;
540 case Matcher::CheckPredicate: OS << "OPC_CheckPredicate"; break;
541 case Matcher::CheckOpcode: OS << "OPC_CheckOpcode"; break;
542 case Matcher::CheckMultiOpcode: OS << "OPC_CheckMultiOpcode"; break;
543 case Matcher::CheckType: OS << "OPC_CheckType"; break;
544 case Matcher::CheckChildType: OS << "OPC_CheckChildType"; break;
545 case Matcher::CheckInteger: OS << "OPC_CheckInteger"; break;
546 case Matcher::CheckCondCode: OS << "OPC_CheckCondCode"; break;
547 case Matcher::CheckValueType: OS << "OPC_CheckValueType"; break;
548 case Matcher::CheckComplexPat: OS << "OPC_CheckComplexPat"; break;
549 case Matcher::CheckAndImm: OS << "OPC_CheckAndImm"; break;
550 case Matcher::CheckOrImm: OS << "OPC_CheckOrImm"; break;
551 case Matcher::CheckFoldableChainNode:
552 OS << "OPC_CheckFoldableChainNode"; break;
553 case Matcher::CheckChainCompatible: OS << "OPC_CheckChainCompatible"; break;
554 case Matcher::EmitInteger: OS << "OPC_EmitInteger"; break;
555 case Matcher::EmitStringInteger: OS << "OPC_EmitStringInteger"; break;
556 case Matcher::EmitRegister: OS << "OPC_EmitRegister"; break;
557 case Matcher::EmitConvertToTarget: OS << "OPC_EmitConvertToTarget"; break;
558 case Matcher::EmitMergeInputChains: OS << "OPC_EmitMergeInputChains"; break;
559 case Matcher::EmitCopyToReg: OS << "OPC_EmitCopyToReg"; break;
560 case Matcher::EmitNode: OS << "OPC_EmitNode"; break;
561 case Matcher::EmitNodeXForm: OS << "OPC_EmitNodeXForm"; break;
562 case Matcher::MarkFlagResults: OS << "OPC_MarkFlagResults"; break;
563 case Matcher::CompleteMatch: OS << "OPC_CompleteMatch"; break;
566 OS.PadToColumn(40) << " = " << Histogram[i] << '\n';
572 void llvm::EmitMatcherTable(const Matcher *TheMatcher, raw_ostream &O) {
573 formatted_raw_ostream OS(O);
575 OS << "// The main instruction selector code.\n";
576 OS << "SDNode *SelectCode(SDNode *N) {\n";
578 MatcherTableEmitter MatcherEmitter;
580 OS << " // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
581 OS << " #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
582 OS << " static const unsigned char MatcherTable[] = {\n";
583 unsigned TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 5, 0, OS);
584 OS << " 0\n }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
586 MatcherEmitter.EmitHistogram(OS);
588 OS << " #undef TARGET_OPCODE\n";
589 OS << " return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
592 // Next up, emit the function for node and pattern predicates:
593 MatcherEmitter.EmitPredicateFunctions(OS);