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"
29 /// ClassifyInt - Classify an integer by size, return '1','2','4','8' if this
30 /// fits in 1, 2, 4, or 8 sign extended bytes.
31 static char ClassifyInt(int64_t Val) {
32 if (Val == int8_t(Val)) return '1';
33 if (Val == int16_t(Val)) return '2';
34 if (Val == int32_t(Val)) return '4';
38 /// EmitInt - Emit the specified integer, returning the number of bytes emitted.
39 static unsigned EmitInt(int64_t Val, formatted_raw_ostream &OS) {
40 unsigned BytesEmitted = 1;
41 OS << (int)(unsigned char)Val << ", ";
42 if (Val == int8_t(Val)) {
47 OS << (int)(unsigned char)(Val >> 8) << ", ";
50 if (Val != int16_t(Val)) {
51 OS << (int)(unsigned char)(Val >> 16) << ", "
52 << (int)(unsigned char)(Val >> 24) << ", ";
55 if (Val != int32_t(Val)) {
56 OS << (int)(unsigned char)(Val >> 32) << ", "
57 << (int)(unsigned char)(Val >> 40) << ", "
58 << (int)(unsigned char)(Val >> 48) << ", "
59 << (int)(unsigned char)(Val >> 56) << ", ";
64 OS.PadToColumn(CommentIndent) << "// " << Val << " aka 0x";
65 OS.write_hex(Val) << '\n';
70 class MatcherTableEmitter {
71 StringMap<unsigned> NodePredicateMap, PatternPredicateMap;
72 std::vector<std::string> NodePredicates, PatternPredicates;
74 DenseMap<const ComplexPattern*, unsigned> ComplexPatternMap;
75 std::vector<const ComplexPattern*> ComplexPatterns;
78 DenseMap<Record*, unsigned> NodeXFormMap;
79 std::vector<const Record*> NodeXForms;
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 unsigned EmitMatcher(const MatcherNode *N, unsigned Indent,
90 formatted_raw_ostream &OS);
92 unsigned getNodePredicate(StringRef PredName) {
93 unsigned &Entry = NodePredicateMap[PredName];
95 NodePredicates.push_back(PredName.str());
96 Entry = NodePredicates.size();
100 unsigned getPatternPredicate(StringRef PredName) {
101 unsigned &Entry = PatternPredicateMap[PredName];
103 PatternPredicates.push_back(PredName.str());
104 Entry = PatternPredicates.size();
109 unsigned getComplexPat(const ComplexPattern &P) {
110 unsigned &Entry = ComplexPatternMap[&P];
112 ComplexPatterns.push_back(&P);
113 Entry = ComplexPatterns.size();
118 unsigned getNodeXFormID(Record *Rec) {
119 unsigned &Entry = NodeXFormMap[Rec];
121 NodeXForms.push_back(Rec);
122 Entry = NodeXForms.size();
128 } // end anonymous namespace.
130 /// EmitMatcherOpcodes - Emit bytes for the specified matcher and return
131 /// the number of bytes emitted.
132 unsigned MatcherTableEmitter::
133 EmitMatcher(const MatcherNode *N, unsigned Indent, formatted_raw_ostream &OS) {
134 OS.PadToColumn(Indent*2);
136 switch (N->getKind()) {
137 case MatcherNode::Push: assert(0 && "Should be handled by caller");
138 case MatcherNode::RecordNode:
139 OS << "OPC_RecordNode,";
140 OS.PadToColumn(CommentIndent) << "// "
141 << cast<RecordMatcherNode>(N)->getWhatFor() << '\n';
144 case MatcherNode::RecordMemRef:
145 OS << "OPC_RecordMemRef,\n";
148 case MatcherNode::CaptureFlagInput:
149 OS << "OPC_CaptureFlagInput,\n";
152 case MatcherNode::MoveChild:
153 OS << "OPC_MoveChild, "
154 << cast<MoveChildMatcherNode>(N)->getChildNo() << ",\n";
157 case MatcherNode::MoveParent:
158 OS << "OPC_MoveParent,\n";
161 case MatcherNode::CheckSame:
162 OS << "OPC_CheckSame, "
163 << cast<CheckSameMatcherNode>(N)->getMatchNumber() << ",\n";
166 case MatcherNode::CheckPatternPredicate: {
167 StringRef Pred = cast<CheckPatternPredicateMatcherNode>(N)->getPredicate();
168 OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
169 OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
172 case MatcherNode::CheckPredicate: {
173 StringRef Pred = cast<CheckPredicateMatcherNode>(N)->getPredicateName();
174 OS << "OPC_CheckPredicate, " << getNodePredicate(Pred) << ',';
175 OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
179 case MatcherNode::CheckOpcode:
180 OS << "OPC_CheckOpcode, "
181 << cast<CheckOpcodeMatcherNode>(N)->getOpcodeName() << ",\n";
184 case MatcherNode::CheckMultiOpcode: {
185 const CheckMultiOpcodeMatcherNode *CMO=cast<CheckMultiOpcodeMatcherNode>(N);
186 OS << "OPC_CheckMultiOpcode, " << CMO->getNumOpcodeNames() << ", ";
187 for (unsigned i = 0, e = CMO->getNumOpcodeNames(); i != e; ++i)
188 OS << CMO->getOpcodeName(i) << ", ";
190 return 2 + CMO->getNumOpcodeNames();
193 case MatcherNode::CheckType:
194 OS << "OPC_CheckType, "
195 << getEnumName(cast<CheckTypeMatcherNode>(N)->getType()) << ",\n";
198 case MatcherNode::CheckInteger: {
199 int64_t Val = cast<CheckIntegerMatcherNode>(N)->getValue();
200 OS << "OPC_CheckInteger" << ClassifyInt(Val) << ", ";
201 return EmitInt(Val, OS)+1;
203 case MatcherNode::CheckCondCode:
204 OS << "OPC_CheckCondCode, ISD::"
205 << cast<CheckCondCodeMatcherNode>(N)->getCondCodeName() << ",\n";
208 case MatcherNode::CheckValueType:
209 OS << "OPC_CheckValueType, MVT::"
210 << cast<CheckValueTypeMatcherNode>(N)->getTypeName() << ",\n";
213 case MatcherNode::CheckComplexPat: {
214 const ComplexPattern &Pattern =
215 cast<CheckComplexPatMatcherNode>(N)->getPattern();
216 OS << "OPC_CheckComplexPat, " << getComplexPat(Pattern) << ',';
217 OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
218 OS << ": " << Pattern.getNumOperands() << " operands";
219 if (Pattern.hasProperty(SDNPHasChain))
220 OS << " + chain result and input";
225 case MatcherNode::CheckAndImm: {
226 int64_t Val = cast<CheckAndImmMatcherNode>(N)->getValue();
227 OS << "OPC_CheckAndImm" << ClassifyInt(Val) << ", ";
228 return EmitInt(Val, OS)+1;
231 case MatcherNode::CheckOrImm: {
232 int64_t Val = cast<CheckOrImmMatcherNode>(N)->getValue();
233 OS << "OPC_CheckOrImm" << ClassifyInt(Val) << ", ";
234 return EmitInt(Val, OS)+1;
236 case MatcherNode::CheckFoldableChainNode:
237 OS << "OPC_CheckFoldableChainNode,\n";
239 case MatcherNode::CheckChainCompatible:
240 OS << "OPC_CheckChainCompatible, "
241 << cast<CheckChainCompatibleMatcherNode>(N)->getPreviousOp() << ",\n";
244 case MatcherNode::EmitInteger: {
245 int64_t Val = cast<EmitIntegerMatcherNode>(N)->getValue();
246 OS << "OPC_EmitInteger" << ClassifyInt(Val) << ", "
247 << getEnumName(cast<EmitIntegerMatcherNode>(N)->getVT()) << ", ";
248 return EmitInt(Val, OS)+2;
250 case MatcherNode::EmitStringInteger: {
251 const std::string &Val = cast<EmitStringIntegerMatcherNode>(N)->getValue();
252 // These should always fit into one byte.
253 OS << "OPC_EmitInteger1, "
254 << getEnumName(cast<EmitStringIntegerMatcherNode>(N)->getVT()) << ", "
259 case MatcherNode::EmitRegister:
260 OS << "OPC_EmitRegister, "
261 << getEnumName(cast<EmitRegisterMatcherNode>(N)->getVT()) << ", ";
262 if (Record *R = cast<EmitRegisterMatcherNode>(N)->getReg())
263 OS << getQualifiedName(R) << ",\n";
265 OS << "0 /*zero_reg*/,\n";
268 case MatcherNode::EmitConvertToTarget:
269 OS << "OPC_EmitConvertToTarget, "
270 << cast<EmitConvertToTargetMatcherNode>(N)->getSlot() << ",\n";
273 case MatcherNode::EmitMergeInputChains: {
274 const EmitMergeInputChainsMatcherNode *MN =
275 cast<EmitMergeInputChainsMatcherNode>(N);
276 OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
277 for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
278 OS << MN->getNode(i) << ", ";
280 return 2+MN->getNumNodes();
282 case MatcherNode::EmitCopyToReg:
283 OS << "OPC_EmitCopyToReg, "
284 << cast<EmitCopyToRegMatcherNode>(N)->getSrcSlot() << ", "
285 << getQualifiedName(cast<EmitCopyToRegMatcherNode>(N)->getDestPhysReg())
288 case MatcherNode::EmitNodeXForm: {
289 const EmitNodeXFormMatcherNode *XF = cast<EmitNodeXFormMatcherNode>(N);
290 OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
291 << XF->getSlot() << ',';
292 OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName()<<'\n';
296 case MatcherNode::EmitNode: {
297 const EmitNodeMatcherNode *EN = cast<EmitNodeMatcherNode>(N);
298 OS << "OPC_EmitNode, TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
300 if (EN->hasChain()) OS << "|OPFL_Chain";
301 if (EN->hasFlag()) OS << "|OPFL_Flag";
302 if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
303 if (EN->getNumFixedArityOperands() != -1)
304 OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
307 OS.PadToColumn(Indent*2+4) << EN->getNumVTs() << "/*#VTs*/, ";
308 for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
309 OS << getEnumName(EN->getVT(i)) << ", ";
311 OS << EN->getNumOperands() << "/*#Ops*/, ";
312 for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
313 OS << EN->getOperand(i) << ", ";
315 return 6+EN->getNumVTs()+EN->getNumOperands();
317 case MatcherNode::CompleteMatch: {
318 const CompleteMatchMatcherNode *CM = cast<CompleteMatchMatcherNode>(N);
319 OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
320 for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
321 OS << CM->getResult(i) << ", ";
323 OS.PadToColumn(Indent*2) << "// Src: "
324 << *CM->getPattern().getSrcPattern() << '\n';
325 OS.PadToColumn(Indent*2) << "// Dst: "
326 << *CM->getPattern().getDstPattern() << '\n';
327 return 2+CM->getNumResults();
330 assert(0 && "Unreachable");
334 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
335 unsigned MatcherTableEmitter::
336 EmitMatcherList(const MatcherNode *N, unsigned Indent, unsigned CurrentIdx,
337 formatted_raw_ostream &OS) {
340 // Push is a special case since it is binary.
341 if (const PushMatcherNode *PMN = dyn_cast<PushMatcherNode>(N)) {
342 // We need to encode the child and the offset of the failure code before
343 // emitting either of them. Handle this by buffering the output into a
344 // string while we get the size.
345 SmallString<128> TmpBuf;
348 raw_svector_ostream OS(TmpBuf);
349 formatted_raw_ostream FOS(OS);
350 NextSize = EmitMatcherList(cast<PushMatcherNode>(N)->getNext(),
351 Indent+1, CurrentIdx+2, FOS);
354 if (NextSize > 255) {
356 "Tblgen internal error: can't handle predicate this complex yet\n";
360 OS << "/*" << CurrentIdx << "*/";
361 OS.PadToColumn(Indent*2);
362 OS << "OPC_Push, " << NextSize << ",\n";
366 CurrentIdx += 2+NextSize;
367 N = PMN->getFailure();
371 OS << "/*" << CurrentIdx << "*/";
372 unsigned MatcherSize = EmitMatcher(N, Indent, OS);
374 CurrentIdx += MatcherSize;
376 // If there are other nodes in this list, iterate to them, otherwise we're
383 void MatcherTableEmitter::EmitPredicateFunctions(formatted_raw_ostream &OS) {
384 // FIXME: Don't build off the DAGISelEmitter's predicates, emit them directly
385 // here into the case stmts.
387 // Emit pattern predicates.
388 OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
389 OS << " switch (PredNo) {\n";
390 OS << " default: assert(0 && \"Invalid predicate in table?\");\n";
391 for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
392 OS << " case " << i << ": return " << PatternPredicates[i] << ";\n";
396 // Emit Node predicates.
397 OS << "bool CheckNodePredicate(SDNode *N, unsigned PredNo) const {\n";
398 OS << " switch (PredNo) {\n";
399 OS << " default: assert(0 && \"Invalid predicate in table?\");\n";
400 for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i)
401 OS << " case " << i << ": return " << NodePredicates[i] << "(N);\n";
405 // Emit CompletePattern matchers.
406 // FIXME: This should be const.
407 OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
408 OS << " unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
409 OS << " switch (PatternNo) {\n";
410 OS << " default: assert(0 && \"Invalid pattern # in table?\");\n";
411 for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
412 const ComplexPattern &P = *ComplexPatterns[i];
413 unsigned NumOps = P.getNumOperands();
415 if (P.hasProperty(SDNPHasChain))
416 ++NumOps; // Get the chained node too.
418 OS << " case " << i << ":\n";
419 OS << " Result.resize(Result.size()+" << NumOps << ");\n";
420 OS << " return " << P.getSelectFunc();
422 // FIXME: Temporary hack until old isel dies.
423 if (P.hasProperty(SDNPHasChain))
427 for (unsigned i = 0; i != NumOps; ++i)
428 OS << ", Result[Result.size()-" << (NumOps-i) << ']';
434 // Emit SDNodeXForm handlers.
435 // FIXME: This should be const.
436 OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
437 OS << " switch (XFormNo) {\n";
438 OS << " default: assert(0 && \"Invalid xform # in table?\");\n";
440 // FIXME: The node xform could take SDValue's instead of SDNode*'s.
441 for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i)
442 OS << " case " << i << ": return Transform_" << NodeXForms[i]->getName()
443 << "(V.getNode());\n";
449 void llvm::EmitMatcherTable(const MatcherNode *Matcher, raw_ostream &O) {
450 formatted_raw_ostream OS(O);
452 OS << "// The main instruction selector code.\n";
453 OS << "SDNode *SelectCode2(SDNode *N) {\n";
455 MatcherTableEmitter MatcherEmitter;
457 OS << " // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
458 OS << " #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
459 OS << " static const unsigned char MatcherTable[] = {\n";
460 unsigned TotalSize = MatcherEmitter.EmitMatcherList(Matcher, 5, 0, OS);
461 OS << " 0\n }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
462 OS << " #undef TARGET_OPCODE\n";
463 OS << " return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
466 // Next up, emit the function for node and pattern predicates:
467 MatcherEmitter.EmitPredicateFunctions(OS);