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 MatcherNode *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 MatcherNode *N, unsigned Indent,
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 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
134 static unsigned EmitVBRValue(unsigned Val, raw_ostream &OS) {
140 unsigned InVal = Val;
141 unsigned NumBytes = 0;
143 OS << (Val&127) << "|128,";
147 OS << Val << "/*" << InVal << "*/, ";
151 /// EmitMatcherOpcodes - Emit bytes for the specified matcher and return
152 /// the number of bytes emitted.
153 unsigned MatcherTableEmitter::
154 EmitMatcher(const MatcherNode *N, unsigned Indent, formatted_raw_ostream &OS) {
155 OS.PadToColumn(Indent*2);
157 switch (N->getKind()) {
158 case MatcherNode::Push: assert(0 && "Should be handled by caller");
159 case MatcherNode::RecordNode:
160 OS << "OPC_RecordNode,";
161 OS.PadToColumn(CommentIndent) << "// "
162 << cast<RecordMatcherNode>(N)->getWhatFor() << '\n';
165 case MatcherNode::RecordChild:
166 OS << "OPC_RecordChild" << cast<RecordChildMatcherNode>(N)->getChildNo()
168 OS.PadToColumn(CommentIndent) << "// "
169 << cast<RecordChildMatcherNode>(N)->getWhatFor() << '\n';
172 case MatcherNode::RecordMemRef:
173 OS << "OPC_RecordMemRef,\n";
176 case MatcherNode::CaptureFlagInput:
177 OS << "OPC_CaptureFlagInput,\n";
180 case MatcherNode::MoveChild:
181 OS << "OPC_MoveChild, "
182 << cast<MoveChildMatcherNode>(N)->getChildNo() << ",\n";
185 case MatcherNode::MoveParent:
186 OS << "OPC_MoveParent,\n";
189 case MatcherNode::CheckSame:
190 OS << "OPC_CheckSame, "
191 << cast<CheckSameMatcherNode>(N)->getMatchNumber() << ",\n";
194 case MatcherNode::CheckPatternPredicate: {
195 StringRef Pred = cast<CheckPatternPredicateMatcherNode>(N)->getPredicate();
196 OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
197 OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
200 case MatcherNode::CheckPredicate: {
201 StringRef Pred = cast<CheckPredicateMatcherNode>(N)->getPredicateName();
202 OS << "OPC_CheckPredicate, " << getNodePredicate(Pred) << ',';
203 OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
207 case MatcherNode::CheckOpcode:
208 OS << "OPC_CheckOpcode, "
209 << cast<CheckOpcodeMatcherNode>(N)->getOpcodeName() << ",\n";
212 case MatcherNode::CheckMultiOpcode: {
213 const CheckMultiOpcodeMatcherNode *CMO=cast<CheckMultiOpcodeMatcherNode>(N);
214 OS << "OPC_CheckMultiOpcode, " << CMO->getNumOpcodeNames() << ", ";
215 for (unsigned i = 0, e = CMO->getNumOpcodeNames(); i != e; ++i)
216 OS << CMO->getOpcodeName(i) << ", ";
218 return 2 + CMO->getNumOpcodeNames();
221 case MatcherNode::CheckType:
222 OS << "OPC_CheckType, "
223 << getEnumName(cast<CheckTypeMatcherNode>(N)->getType()) << ",\n";
226 case MatcherNode::CheckInteger: {
227 int64_t Val = cast<CheckIntegerMatcherNode>(N)->getValue();
228 OS << "OPC_CheckInteger" << ClassifyInt(Val) << ", ";
229 return EmitInt(Val, OS)+1;
231 case MatcherNode::CheckCondCode:
232 OS << "OPC_CheckCondCode, ISD::"
233 << cast<CheckCondCodeMatcherNode>(N)->getCondCodeName() << ",\n";
236 case MatcherNode::CheckValueType:
237 OS << "OPC_CheckValueType, MVT::"
238 << cast<CheckValueTypeMatcherNode>(N)->getTypeName() << ",\n";
241 case MatcherNode::CheckComplexPat: {
242 const ComplexPattern &Pattern =
243 cast<CheckComplexPatMatcherNode>(N)->getPattern();
244 OS << "OPC_CheckComplexPat, " << getComplexPat(Pattern) << ',';
245 OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
246 OS << ": " << Pattern.getNumOperands() << " operands";
247 if (Pattern.hasProperty(SDNPHasChain))
248 OS << " + chain result and input";
253 case MatcherNode::CheckAndImm: {
254 int64_t Val = cast<CheckAndImmMatcherNode>(N)->getValue();
255 OS << "OPC_CheckAndImm" << ClassifyInt(Val) << ", ";
256 return EmitInt(Val, OS)+1;
259 case MatcherNode::CheckOrImm: {
260 int64_t Val = cast<CheckOrImmMatcherNode>(N)->getValue();
261 OS << "OPC_CheckOrImm" << ClassifyInt(Val) << ", ";
262 return EmitInt(Val, OS)+1;
264 case MatcherNode::CheckFoldableChainNode:
265 OS << "OPC_CheckFoldableChainNode,\n";
267 case MatcherNode::CheckChainCompatible:
268 OS << "OPC_CheckChainCompatible, "
269 << cast<CheckChainCompatibleMatcherNode>(N)->getPreviousOp() << ",\n";
272 case MatcherNode::EmitInteger: {
273 int64_t Val = cast<EmitIntegerMatcherNode>(N)->getValue();
274 OS << "OPC_EmitInteger" << ClassifyInt(Val) << ", "
275 << getEnumName(cast<EmitIntegerMatcherNode>(N)->getVT()) << ", ";
276 return EmitInt(Val, OS)+2;
278 case MatcherNode::EmitStringInteger: {
279 const std::string &Val = cast<EmitStringIntegerMatcherNode>(N)->getValue();
280 // These should always fit into one byte.
281 OS << "OPC_EmitInteger1, "
282 << getEnumName(cast<EmitStringIntegerMatcherNode>(N)->getVT()) << ", "
287 case MatcherNode::EmitRegister:
288 OS << "OPC_EmitRegister, "
289 << getEnumName(cast<EmitRegisterMatcherNode>(N)->getVT()) << ", ";
290 if (Record *R = cast<EmitRegisterMatcherNode>(N)->getReg())
291 OS << getQualifiedName(R) << ",\n";
293 OS << "0 /*zero_reg*/,\n";
296 case MatcherNode::EmitConvertToTarget:
297 OS << "OPC_EmitConvertToTarget, "
298 << cast<EmitConvertToTargetMatcherNode>(N)->getSlot() << ",\n";
301 case MatcherNode::EmitMergeInputChains: {
302 const EmitMergeInputChainsMatcherNode *MN =
303 cast<EmitMergeInputChainsMatcherNode>(N);
304 OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
305 for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
306 OS << MN->getNode(i) << ", ";
308 return 2+MN->getNumNodes();
310 case MatcherNode::EmitCopyToReg:
311 OS << "OPC_EmitCopyToReg, "
312 << cast<EmitCopyToRegMatcherNode>(N)->getSrcSlot() << ", "
313 << getQualifiedName(cast<EmitCopyToRegMatcherNode>(N)->getDestPhysReg())
316 case MatcherNode::EmitNodeXForm: {
317 const EmitNodeXFormMatcherNode *XF = cast<EmitNodeXFormMatcherNode>(N);
318 OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
319 << XF->getSlot() << ',';
320 OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName()<<'\n';
324 case MatcherNode::EmitNode: {
325 const EmitNodeMatcherNode *EN = cast<EmitNodeMatcherNode>(N);
326 OS << "OPC_EmitNode, TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
328 if (EN->hasChain()) OS << "|OPFL_Chain";
329 if (EN->hasFlag()) OS << "|OPFL_Flag";
330 if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
331 if (EN->getNumFixedArityOperands() != -1)
332 OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
335 OS.PadToColumn(Indent*2+4) << EN->getNumVTs() << "/*#VTs*/, ";
336 for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
337 OS << getEnumName(EN->getVT(i)) << ", ";
339 OS << EN->getNumOperands() << "/*#Ops*/, ";
340 unsigned NumOperandBytes = 0;
341 for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i) {
342 // We emit the operand numbers in VBR encoded format, in case the number
343 // is too large to represent with a byte.
344 NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
347 return 6+EN->getNumVTs()+NumOperandBytes;
349 case MatcherNode::MarkFlagResults: {
350 const MarkFlagResultsMatcherNode *CFR = cast<MarkFlagResultsMatcherNode>(N);
351 OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", ";
352 unsigned NumOperandBytes = 0;
353 for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i)
354 NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS);
356 return 2+NumOperandBytes;
358 case MatcherNode::CompleteMatch: {
359 const CompleteMatchMatcherNode *CM = cast<CompleteMatchMatcherNode>(N);
360 OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
361 unsigned NumResultBytes = 0;
362 for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
363 NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
365 OS.PadToColumn(Indent*2) << "// Src: "
366 << *CM->getPattern().getSrcPattern() << '\n';
367 OS.PadToColumn(Indent*2) << "// Dst: "
368 << *CM->getPattern().getDstPattern() << '\n';
369 return 2 + NumResultBytes;
372 assert(0 && "Unreachable");
376 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
377 unsigned MatcherTableEmitter::
378 EmitMatcherList(const MatcherNode *N, unsigned Indent, unsigned CurrentIdx,
379 formatted_raw_ostream &OS) {
382 if (unsigned(N->getKind()) >= Histogram.size())
383 Histogram.resize(N->getKind()+1);
384 Histogram[N->getKind()]++;
386 // Push is a special case since it is binary.
387 if (const PushMatcherNode *PMN = dyn_cast<PushMatcherNode>(N)) {
388 // We need to encode the child and the offset of the failure code before
389 // emitting either of them. Handle this by buffering the output into a
390 // string while we get the size.
391 SmallString<128> TmpBuf;
394 raw_svector_ostream OS(TmpBuf);
395 formatted_raw_ostream FOS(OS);
396 NextSize = EmitMatcherList(cast<PushMatcherNode>(N)->getNext(),
397 Indent+1, CurrentIdx+2, FOS);
400 // In the unlikely event that we have something too big to emit with a
401 // one byte offset, regenerate it with a two-byte one.
402 if (NextSize > 255) {
404 raw_svector_ostream OS(TmpBuf);
405 formatted_raw_ostream FOS(OS);
406 NextSize = EmitMatcherList(cast<PushMatcherNode>(N)->getNext(),
407 Indent+1, CurrentIdx+3, FOS);
408 if (NextSize > 65535) {
410 "Tblgen internal error: can't handle pattern this complex yet\n";
415 OS << "/*" << CurrentIdx << "*/";
416 OS.PadToColumn(Indent*2);
419 OS << "OPC_Push, " << NextSize << ",\n";
421 OS << "OPC_Push2, " << (NextSize&255) << ", " << (NextSize>>8) << ",\n";
425 CurrentIdx += 2+NextSize;
426 N = PMN->getFailure();
430 OS << "/*" << CurrentIdx << "*/";
431 unsigned MatcherSize = EmitMatcher(N, Indent, OS);
433 CurrentIdx += MatcherSize;
435 // If there are other nodes in this list, iterate to them, otherwise we're
442 void MatcherTableEmitter::EmitPredicateFunctions(formatted_raw_ostream &OS) {
443 // FIXME: Don't build off the DAGISelEmitter's predicates, emit them directly
444 // here into the case stmts.
446 // Emit pattern predicates.
447 OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
448 OS << " switch (PredNo) {\n";
449 OS << " default: assert(0 && \"Invalid predicate in table?\");\n";
450 for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
451 OS << " case " << i << ": return " << PatternPredicates[i] << ";\n";
455 // Emit Node predicates.
456 OS << "bool CheckNodePredicate(SDNode *N, unsigned PredNo) const {\n";
457 OS << " switch (PredNo) {\n";
458 OS << " default: assert(0 && \"Invalid predicate in table?\");\n";
459 for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i)
460 OS << " case " << i << ": return " << NodePredicates[i] << "(N);\n";
464 // Emit CompletePattern matchers.
465 // FIXME: This should be const.
466 OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
467 OS << " unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
468 OS << " switch (PatternNo) {\n";
469 OS << " default: assert(0 && \"Invalid pattern # in table?\");\n";
470 for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
471 const ComplexPattern &P = *ComplexPatterns[i];
472 unsigned NumOps = P.getNumOperands();
474 if (P.hasProperty(SDNPHasChain))
475 ++NumOps; // Get the chained node too.
477 OS << " case " << i << ":\n";
478 OS << " Result.resize(Result.size()+" << NumOps << ");\n";
479 OS << " return " << P.getSelectFunc();
481 // FIXME: Temporary hack until old isel dies.
482 if (P.hasProperty(SDNPHasChain))
486 for (unsigned i = 0; i != NumOps; ++i)
487 OS << ", Result[Result.size()-" << (NumOps-i) << ']';
493 // Emit SDNodeXForm handlers.
494 // FIXME: This should be const.
495 OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
496 OS << " switch (XFormNo) {\n";
497 OS << " default: assert(0 && \"Invalid xform # in table?\");\n";
499 // FIXME: The node xform could take SDValue's instead of SDNode*'s.
500 for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i)
501 OS << " case " << i << ": return Transform_" << NodeXForms[i]->getName()
502 << "(V.getNode());\n";
507 void MatcherTableEmitter::EmitHistogram(formatted_raw_ostream &OS) {
508 OS << " // Opcode Histogram:\n";
509 for (unsigned i = 0, e = Histogram.size(); i != e; ++i) {
511 switch ((MatcherNode::KindTy)i) {
512 case MatcherNode::Push: OS << "OPC_Push"; break;
513 case MatcherNode::RecordNode: OS << "OPC_RecordNode"; break;
514 case MatcherNode::RecordChild: OS << "OPC_RecordChild"; break;
515 case MatcherNode::RecordMemRef: OS << "OPC_RecordMemRef"; break;
516 case MatcherNode::CaptureFlagInput: OS << "OPC_CaptureFlagInput"; break;
517 case MatcherNode::MoveChild: OS << "OPC_MoveChild"; break;
518 case MatcherNode::MoveParent: OS << "OPC_MoveParent"; break;
519 case MatcherNode::CheckSame: OS << "OPC_CheckSame"; break;
520 case MatcherNode::CheckPatternPredicate:
521 OS << "OPC_CheckPatternPredicate"; break;
522 case MatcherNode::CheckPredicate: OS << "OPC_CheckPredicate"; break;
523 case MatcherNode::CheckOpcode: OS << "OPC_CheckOpcode"; break;
524 case MatcherNode::CheckMultiOpcode: OS << "OPC_CheckMultiOpcode"; break;
525 case MatcherNode::CheckType: OS << "OPC_CheckType"; break;
526 case MatcherNode::CheckInteger: OS << "OPC_CheckInteger"; break;
527 case MatcherNode::CheckCondCode: OS << "OPC_CheckCondCode"; break;
528 case MatcherNode::CheckValueType: OS << "OPC_CheckValueType"; break;
529 case MatcherNode::CheckComplexPat: OS << "OPC_CheckComplexPat"; break;
530 case MatcherNode::CheckAndImm: OS << "OPC_CheckAndImm"; break;
531 case MatcherNode::CheckOrImm: OS << "OPC_CheckOrImm"; break;
532 case MatcherNode::CheckFoldableChainNode:
533 OS << "OPC_CheckFoldableChainNode"; break;
534 case MatcherNode::CheckChainCompatible:
535 OS << "OPC_CheckChainCompatible"; break;
536 case MatcherNode::EmitInteger: OS << "OPC_EmitInteger"; break;
537 case MatcherNode::EmitStringInteger: OS << "OPC_EmitStringInteger"; break;
538 case MatcherNode::EmitRegister: OS << "OPC_EmitRegister"; break;
539 case MatcherNode::EmitConvertToTarget:
540 OS << "OPC_EmitConvertToTarget"; break;
541 case MatcherNode::EmitMergeInputChains:
542 OS << "OPC_EmitMergeInputChains"; break;
543 case MatcherNode::EmitCopyToReg: OS << "OPC_EmitCopyToReg"; break;
544 case MatcherNode::EmitNode: OS << "OPC_EmitNode"; break;
545 case MatcherNode::EmitNodeXForm: OS << "OPC_EmitNodeXForm"; break;
546 case MatcherNode::MarkFlagResults: OS << "OPC_MarkFlagResults"; break;
547 case MatcherNode::CompleteMatch: OS << "OPC_CompleteMatch"; break;
550 OS.PadToColumn(40) << " = " << Histogram[i] << '\n';
556 void llvm::EmitMatcherTable(const MatcherNode *Matcher, raw_ostream &O) {
557 formatted_raw_ostream OS(O);
559 OS << "// The main instruction selector code.\n";
560 OS << "SDNode *SelectCode(SDNode *N) {\n";
562 MatcherTableEmitter MatcherEmitter;
564 OS << " // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
565 OS << " #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
566 OS << " static const unsigned char MatcherTable[] = {\n";
567 unsigned TotalSize = MatcherEmitter.EmitMatcherList(Matcher, 5, 0, OS);
568 OS << " 0\n }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
570 MatcherEmitter.EmitHistogram(OS);
572 OS << " #undef TARGET_OPCODE\n";
573 OS << " return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
576 // Next up, emit the function for node and pattern predicates:
577 MatcherEmitter.EmitPredicateFunctions(OS);