1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelEmitter.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
22 //===----------------------------------------------------------------------===//
23 // Helpers for working with extended types.
25 /// FilterVTs - Filter a list of VT's according to a predicate.
28 static std::vector<MVT::ValueType>
29 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
33 Result.push_back(InVTs[i]);
38 static std::vector<unsigned char>
39 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40 std::vector<unsigned char> Result;
41 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42 if (Filter((MVT::ValueType)InVTs[i]))
43 Result.push_back(InVTs[i]);
47 static std::vector<unsigned char>
48 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49 std::vector<unsigned char> Result;
50 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51 Result.push_back(InVTs[i]);
55 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56 const std::vector<unsigned char> &RHS) {
57 if (LHS.size() > RHS.size()) return false;
58 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
59 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
64 /// isExtIntegerVT - Return true if the specified extended value type vector
65 /// contains isInt or an integer value type.
66 static bool isExtIntegerInVTs(std::vector<unsigned char> EVTs) {
67 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
71 /// isExtFloatingPointVT - Return true if the specified extended value type
72 /// vector contains isFP or a FP value type.
73 static bool isExtFloatingPointInVTs(std::vector<unsigned char> EVTs) {
74 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
75 return EVTs[0] == MVT::isFP ||
76 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
79 //===----------------------------------------------------------------------===//
80 // SDTypeConstraint implementation
83 SDTypeConstraint::SDTypeConstraint(Record *R) {
84 OperandNo = R->getValueAsInt("OperandNum");
86 if (R->isSubClassOf("SDTCisVT")) {
87 ConstraintType = SDTCisVT;
88 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
89 } else if (R->isSubClassOf("SDTCisPtrTy")) {
90 ConstraintType = SDTCisPtrTy;
91 } else if (R->isSubClassOf("SDTCisInt")) {
92 ConstraintType = SDTCisInt;
93 } else if (R->isSubClassOf("SDTCisFP")) {
94 ConstraintType = SDTCisFP;
95 } else if (R->isSubClassOf("SDTCisSameAs")) {
96 ConstraintType = SDTCisSameAs;
97 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
98 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
99 ConstraintType = SDTCisVTSmallerThanOp;
100 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
101 R->getValueAsInt("OtherOperandNum");
102 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
103 ConstraintType = SDTCisOpSmallerThanOp;
104 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
105 R->getValueAsInt("BigOperandNum");
107 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
112 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
113 /// N, which has NumResults results.
114 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
116 unsigned NumResults) const {
117 assert(NumResults <= 1 &&
118 "We only work with nodes with zero or one result so far!");
120 if (OpNo < NumResults)
121 return N; // FIXME: need value #
123 return N->getChild(OpNo-NumResults);
126 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
127 /// constraint to the nodes operands. This returns true if it makes a
128 /// change, false otherwise. If a type contradiction is found, throw an
130 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
131 const SDNodeInfo &NodeInfo,
132 TreePattern &TP) const {
133 unsigned NumResults = NodeInfo.getNumResults();
134 assert(NumResults <= 1 &&
135 "We only work with nodes with zero or one result so far!");
137 // Check that the number of operands is sane.
138 if (NodeInfo.getNumOperands() >= 0) {
139 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
140 TP.error(N->getOperator()->getName() + " node requires exactly " +
141 itostr(NodeInfo.getNumOperands()) + " operands!");
144 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
146 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
148 switch (ConstraintType) {
149 default: assert(0 && "Unknown constraint type!");
151 // Operand must be a particular type.
152 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
154 // Operand must be same as target pointer type.
155 return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
158 // If there is only one integer type supported, this must be it.
159 std::vector<MVT::ValueType> IntVTs =
160 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
162 // If we found exactly one supported integer type, apply it.
163 if (IntVTs.size() == 1)
164 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
165 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
168 // If there is only one FP type supported, this must be it.
169 std::vector<MVT::ValueType> FPVTs =
170 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
172 // If we found exactly one supported FP type, apply it.
173 if (FPVTs.size() == 1)
174 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
175 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
178 TreePatternNode *OtherNode =
179 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
180 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
181 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
183 case SDTCisVTSmallerThanOp: {
184 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
185 // have an integer type that is smaller than the VT.
186 if (!NodeToApply->isLeaf() ||
187 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
188 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
189 ->isSubClassOf("ValueType"))
190 TP.error(N->getOperator()->getName() + " expects a VT operand!");
192 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
193 if (!MVT::isInteger(VT))
194 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
196 TreePatternNode *OtherNode =
197 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
199 // It must be integer.
200 bool MadeChange = false;
201 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
203 // This code only handles nodes that have one type set. Assert here so
204 // that we can change this if we ever need to deal with multiple value
205 // types at this point.
206 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
207 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
208 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
211 case SDTCisOpSmallerThanOp: {
212 TreePatternNode *BigOperand =
213 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
215 // Both operands must be integer or FP, but we don't care which.
216 bool MadeChange = false;
218 // This code does not currently handle nodes which have multiple types,
219 // where some types are integer, and some are fp. Assert that this is not
221 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
222 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
223 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
224 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
225 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
226 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
227 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
228 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
229 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
230 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
231 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
232 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
233 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
235 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
237 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
238 VTs = FilterVTs(VTs, MVT::isInteger);
239 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
240 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
245 switch (VTs.size()) {
246 default: // Too many VT's to pick from.
247 case 0: break; // No info yet.
249 // Only one VT of this flavor. Cannot ever satisify the constraints.
250 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
252 // If we have exactly two possible types, the little operand must be the
253 // small one, the big operand should be the big one. Common with
254 // float/double for example.
255 assert(VTs[0] < VTs[1] && "Should be sorted!");
256 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
257 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
267 //===----------------------------------------------------------------------===//
268 // SDNodeInfo implementation
270 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
271 EnumName = R->getValueAsString("Opcode");
272 SDClassName = R->getValueAsString("SDClass");
273 Record *TypeProfile = R->getValueAsDef("TypeProfile");
274 NumResults = TypeProfile->getValueAsInt("NumResults");
275 NumOperands = TypeProfile->getValueAsInt("NumOperands");
277 // Parse the properties.
279 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
280 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
281 if (PropList[i]->getName() == "SDNPCommutative") {
282 Properties |= 1 << SDNPCommutative;
283 } else if (PropList[i]->getName() == "SDNPAssociative") {
284 Properties |= 1 << SDNPAssociative;
285 } else if (PropList[i]->getName() == "SDNPHasChain") {
286 Properties |= 1 << SDNPHasChain;
287 } else if (PropList[i]->getName() == "SDNPOutFlag") {
288 Properties |= 1 << SDNPOutFlag;
289 } else if (PropList[i]->getName() == "SDNPInFlag") {
290 Properties |= 1 << SDNPInFlag;
291 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
292 Properties |= 1 << SDNPOptInFlag;
294 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
295 << "' on node '" << R->getName() << "'!\n";
301 // Parse the type constraints.
302 std::vector<Record*> ConstraintList =
303 TypeProfile->getValueAsListOfDefs("Constraints");
304 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
307 //===----------------------------------------------------------------------===//
308 // TreePatternNode implementation
311 TreePatternNode::~TreePatternNode() {
312 #if 0 // FIXME: implement refcounted tree nodes!
313 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
318 /// UpdateNodeType - Set the node type of N to VT if VT contains
319 /// information. If N already contains a conflicting type, then throw an
320 /// exception. This returns true if any information was updated.
322 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
324 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
326 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
328 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
333 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
334 assert(hasTypeSet() && "should be handled above!");
335 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
336 if (getExtTypes() == FVTs)
341 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
342 assert(hasTypeSet() && "should be handled above!");
343 std::vector<unsigned char> FVTs =
344 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
345 if (getExtTypes() == FVTs)
351 // If we know this is an int or fp type, and we are told it is a specific one,
354 // Similarly, we should probably set the type here to the intersection of
355 // {isInt|isFP} and ExtVTs
356 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
357 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
365 TP.error("Type inference contradiction found in node!");
367 TP.error("Type inference contradiction found in node " +
368 getOperator()->getName() + "!");
370 return true; // unreachable
374 void TreePatternNode::print(std::ostream &OS) const {
376 OS << *getLeafValue();
378 OS << "(" << getOperator()->getName();
381 // FIXME: At some point we should handle printing all the value types for
382 // nodes that are multiply typed.
383 switch (getExtTypeNum(0)) {
384 case MVT::Other: OS << ":Other"; break;
385 case MVT::isInt: OS << ":isInt"; break;
386 case MVT::isFP : OS << ":isFP"; break;
387 case MVT::isUnknown: ; /*OS << ":?";*/ break;
388 default: OS << ":" << getTypeNum(0); break;
392 if (getNumChildren() != 0) {
394 getChild(0)->print(OS);
395 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
397 getChild(i)->print(OS);
403 if (!PredicateFn.empty())
404 OS << "<<P:" << PredicateFn << ">>";
406 OS << "<<X:" << TransformFn->getName() << ">>";
407 if (!getName().empty())
408 OS << ":$" << getName();
411 void TreePatternNode::dump() const {
415 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
416 /// the specified node. For this comparison, all of the state of the node
417 /// is considered, except for the assigned name. Nodes with differing names
418 /// that are otherwise identical are considered isomorphic.
419 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
420 if (N == this) return true;
421 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
422 getPredicateFn() != N->getPredicateFn() ||
423 getTransformFn() != N->getTransformFn())
427 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
428 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
429 return DI->getDef() == NDI->getDef();
430 return getLeafValue() == N->getLeafValue();
433 if (N->getOperator() != getOperator() ||
434 N->getNumChildren() != getNumChildren()) return false;
435 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
436 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
441 /// clone - Make a copy of this tree and all of its children.
443 TreePatternNode *TreePatternNode::clone() const {
444 TreePatternNode *New;
446 New = new TreePatternNode(getLeafValue());
448 std::vector<TreePatternNode*> CChildren;
449 CChildren.reserve(Children.size());
450 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
451 CChildren.push_back(getChild(i)->clone());
452 New = new TreePatternNode(getOperator(), CChildren);
454 New->setName(getName());
455 New->setTypes(getExtTypes());
456 New->setPredicateFn(getPredicateFn());
457 New->setTransformFn(getTransformFn());
461 /// SubstituteFormalArguments - Replace the formal arguments in this tree
462 /// with actual values specified by ArgMap.
463 void TreePatternNode::
464 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
465 if (isLeaf()) return;
467 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
468 TreePatternNode *Child = getChild(i);
469 if (Child->isLeaf()) {
470 Init *Val = Child->getLeafValue();
471 if (dynamic_cast<DefInit*>(Val) &&
472 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
473 // We found a use of a formal argument, replace it with its value.
474 Child = ArgMap[Child->getName()];
475 assert(Child && "Couldn't find formal argument!");
479 getChild(i)->SubstituteFormalArguments(ArgMap);
485 /// InlinePatternFragments - If this pattern refers to any pattern
486 /// fragments, inline them into place, giving us a pattern without any
487 /// PatFrag references.
488 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
489 if (isLeaf()) return this; // nothing to do.
490 Record *Op = getOperator();
492 if (!Op->isSubClassOf("PatFrag")) {
493 // Just recursively inline children nodes.
494 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
495 setChild(i, getChild(i)->InlinePatternFragments(TP));
499 // Otherwise, we found a reference to a fragment. First, look up its
500 // TreePattern record.
501 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
503 // Verify that we are passing the right number of operands.
504 if (Frag->getNumArgs() != Children.size())
505 TP.error("'" + Op->getName() + "' fragment requires " +
506 utostr(Frag->getNumArgs()) + " operands!");
508 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
510 // Resolve formal arguments to their actual value.
511 if (Frag->getNumArgs()) {
512 // Compute the map of formal to actual arguments.
513 std::map<std::string, TreePatternNode*> ArgMap;
514 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
515 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
517 FragTree->SubstituteFormalArguments(ArgMap);
520 FragTree->setName(getName());
521 FragTree->UpdateNodeType(getExtTypes(), TP);
523 // Get a new copy of this fragment to stitch into here.
524 //delete this; // FIXME: implement refcounting!
528 /// getIntrinsicType - Check to see if the specified record has an intrinsic
529 /// type which should be applied to it. This infer the type of register
530 /// references from the register file information, for example.
532 static std::vector<unsigned char> getIntrinsicType(Record *R, bool NotRegisters,
534 // Some common return values
535 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
536 std::vector<unsigned char> Other(1, MVT::Other);
538 // Check to see if this is a register or a register class...
539 if (R->isSubClassOf("RegisterClass")) {
542 const CodeGenRegisterClass &RC =
543 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
544 return ConvertVTs(RC.getValueTypes());
545 } else if (R->isSubClassOf("PatFrag")) {
546 // Pattern fragment types will be resolved when they are inlined.
548 } else if (R->isSubClassOf("Register")) {
551 // If the register appears in exactly one regclass, and the regclass has one
552 // value type, use it as the known type.
553 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
554 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
555 return ConvertVTs(RC->getValueTypes());
557 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
558 // Using a VTSDNode or CondCodeSDNode.
560 } else if (R->isSubClassOf("ComplexPattern")) {
563 std::vector<unsigned char>
564 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
566 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
571 TP.error("Unknown node flavor used in pattern: " + R->getName());
575 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
576 /// this node and its children in the tree. This returns true if it makes a
577 /// change, false otherwise. If a type contradiction is found, throw an
579 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
581 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
582 // If it's a regclass or something else known, include the type.
583 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
585 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
586 // Int inits are always integers. :)
587 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
590 // At some point, it may make sense for this tree pattern to have
591 // multiple types. Assert here that it does not, so we revisit this
592 // code when appropriate.
593 assert(getExtTypes().size() == 1 && "TreePattern has too many types!");
595 unsigned Size = MVT::getSizeInBits(getTypeNum(0));
596 // Make sure that the value is representable for this type.
598 int Val = (II->getValue() << (32-Size)) >> (32-Size);
599 if (Val != II->getValue())
600 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
601 "' is out of range for type 'MVT::" +
602 getEnumName(getTypeNum(0)) + "'!");
611 // special handling for set, which isn't really an SDNode.
612 if (getOperator()->getName() == "set") {
613 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
614 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
615 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
617 // Types of operands must match.
618 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
619 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
620 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
622 } else if (getOperator()->isSubClassOf("SDNode")) {
623 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
625 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
626 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
627 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
628 // Branch, etc. do not produce results and top-level forms in instr pattern
629 // must have void types.
630 if (NI.getNumResults() == 0)
631 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
633 } else if (getOperator()->isSubClassOf("Instruction")) {
634 const DAGInstruction &Inst =
635 TP.getDAGISelEmitter().getInstruction(getOperator());
636 bool MadeChange = false;
637 unsigned NumResults = Inst.getNumResults();
639 assert(NumResults <= 1 &&
640 "Only supports zero or one result instrs!");
641 // Apply the result type to the node
642 if (NumResults == 0) {
643 MadeChange = UpdateNodeType(MVT::isVoid, TP);
645 Record *ResultNode = Inst.getResult(0);
646 assert(ResultNode->isSubClassOf("RegisterClass") &&
647 "Operands should be register classes!");
649 const CodeGenRegisterClass &RC =
650 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
651 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
654 if (getNumChildren() != Inst.getNumOperands())
655 TP.error("Instruction '" + getOperator()->getName() + " expects " +
656 utostr(Inst.getNumOperands()) + " operands, not " +
657 utostr(getNumChildren()) + " operands!");
658 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
659 Record *OperandNode = Inst.getOperand(i);
661 if (OperandNode->isSubClassOf("RegisterClass")) {
662 const CodeGenRegisterClass &RC =
663 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
664 //VT = RC.getValueTypeNum(0);
665 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
667 } else if (OperandNode->isSubClassOf("Operand")) {
668 VT = getValueType(OperandNode->getValueAsDef("Type"));
669 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
671 assert(0 && "Unknown operand type!");
674 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
678 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
680 // Node transforms always take one operand, and take and return the same
682 if (getNumChildren() != 1)
683 TP.error("Node transform '" + getOperator()->getName() +
684 "' requires one operand!");
685 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
686 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
691 /// canPatternMatch - If it is impossible for this pattern to match on this
692 /// target, fill in Reason and return false. Otherwise, return true. This is
693 /// used as a santity check for .td files (to prevent people from writing stuff
694 /// that can never possibly work), and to prevent the pattern permuter from
695 /// generating stuff that is useless.
696 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
697 if (isLeaf()) return true;
699 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
700 if (!getChild(i)->canPatternMatch(Reason, ISE))
703 // If this node is a commutative operator, check that the LHS isn't an
705 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
706 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
707 // Scan all of the operands of the node and make sure that only the last one
708 // is a constant node.
709 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
710 if (!getChild(i)->isLeaf() &&
711 getChild(i)->getOperator()->getName() == "imm") {
712 Reason = "Immediate value must be on the RHS of commutative operators!";
720 //===----------------------------------------------------------------------===//
721 // TreePattern implementation
724 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
725 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
726 isInputPattern = isInput;
727 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
728 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
731 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
732 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
733 isInputPattern = isInput;
734 Trees.push_back(ParseTreePattern(Pat));
737 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
738 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
739 isInputPattern = isInput;
740 Trees.push_back(Pat);
745 void TreePattern::error(const std::string &Msg) const {
747 throw "In " + TheRecord->getName() + ": " + Msg;
750 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
751 Record *Operator = Dag->getNodeType();
753 if (Operator->isSubClassOf("ValueType")) {
754 // If the operator is a ValueType, then this must be "type cast" of a leaf
756 if (Dag->getNumArgs() != 1)
757 error("Type cast only takes one operand!");
759 Init *Arg = Dag->getArg(0);
760 TreePatternNode *New;
761 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
762 Record *R = DI->getDef();
763 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
764 Dag->setArg(0, new DagInit(R,
765 std::vector<std::pair<Init*, std::string> >()));
766 return ParseTreePattern(Dag);
768 New = new TreePatternNode(DI);
769 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
770 New = ParseTreePattern(DI);
771 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
772 New = new TreePatternNode(II);
773 if (!Dag->getArgName(0).empty())
774 error("Constant int argument should not have a name!");
777 error("Unknown leaf value for tree pattern!");
781 // Apply the type cast.
782 New->UpdateNodeType(getValueType(Operator), *this);
783 New->setName(Dag->getArgName(0));
787 // Verify that this is something that makes sense for an operator.
788 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
789 !Operator->isSubClassOf("Instruction") &&
790 !Operator->isSubClassOf("SDNodeXForm") &&
791 Operator->getName() != "set")
792 error("Unrecognized node '" + Operator->getName() + "'!");
794 // Check to see if this is something that is illegal in an input pattern.
795 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
796 Operator->isSubClassOf("SDNodeXForm")))
797 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
799 std::vector<TreePatternNode*> Children;
801 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
802 Init *Arg = Dag->getArg(i);
803 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
804 Children.push_back(ParseTreePattern(DI));
805 if (Children.back()->getName().empty())
806 Children.back()->setName(Dag->getArgName(i));
807 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
808 Record *R = DefI->getDef();
809 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
810 // TreePatternNode if its own.
811 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
812 Dag->setArg(i, new DagInit(R,
813 std::vector<std::pair<Init*, std::string> >()));
814 --i; // Revisit this node...
816 TreePatternNode *Node = new TreePatternNode(DefI);
817 Node->setName(Dag->getArgName(i));
818 Children.push_back(Node);
821 if (R->getName() == "node") {
822 if (Dag->getArgName(i).empty())
823 error("'node' argument requires a name to match with operand list");
824 Args.push_back(Dag->getArgName(i));
827 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
828 TreePatternNode *Node = new TreePatternNode(II);
829 if (!Dag->getArgName(i).empty())
830 error("Constant int argument should not have a name!");
831 Children.push_back(Node);
836 error("Unknown leaf value for tree pattern!");
840 return new TreePatternNode(Operator, Children);
843 /// InferAllTypes - Infer/propagate as many types throughout the expression
844 /// patterns as possible. Return true if all types are infered, false
845 /// otherwise. Throw an exception if a type contradiction is found.
846 bool TreePattern::InferAllTypes() {
847 bool MadeChange = true;
850 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
851 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
854 bool HasUnresolvedTypes = false;
855 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
856 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
857 return !HasUnresolvedTypes;
860 void TreePattern::print(std::ostream &OS) const {
861 OS << getRecord()->getName();
863 OS << "(" << Args[0];
864 for (unsigned i = 1, e = Args.size(); i != e; ++i)
865 OS << ", " << Args[i];
870 if (Trees.size() > 1)
872 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
878 if (Trees.size() > 1)
882 void TreePattern::dump() const { print(std::cerr); }
886 //===----------------------------------------------------------------------===//
887 // DAGISelEmitter implementation
890 // Parse all of the SDNode definitions for the target, populating SDNodes.
891 void DAGISelEmitter::ParseNodeInfo() {
892 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
893 while (!Nodes.empty()) {
894 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
899 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
900 /// map, and emit them to the file as functions.
901 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
902 OS << "\n// Node transformations.\n";
903 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
904 while (!Xforms.empty()) {
905 Record *XFormNode = Xforms.back();
906 Record *SDNode = XFormNode->getValueAsDef("Opcode");
907 std::string Code = XFormNode->getValueAsCode("XFormFunction");
908 SDNodeXForms.insert(std::make_pair(XFormNode,
909 std::make_pair(SDNode, Code)));
912 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
913 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
915 OS << "inline SDOperand Transform_" << XFormNode->getName()
916 << "(SDNode *" << C2 << ") {\n";
917 if (ClassName != "SDNode")
918 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
919 OS << Code << "\n}\n";
926 void DAGISelEmitter::ParseComplexPatterns() {
927 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
928 while (!AMs.empty()) {
929 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
935 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
936 /// file, building up the PatternFragments map. After we've collected them all,
937 /// inline fragments together as necessary, so that there are no references left
938 /// inside a pattern fragment to a pattern fragment.
940 /// This also emits all of the predicate functions to the output file.
942 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
943 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
945 // First step, parse all of the fragments and emit predicate functions.
946 OS << "\n// Predicate functions.\n";
947 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
948 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
949 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
950 PatternFragments[Fragments[i]] = P;
952 // Validate the argument list, converting it to map, to discard duplicates.
953 std::vector<std::string> &Args = P->getArgList();
954 std::set<std::string> OperandsMap(Args.begin(), Args.end());
956 if (OperandsMap.count(""))
957 P->error("Cannot have unnamed 'node' values in pattern fragment!");
959 // Parse the operands list.
960 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
961 if (OpsList->getNodeType()->getName() != "ops")
962 P->error("Operands list should start with '(ops ... '!");
964 // Copy over the arguments.
966 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
967 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
968 static_cast<DefInit*>(OpsList->getArg(j))->
969 getDef()->getName() != "node")
970 P->error("Operands list should all be 'node' values.");
971 if (OpsList->getArgName(j).empty())
972 P->error("Operands list should have names for each operand!");
973 if (!OperandsMap.count(OpsList->getArgName(j)))
974 P->error("'" + OpsList->getArgName(j) +
975 "' does not occur in pattern or was multiply specified!");
976 OperandsMap.erase(OpsList->getArgName(j));
977 Args.push_back(OpsList->getArgName(j));
980 if (!OperandsMap.empty())
981 P->error("Operands list does not contain an entry for operand '" +
982 *OperandsMap.begin() + "'!");
984 // If there is a code init for this fragment, emit the predicate code and
985 // keep track of the fact that this fragment uses it.
986 std::string Code = Fragments[i]->getValueAsCode("Predicate");
988 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
989 std::string ClassName =
990 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
991 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
993 OS << "inline bool Predicate_" << Fragments[i]->getName()
994 << "(SDNode *" << C2 << ") {\n";
995 if (ClassName != "SDNode")
996 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
997 OS << Code << "\n}\n";
998 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1001 // If there is a node transformation corresponding to this, keep track of
1003 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1004 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1005 P->getOnlyTree()->setTransformFn(Transform);
1010 // Now that we've parsed all of the tree fragments, do a closure on them so
1011 // that there are not references to PatFrags left inside of them.
1012 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1013 E = PatternFragments.end(); I != E; ++I) {
1014 TreePattern *ThePat = I->second;
1015 ThePat->InlinePatternFragments();
1017 // Infer as many types as possible. Don't worry about it if we don't infer
1018 // all of them, some may depend on the inputs of the pattern.
1020 ThePat->InferAllTypes();
1022 // If this pattern fragment is not supported by this target (no types can
1023 // satisfy its constraints), just ignore it. If the bogus pattern is
1024 // actually used by instructions, the type consistency error will be
1028 // If debugging, print out the pattern fragment result.
1029 DEBUG(ThePat->dump());
1033 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1034 /// instruction input. Return true if this is a real use.
1035 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1036 std::map<std::string, TreePatternNode*> &InstInputs,
1037 std::vector<Record*> &InstImpInputs) {
1038 // No name -> not interesting.
1039 if (Pat->getName().empty()) {
1040 if (Pat->isLeaf()) {
1041 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1042 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1043 I->error("Input " + DI->getDef()->getName() + " must be named!");
1044 else if (DI && DI->getDef()->isSubClassOf("Register"))
1045 InstImpInputs.push_back(DI->getDef());
1051 if (Pat->isLeaf()) {
1052 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1053 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1056 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1057 Rec = Pat->getOperator();
1060 // SRCVALUE nodes are ignored.
1061 if (Rec->getName() == "srcvalue")
1064 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1069 if (Slot->isLeaf()) {
1070 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1072 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1073 SlotRec = Slot->getOperator();
1076 // Ensure that the inputs agree if we've already seen this input.
1078 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1079 if (Slot->getExtTypes() != Pat->getExtTypes())
1080 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1085 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1086 /// part of "I", the instruction), computing the set of inputs and outputs of
1087 /// the pattern. Report errors if we see anything naughty.
1088 void DAGISelEmitter::
1089 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1090 std::map<std::string, TreePatternNode*> &InstInputs,
1091 std::map<std::string, Record*> &InstResults,
1092 std::vector<Record*> &InstImpInputs,
1093 std::vector<Record*> &InstImpResults) {
1094 if (Pat->isLeaf()) {
1095 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1096 if (!isUse && Pat->getTransformFn())
1097 I->error("Cannot specify a transform function for a non-input value!");
1099 } else if (Pat->getOperator()->getName() != "set") {
1100 // If this is not a set, verify that the children nodes are not void typed,
1102 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1103 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1104 I->error("Cannot have void nodes inside of patterns!");
1105 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1106 InstImpInputs, InstImpResults);
1109 // If this is a non-leaf node with no children, treat it basically as if
1110 // it were a leaf. This handles nodes like (imm).
1112 if (Pat->getNumChildren() == 0)
1113 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1115 if (!isUse && Pat->getTransformFn())
1116 I->error("Cannot specify a transform function for a non-input value!");
1120 // Otherwise, this is a set, validate and collect instruction results.
1121 if (Pat->getNumChildren() == 0)
1122 I->error("set requires operands!");
1123 else if (Pat->getNumChildren() & 1)
1124 I->error("set requires an even number of operands");
1126 if (Pat->getTransformFn())
1127 I->error("Cannot specify a transform function on a set node!");
1129 // Check the set destinations.
1130 unsigned NumValues = Pat->getNumChildren()/2;
1131 for (unsigned i = 0; i != NumValues; ++i) {
1132 TreePatternNode *Dest = Pat->getChild(i);
1133 if (!Dest->isLeaf())
1134 I->error("set destination should be a register!");
1136 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1138 I->error("set destination should be a register!");
1140 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1141 if (Dest->getName().empty())
1142 I->error("set destination must have a name!");
1143 if (InstResults.count(Dest->getName()))
1144 I->error("cannot set '" + Dest->getName() +"' multiple times");
1145 InstResults[Dest->getName()] = Val->getDef();
1146 } else if (Val->getDef()->isSubClassOf("Register")) {
1147 InstImpResults.push_back(Val->getDef());
1149 I->error("set destination should be a register!");
1152 // Verify and collect info from the computation.
1153 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1154 InstInputs, InstResults,
1155 InstImpInputs, InstImpResults);
1159 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1160 /// any fragments involved. This populates the Instructions list with fully
1161 /// resolved instructions.
1162 void DAGISelEmitter::ParseInstructions() {
1163 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1165 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1168 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1169 LI = Instrs[i]->getValueAsListInit("Pattern");
1171 // If there is no pattern, only collect minimal information about the
1172 // instruction for its operand list. We have to assume that there is one
1173 // result, as we have no detailed info.
1174 if (!LI || LI->getSize() == 0) {
1175 std::vector<Record*> Results;
1176 std::vector<Record*> Operands;
1178 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1180 if (InstInfo.OperandList.size() != 0) {
1181 // FIXME: temporary hack...
1182 if (InstInfo.noResults) {
1183 // These produce no results
1184 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1185 Operands.push_back(InstInfo.OperandList[j].Rec);
1187 // Assume the first operand is the result.
1188 Results.push_back(InstInfo.OperandList[0].Rec);
1190 // The rest are inputs.
1191 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1192 Operands.push_back(InstInfo.OperandList[j].Rec);
1196 // Create and insert the instruction.
1197 std::vector<Record*> ImpResults;
1198 std::vector<Record*> ImpOperands;
1199 Instructions.insert(std::make_pair(Instrs[i],
1200 DAGInstruction(0, Results, Operands, ImpResults,
1202 continue; // no pattern.
1205 // Parse the instruction.
1206 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1207 // Inline pattern fragments into it.
1208 I->InlinePatternFragments();
1210 // Infer as many types as possible. If we cannot infer all of them, we can
1211 // never do anything with this instruction pattern: report it to the user.
1212 if (!I->InferAllTypes())
1213 I->error("Could not infer all types in pattern!");
1215 // InstInputs - Keep track of all of the inputs of the instruction, along
1216 // with the record they are declared as.
1217 std::map<std::string, TreePatternNode*> InstInputs;
1219 // InstResults - Keep track of all the virtual registers that are 'set'
1220 // in the instruction, including what reg class they are.
1221 std::map<std::string, Record*> InstResults;
1223 std::vector<Record*> InstImpInputs;
1224 std::vector<Record*> InstImpResults;
1226 // Verify that the top-level forms in the instruction are of void type, and
1227 // fill in the InstResults map.
1228 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1229 TreePatternNode *Pat = I->getTree(j);
1230 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1231 I->error("Top-level forms in instruction pattern should have"
1234 // Find inputs and outputs, and verify the structure of the uses/defs.
1235 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1236 InstImpInputs, InstImpResults);
1239 // Now that we have inputs and outputs of the pattern, inspect the operands
1240 // list for the instruction. This determines the order that operands are
1241 // added to the machine instruction the node corresponds to.
1242 unsigned NumResults = InstResults.size();
1244 // Parse the operands list from the (ops) list, validating it.
1245 std::vector<std::string> &Args = I->getArgList();
1246 assert(Args.empty() && "Args list should still be empty here!");
1247 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1249 // Check that all of the results occur first in the list.
1250 std::vector<Record*> Results;
1251 for (unsigned i = 0; i != NumResults; ++i) {
1252 if (i == CGI.OperandList.size())
1253 I->error("'" + InstResults.begin()->first +
1254 "' set but does not appear in operand list!");
1255 const std::string &OpName = CGI.OperandList[i].Name;
1257 // Check that it exists in InstResults.
1258 Record *R = InstResults[OpName];
1260 I->error("Operand $" + OpName + " should be a set destination: all "
1261 "outputs must occur before inputs in operand list!");
1263 if (CGI.OperandList[i].Rec != R)
1264 I->error("Operand $" + OpName + " class mismatch!");
1266 // Remember the return type.
1267 Results.push_back(CGI.OperandList[i].Rec);
1269 // Okay, this one checks out.
1270 InstResults.erase(OpName);
1273 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1274 // the copy while we're checking the inputs.
1275 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1277 std::vector<TreePatternNode*> ResultNodeOperands;
1278 std::vector<Record*> Operands;
1279 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1280 const std::string &OpName = CGI.OperandList[i].Name;
1282 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1284 if (!InstInputsCheck.count(OpName))
1285 I->error("Operand $" + OpName +
1286 " does not appear in the instruction pattern");
1287 TreePatternNode *InVal = InstInputsCheck[OpName];
1288 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1290 if (InVal->isLeaf() &&
1291 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1292 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1293 if (CGI.OperandList[i].Rec != InRec &&
1294 !InRec->isSubClassOf("ComplexPattern"))
1295 I->error("Operand $" + OpName + "'s register class disagrees"
1296 " between the operand and pattern");
1298 Operands.push_back(CGI.OperandList[i].Rec);
1300 // Construct the result for the dest-pattern operand list.
1301 TreePatternNode *OpNode = InVal->clone();
1303 // No predicate is useful on the result.
1304 OpNode->setPredicateFn("");
1306 // Promote the xform function to be an explicit node if set.
1307 if (Record *Xform = OpNode->getTransformFn()) {
1308 OpNode->setTransformFn(0);
1309 std::vector<TreePatternNode*> Children;
1310 Children.push_back(OpNode);
1311 OpNode = new TreePatternNode(Xform, Children);
1314 ResultNodeOperands.push_back(OpNode);
1317 if (!InstInputsCheck.empty())
1318 I->error("Input operand $" + InstInputsCheck.begin()->first +
1319 " occurs in pattern but not in operands list!");
1321 TreePatternNode *ResultPattern =
1322 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1324 // Create and insert the instruction.
1325 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1326 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1328 // Use a temporary tree pattern to infer all types and make sure that the
1329 // constructed result is correct. This depends on the instruction already
1330 // being inserted into the Instructions map.
1331 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1332 Temp.InferAllTypes();
1334 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1335 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1340 // If we can, convert the instructions to be patterns that are matched!
1341 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1342 E = Instructions.end(); II != E; ++II) {
1343 DAGInstruction &TheInst = II->second;
1344 TreePattern *I = TheInst.getPattern();
1345 if (I == 0) continue; // No pattern.
1347 if (I->getNumTrees() != 1) {
1348 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1351 TreePatternNode *Pattern = I->getTree(0);
1352 TreePatternNode *SrcPattern;
1353 if (Pattern->getOperator()->getName() == "set") {
1354 if (Pattern->getNumChildren() != 2)
1355 continue; // Not a set of a single value (not handled so far)
1357 SrcPattern = Pattern->getChild(1)->clone();
1359 // Not a set (store or something?)
1360 SrcPattern = Pattern;
1364 if (!SrcPattern->canPatternMatch(Reason, *this))
1365 I->error("Instruction can never match: " + Reason);
1367 Record *Instr = II->first;
1368 TreePatternNode *DstPattern = TheInst.getResultPattern();
1370 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1371 SrcPattern, DstPattern));
1375 void DAGISelEmitter::ParsePatterns() {
1376 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1378 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1379 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1380 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1382 // Inline pattern fragments into it.
1383 Pattern->InlinePatternFragments();
1385 // Infer as many types as possible. If we cannot infer all of them, we can
1386 // never do anything with this pattern: report it to the user.
1387 if (!Pattern->InferAllTypes())
1388 Pattern->error("Could not infer all types in pattern!");
1390 // Validate that the input pattern is correct.
1392 std::map<std::string, TreePatternNode*> InstInputs;
1393 std::map<std::string, Record*> InstResults;
1394 std::vector<Record*> InstImpInputs;
1395 std::vector<Record*> InstImpResults;
1396 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1397 InstInputs, InstResults,
1398 InstImpInputs, InstImpResults);
1401 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1402 if (LI->getSize() == 0) continue; // no pattern.
1404 // Parse the instruction.
1405 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1407 // Inline pattern fragments into it.
1408 Result->InlinePatternFragments();
1410 // Infer as many types as possible. If we cannot infer all of them, we can
1411 // never do anything with this pattern: report it to the user.
1412 if (!Result->InferAllTypes())
1413 Result->error("Could not infer all types in pattern result!");
1415 if (Result->getNumTrees() != 1)
1416 Result->error("Cannot handle instructions producing instructions "
1417 "with temporaries yet!");
1420 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1421 Pattern->error("Pattern can never match: " + Reason);
1424 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1425 Pattern->getOnlyTree(),
1426 Result->getOnlyTree()));
1430 /// CombineChildVariants - Given a bunch of permutations of each child of the
1431 /// 'operator' node, put them together in all possible ways.
1432 static void CombineChildVariants(TreePatternNode *Orig,
1433 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1434 std::vector<TreePatternNode*> &OutVariants,
1435 DAGISelEmitter &ISE) {
1436 // Make sure that each operand has at least one variant to choose from.
1437 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1438 if (ChildVariants[i].empty())
1441 // The end result is an all-pairs construction of the resultant pattern.
1442 std::vector<unsigned> Idxs;
1443 Idxs.resize(ChildVariants.size());
1444 bool NotDone = true;
1446 // Create the variant and add it to the output list.
1447 std::vector<TreePatternNode*> NewChildren;
1448 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1449 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1450 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1452 // Copy over properties.
1453 R->setName(Orig->getName());
1454 R->setPredicateFn(Orig->getPredicateFn());
1455 R->setTransformFn(Orig->getTransformFn());
1456 R->setTypes(Orig->getExtTypes());
1458 // If this pattern cannot every match, do not include it as a variant.
1459 std::string ErrString;
1460 if (!R->canPatternMatch(ErrString, ISE)) {
1463 bool AlreadyExists = false;
1465 // Scan to see if this pattern has already been emitted. We can get
1466 // duplication due to things like commuting:
1467 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1468 // which are the same pattern. Ignore the dups.
1469 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1470 if (R->isIsomorphicTo(OutVariants[i])) {
1471 AlreadyExists = true;
1478 OutVariants.push_back(R);
1481 // Increment indices to the next permutation.
1483 // Look for something we can increment without causing a wrap-around.
1484 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1485 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1486 NotDone = true; // Found something to increment.
1494 /// CombineChildVariants - A helper function for binary operators.
1496 static void CombineChildVariants(TreePatternNode *Orig,
1497 const std::vector<TreePatternNode*> &LHS,
1498 const std::vector<TreePatternNode*> &RHS,
1499 std::vector<TreePatternNode*> &OutVariants,
1500 DAGISelEmitter &ISE) {
1501 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1502 ChildVariants.push_back(LHS);
1503 ChildVariants.push_back(RHS);
1504 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1508 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1509 std::vector<TreePatternNode *> &Children) {
1510 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1511 Record *Operator = N->getOperator();
1513 // Only permit raw nodes.
1514 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1515 N->getTransformFn()) {
1516 Children.push_back(N);
1520 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1521 Children.push_back(N->getChild(0));
1523 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1525 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1526 Children.push_back(N->getChild(1));
1528 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1531 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1532 /// the (potentially recursive) pattern by using algebraic laws.
1534 static void GenerateVariantsOf(TreePatternNode *N,
1535 std::vector<TreePatternNode*> &OutVariants,
1536 DAGISelEmitter &ISE) {
1537 // We cannot permute leaves.
1539 OutVariants.push_back(N);
1543 // Look up interesting info about the node.
1544 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1546 // If this node is associative, reassociate.
1547 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1548 // Reassociate by pulling together all of the linked operators
1549 std::vector<TreePatternNode*> MaximalChildren;
1550 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1552 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1554 if (MaximalChildren.size() == 3) {
1555 // Find the variants of all of our maximal children.
1556 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1557 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1558 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1559 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1561 // There are only two ways we can permute the tree:
1562 // (A op B) op C and A op (B op C)
1563 // Within these forms, we can also permute A/B/C.
1565 // Generate legal pair permutations of A/B/C.
1566 std::vector<TreePatternNode*> ABVariants;
1567 std::vector<TreePatternNode*> BAVariants;
1568 std::vector<TreePatternNode*> ACVariants;
1569 std::vector<TreePatternNode*> CAVariants;
1570 std::vector<TreePatternNode*> BCVariants;
1571 std::vector<TreePatternNode*> CBVariants;
1572 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1573 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1574 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1575 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1576 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1577 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1579 // Combine those into the result: (x op x) op x
1580 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1581 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1582 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1583 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1584 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1585 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1587 // Combine those into the result: x op (x op x)
1588 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1589 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1590 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1591 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1592 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1593 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1598 // Compute permutations of all children.
1599 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1600 ChildVariants.resize(N->getNumChildren());
1601 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1602 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1604 // Build all permutations based on how the children were formed.
1605 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1607 // If this node is commutative, consider the commuted order.
1608 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1609 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1610 // Consider the commuted order.
1611 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1617 // GenerateVariants - Generate variants. For example, commutative patterns can
1618 // match multiple ways. Add them to PatternsToMatch as well.
1619 void DAGISelEmitter::GenerateVariants() {
1621 DEBUG(std::cerr << "Generating instruction variants.\n");
1623 // Loop over all of the patterns we've collected, checking to see if we can
1624 // generate variants of the instruction, through the exploitation of
1625 // identities. This permits the target to provide agressive matching without
1626 // the .td file having to contain tons of variants of instructions.
1628 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1629 // intentionally do not reconsider these. Any variants of added patterns have
1630 // already been added.
1632 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1633 std::vector<TreePatternNode*> Variants;
1634 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1636 assert(!Variants.empty() && "Must create at least original variant!");
1637 Variants.erase(Variants.begin()); // Remove the original pattern.
1639 if (Variants.empty()) // No variants for this pattern.
1642 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1643 PatternsToMatch[i].getSrcPattern()->dump();
1646 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1647 TreePatternNode *Variant = Variants[v];
1649 DEBUG(std::cerr << " VAR#" << v << ": ";
1653 // Scan to see if an instruction or explicit pattern already matches this.
1654 bool AlreadyExists = false;
1655 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1656 // Check to see if this variant already exists.
1657 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1658 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1659 AlreadyExists = true;
1663 // If we already have it, ignore the variant.
1664 if (AlreadyExists) continue;
1666 // Otherwise, add it to the list of patterns we have.
1668 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1669 Variant, PatternsToMatch[i].getDstPattern()));
1672 DEBUG(std::cerr << "\n");
1677 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1679 static bool NodeIsComplexPattern(TreePatternNode *N)
1681 return (N->isLeaf() &&
1682 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1683 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1684 isSubClassOf("ComplexPattern"));
1687 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1688 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1689 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1690 DAGISelEmitter &ISE)
1693 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1694 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1695 isSubClassOf("ComplexPattern")) {
1696 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1702 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1703 /// patterns before small ones. This is used to determine the size of a
1705 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1706 assert(isExtIntegerInVTs(P->getExtTypes()) ||
1707 isExtFloatingPointInVTs(P->getExtTypes()) ||
1708 P->getExtTypeNum(0) == MVT::isVoid ||
1709 P->getExtTypeNum(0) == MVT::Flag &&
1710 "Not a valid pattern node to size!");
1711 unsigned Size = 2; // The node itself.
1713 // FIXME: This is a hack to statically increase the priority of patterns
1714 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1715 // Later we can allow complexity / cost for each pattern to be (optionally)
1716 // specified. To get best possible pattern match we'll need to dynamically
1717 // calculate the complexity of all patterns a dag can potentially map to.
1718 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1720 Size += AM->getNumOperands() * 2;
1722 // Count children in the count if they are also nodes.
1723 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1724 TreePatternNode *Child = P->getChild(i);
1725 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1726 Size += getPatternSize(Child, ISE);
1727 else if (Child->isLeaf()) {
1728 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1729 Size += 3; // Matches a ConstantSDNode.
1730 else if (NodeIsComplexPattern(Child))
1731 Size += getPatternSize(Child, ISE);
1738 /// getResultPatternCost - Compute the number of instructions for this pattern.
1739 /// This is a temporary hack. We should really include the instruction
1740 /// latencies in this calculation.
1741 static unsigned getResultPatternCost(TreePatternNode *P) {
1742 if (P->isLeaf()) return 0;
1744 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1745 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1746 Cost += getResultPatternCost(P->getChild(i));
1750 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1751 // In particular, we want to match maximal patterns first and lowest cost within
1752 // a particular complexity first.
1753 struct PatternSortingPredicate {
1754 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1755 DAGISelEmitter &ISE;
1757 bool operator()(PatternToMatch *LHS,
1758 PatternToMatch *RHS) {
1759 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1760 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1761 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1762 if (LHSSize < RHSSize) return false;
1764 // If the patterns have equal complexity, compare generated instruction cost
1765 return getResultPatternCost(LHS->getDstPattern()) <
1766 getResultPatternCost(RHS->getDstPattern());
1770 /// getRegisterValueType - Look up and return the first ValueType of specified
1771 /// RegisterClass record
1772 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1773 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1774 return RC->getValueTypeNum(0);
1779 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1780 /// type information from it.
1781 static void RemoveAllTypes(TreePatternNode *N) {
1784 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1785 RemoveAllTypes(N->getChild(i));
1788 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1789 Record *N = Records.getDef(Name);
1790 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1794 /// NodeHasProperty - return true if TreePatternNode has the specified
1796 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1797 DAGISelEmitter &ISE)
1799 if (N->isLeaf()) return false;
1800 Record *Operator = N->getOperator();
1801 if (!Operator->isSubClassOf("SDNode")) return false;
1803 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1804 return NodeInfo.hasProperty(Property);
1807 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1808 DAGISelEmitter &ISE)
1810 if (NodeHasProperty(N, Property, ISE))
1813 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1814 TreePatternNode *Child = N->getChild(i);
1815 if (PatternHasProperty(Child, Property, ISE))
1822 class PatternCodeEmitter {
1824 DAGISelEmitter &ISE;
1827 ListInit *Predicates;
1828 // Instruction selector pattern.
1829 TreePatternNode *Pattern;
1830 // Matched instruction.
1831 TreePatternNode *Instruction;
1833 // Node to name mapping
1834 std::map<std::string, std::string> VariableMap;
1835 // Node to operator mapping
1836 std::map<std::string, Record*> OperatorMap;
1837 // Names of all the folded nodes which produce chains.
1838 std::vector<std::pair<std::string, unsigned> > FoldedChains;
1839 std::set<std::string> Duplicates;
1841 /// GeneratedCode - This is the buffer that we emit code to. The first bool
1842 /// indicates whether this is an exit predicate (something that should be
1843 /// tested, and if true, the match fails) [when true] or normal code to emit
1845 std::vector<std::pair<bool, std::string> > &GeneratedCode;
1849 void emitCheck(const std::string &S) {
1851 GeneratedCode.push_back(std::make_pair(true, S));
1853 void emitCode(const std::string &S) {
1855 GeneratedCode.push_back(std::make_pair(false, S));
1858 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1859 TreePatternNode *pattern, TreePatternNode *instr,
1860 std::vector<std::pair<bool, std::string> > &gc)
1861 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
1862 GeneratedCode(gc), TmpNo(0) {}
1864 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1865 /// if the match fails. At this point, we already know that the opcode for N
1866 /// matches, and the SDNode for the result has the RootName specified name.
1867 void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
1868 bool &FoundChain, bool isRoot = false) {
1870 // Emit instruction predicates. Each predicate is just a string for now.
1872 std::string PredicateCheck;
1873 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1874 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1875 Record *Def = Pred->getDef();
1876 if (!Def->isSubClassOf("Predicate")) {
1878 assert(0 && "Unknown predicate type!");
1880 if (!PredicateCheck.empty())
1881 PredicateCheck += " || ";
1882 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
1886 emitCheck(PredicateCheck);
1890 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1891 emitCheck("cast<ConstantSDNode>(" + RootName +
1892 ")->getSignExtended() == " + itostr(II->getValue()));
1894 } else if (!NodeIsComplexPattern(N)) {
1895 assert(0 && "Cannot match this as a leaf value!");
1900 // If this node has a name associated with it, capture it in VariableMap. If
1901 // we already saw this in the pattern, emit code to verify dagness.
1902 if (!N->getName().empty()) {
1903 std::string &VarMapEntry = VariableMap[N->getName()];
1904 if (VarMapEntry.empty()) {
1905 VarMapEntry = RootName;
1907 // If we get here, this is a second reference to a specific name. Since
1908 // we already have checked that the first reference is valid, we don't
1909 // have to recursively match it, just check that it's the same as the
1910 // previously named thing.
1911 emitCheck(VarMapEntry + " == " + RootName);
1916 OperatorMap[N->getName()] = N->getOperator();
1920 // Emit code to load the child nodes and match their contents recursively.
1922 bool NodeHasChain = NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
1923 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
1924 bool EmittedUseCheck = false;
1925 bool EmittedSlctedCheck = false;
1930 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
1931 // Multiple uses of actual result?
1932 emitCheck(RootName + ".hasOneUse()");
1933 EmittedUseCheck = true;
1934 // hasOneUse() check is not strong enough. If the original node has
1935 // already been selected, it may have been replaced with another.
1936 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
1937 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
1940 EmittedSlctedCheck = true;
1942 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" +
1943 utostr(CInfo.getNumResults()) + "))");
1947 emitCode("SDOperand Chain = " + RootName + ".getOperand(0);");
1950 emitCheck("Chain.Val == " + RootName + ".Val");
1951 emitCode("Chain = " + RootName + ".getOperand(0);");
1956 // Don't fold any node which reads or writes a flag and has multiple uses.
1957 // FIXME: we really need to separate the concepts of flag and "glue". Those
1958 // real flag results, e.g. X86CMP output, can have multiple uses.
1959 // FIXME: If the incoming flag is optional. Then it is ok to fold it.
1961 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
1962 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
1963 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
1964 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
1965 if (!EmittedUseCheck) {
1966 // Multiple uses of actual result?
1967 emitCheck(RootName + ".hasOneUse()");
1969 if (!EmittedSlctedCheck)
1970 // hasOneUse() check is not strong enough. If the original node has
1971 // already been selected, it may have been replaced with another.
1972 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
1973 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
1977 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1978 emitCode("SDOperand " + RootName + utostr(OpNo) + " = " +
1979 RootName + ".getOperand(" +utostr(OpNo) + ");");
1980 TreePatternNode *Child = N->getChild(i);
1982 if (!Child->isLeaf()) {
1983 // If it's not a leaf, recursively match.
1984 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1985 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
1986 CInfo.getEnumName());
1987 EmitMatchCode(Child, RootName + utostr(OpNo), FoundChain);
1988 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
1989 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
1990 CInfo.getNumResults()));
1992 // If this child has a name associated with it, capture it in VarMap. If
1993 // we already saw this in the pattern, emit code to verify dagness.
1994 if (!Child->getName().empty()) {
1995 std::string &VarMapEntry = VariableMap[Child->getName()];
1996 if (VarMapEntry.empty()) {
1997 VarMapEntry = RootName + utostr(OpNo);
1999 // If we get here, this is a second reference to a specific name.
2000 // Since we already have checked that the first reference is valid,
2001 // we don't have to recursively match it, just check that it's the
2002 // same as the previously named thing.
2003 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2004 Duplicates.insert(RootName + utostr(OpNo));
2009 // Handle leaves of various types.
2010 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2011 Record *LeafRec = DI->getDef();
2012 if (LeafRec->isSubClassOf("RegisterClass")) {
2013 // Handle register references. Nothing to do here.
2014 } else if (LeafRec->isSubClassOf("Register")) {
2015 // Handle register references.
2016 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2017 // Handle complex pattern. Nothing to do here.
2018 } else if (LeafRec->getName() == "srcvalue") {
2019 // Place holder for SRCVALUE nodes. Nothing to do here.
2020 } else if (LeafRec->isSubClassOf("ValueType")) {
2021 // Make sure this is the specified value type.
2022 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2023 ")->getVT() == MVT::" + LeafRec->getName());
2024 } else if (LeafRec->isSubClassOf("CondCode")) {
2025 // Make sure this is the specified cond code.
2026 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2027 ")->get() == ISD::" + LeafRec->getName());
2031 assert(0 && "Unknown leaf type!");
2033 } else if (IntInit *II =
2034 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2035 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) +
2036 ") && cast<ConstantSDNode>(" + RootName + utostr(OpNo) +
2037 ")->getSignExtended() == " + itostr(II->getValue()));
2040 assert(0 && "Unknown leaf type!");
2045 // If there is a node predicate for this, emit the call.
2046 if (!N->getPredicateFn().empty())
2047 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2050 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2051 /// we actually have to build a DAG!
2052 std::pair<unsigned, unsigned>
2053 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
2054 // This is something selected from the pattern we matched.
2055 if (!N->getName().empty()) {
2056 assert(!isRoot && "Root of pattern cannot be a leaf!");
2057 std::string &Val = VariableMap[N->getName()];
2058 assert(!Val.empty() &&
2059 "Variable referenced but not defined and not caught earlier!");
2060 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2061 // Already selected this operand, just return the tmpval.
2062 return std::make_pair(1, atoi(Val.c_str()+3));
2065 const ComplexPattern *CP;
2066 unsigned ResNo = TmpNo++;
2067 unsigned NumRes = 1;
2068 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2069 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2071 switch (N->getTypeNum(0)) {
2072 default: assert(0 && "Unknown type for constant node!");
2073 case MVT::i1: Code = "bool Tmp"; break;
2074 case MVT::i8: Code = "unsigned char Tmp"; break;
2075 case MVT::i16: Code = "unsigned short Tmp"; break;
2076 case MVT::i32: Code = "unsigned Tmp"; break;
2077 case MVT::i64: Code = "uint64_t Tmp"; break;
2079 emitCode(Code + utostr(ResNo) + "C = (unsigned)cast<ConstantSDNode>(" +
2080 Val + ")->getValue();");
2081 emitCode("SDOperand Tmp" + utostr(ResNo) +
2082 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
2083 "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2084 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2085 Record *Op = OperatorMap[N->getName()];
2086 // Transform ExternalSymbol to TargetExternalSymbol
2087 if (Op && Op->getName() == "externalsym") {
2088 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2089 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2090 Val + ")->getSymbol(), MVT::" +
2091 getEnumName(N->getTypeNum(0)) + ");");
2093 emitCode("SDOperand Tmp" + utostr(ResNo) + " = " + Val + ";");
2095 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2096 Record *Op = OperatorMap[N->getName()];
2097 // Transform GlobalAddress to TargetGlobalAddress
2098 if (Op && Op->getName() == "globaladdr") {
2099 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2100 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2101 ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2104 emitCode("SDOperand Tmp" + utostr(ResNo) + " = " + Val + ";");
2106 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2107 emitCode("SDOperand Tmp" + utostr(ResNo) + " = " + Val + ";");
2108 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2109 emitCode("SDOperand Tmp" + utostr(ResNo) + " = " + Val + ";");
2110 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2111 std::string Fn = CP->getSelectFunc();
2112 NumRes = CP->getNumOperands();
2113 std::string Code = "SDOperand ";
2114 for (unsigned i = 0; i < NumRes - 1; ++i)
2115 Code += "Tmp" + utostr(i+ResNo) + ", ";
2116 emitCode(Code + "Tmp" + utostr(NumRes - 1 + ResNo) + ";");
2118 Code = Fn + "(" + Val;
2119 for (unsigned i = 0; i < NumRes; i++)
2120 Code += ", Tmp" + utostr(i + ResNo);
2121 emitCheck(Code + ")");
2122 TmpNo = ResNo + NumRes;
2124 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Select(" + Val + ");");
2126 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2127 // value if used multiple times by this pattern result.
2128 Val = "Tmp"+utostr(ResNo);
2129 return std::make_pair(NumRes, ResNo);
2133 // If this is an explicit register reference, handle it.
2134 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2135 unsigned ResNo = TmpNo++;
2136 if (DI->getDef()->isSubClassOf("Register")) {
2137 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2138 ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2139 getEnumName(N->getTypeNum(0)) + ");");
2140 return std::make_pair(1, ResNo);
2142 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2143 unsigned ResNo = TmpNo++;
2144 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2145 emitCode("SDOperand Tmp" + utostr(ResNo) +
2146 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2147 ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2148 return std::make_pair(1, ResNo);
2152 assert(0 && "Unknown leaf type!");
2153 return std::make_pair(1, ~0U);
2156 Record *Op = N->getOperator();
2157 if (Op->isSubClassOf("Instruction")) {
2158 const CodeGenTarget &CGT = ISE.getTargetInfo();
2159 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2160 const DAGInstruction &Inst = ISE.getInstruction(Op);
2161 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2162 bool HasImpResults = Inst.getNumImpResults() > 0;
2163 bool HasOptInFlag = isRoot &&
2164 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2165 bool HasInFlag = isRoot &&
2166 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2167 bool NodeHasOutFlag = HasImpResults ||
2168 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2170 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2171 bool HasChain = II.hasCtrlDep ||
2172 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
2174 if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
2175 emitCode("SDOperand InFlag = SDOperand(0, 0);");
2177 emitCode("bool HasOptInFlag = false;");
2179 // How many results is this pattern expected to produce?
2180 unsigned NumExpectedResults = 0;
2181 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2182 MVT::ValueType VT = Pattern->getTypeNum(i);
2183 if (VT != MVT::isVoid && VT != MVT::Flag)
2184 NumExpectedResults++;
2187 // Determine operand emission order. Complex pattern first.
2188 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2189 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2190 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2191 TreePatternNode *Child = N->getChild(i);
2193 EmitOrder.push_back(std::make_pair(i, Child));
2194 OI = EmitOrder.begin();
2195 } else if (NodeIsComplexPattern(Child)) {
2196 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2198 EmitOrder.push_back(std::make_pair(i, Child));
2202 // Emit all of the operands.
2203 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2204 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2205 unsigned OpOrder = EmitOrder[i].first;
2206 TreePatternNode *Child = EmitOrder[i].second;
2207 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2208 NumTemps[OpOrder] = NumTemp;
2211 // List all the operands in the right order.
2212 std::vector<unsigned> Ops;
2213 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2214 for (unsigned j = 0; j < NumTemps[i].first; j++)
2215 Ops.push_back(NumTemps[i].second + j);
2218 // Emit all the chain and CopyToReg stuff.
2219 bool ChainEmitted = HasChain;
2221 emitCode("Chain = Select(Chain);");
2222 if (HasInFlag || HasOptInFlag || HasImpInputs)
2223 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
2225 unsigned NumResults = Inst.getNumResults();
2226 unsigned ResNo = TmpNo++;
2229 "SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTargetNode(" +
2230 II.Namespace + "::" + II.TheDef->getName();
2231 if (N->getTypeNum(0) != MVT::isVoid)
2232 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2234 Code += ", MVT::Flag";
2236 unsigned LastOp = 0;
2237 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2239 Code += ", Tmp" + utostr(LastOp);
2241 emitCode(Code + ");");
2243 // Must have at least one result
2244 emitCode("Chain = Tmp" + utostr(LastOp) + ".getValue(" +
2245 utostr(NumResults) + ");");
2247 } else if (HasChain || NodeHasOutFlag) {
2249 emitCode("SDOperand Result = SDOperand(0, 0);");
2250 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
2251 emitCode("if (HasOptInFlag)");
2252 std::string Code = " Result = CurDAG->getTargetNode(" +
2253 II.Namespace + "::" + II.TheDef->getName();
2255 // Output order: results, chain, flags
2257 if (NumResults > 0) {
2258 if (N->getTypeNum(0) != MVT::isVoid)
2259 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2262 Code += ", MVT::Other";
2264 Code += ", MVT::Flag";
2267 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2268 Code += ", Tmp" + utostr(Ops[i]);
2269 if (HasChain) Code += ", Chain";
2270 emitCode(Code + ", InFlag);");
2273 Code = " Result = CurDAG->getTargetNode(" + II.Namespace + "::" +
2274 II.TheDef->getName();
2276 // Output order: results, chain, flags
2278 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2279 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2281 Code += ", MVT::Other";
2283 Code += ", MVT::Flag";
2286 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2287 Code += ", Tmp" + utostr(Ops[i]);
2288 if (HasChain) Code += ", Chain);";
2291 std::string Code = "SDOperand Result = CurDAG->getTargetNode(" +
2292 II.Namespace + "::" + II.TheDef->getName();
2294 // Output order: results, chain, flags
2296 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2297 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2299 Code += ", MVT::Other";
2301 Code += ", MVT::Flag";
2304 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2305 Code += ", Tmp" + utostr(Ops[i]);
2306 if (HasChain) Code += ", Chain";
2307 if (HasInFlag || HasImpInputs) Code += ", InFlag";
2308 emitCode(Code + ");");
2312 for (unsigned i = 0; i < NumResults; i++) {
2313 emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = Result"
2314 ".getValue(" + utostr(ValNo) + ");");
2319 emitCode("Chain = Result.getValue(" + utostr(ValNo) + ");");
2322 emitCode("InFlag = Result.getValue(" +
2323 utostr(ValNo + (unsigned)HasChain) + ");");
2325 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2326 emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = "
2327 "Result.getValue(" + utostr(ValNo) + ");");
2331 // User does not expect that the instruction produces a chain!
2332 bool AddedChain = HasChain && !NodeHasChain;
2334 emitCode("CodeGenMap[N.getValue(" + utostr(ValNo++) + ")] = Chain;");
2336 if (FoldedChains.size() > 0) {
2338 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2339 Code += "CodeGenMap[" + FoldedChains[j].first + ".getValue(" +
2340 utostr(FoldedChains[j].second) + ")] = ";
2341 emitCode(Code + "Chain;");
2345 emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = InFlag;");
2347 if (AddedChain && NodeHasOutFlag) {
2348 if (NumExpectedResults == 0) {
2349 emitCode("return Result.getValue(N.ResNo+1);");
2351 emitCode("if (N.ResNo < " + utostr(NumExpectedResults) + ")");
2352 emitCode(" return Result.getValue(N.ResNo);");
2354 emitCode(" return Result.getValue(N.ResNo+1);");
2357 emitCode("return Result.getValue(N.ResNo);");
2360 // If this instruction is the root, and if there is only one use of it,
2361 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2362 emitCode("if (N.Val->hasOneUse()) {");
2363 std::string Code = " return CurDAG->SelectNodeTo(N.Val, " +
2364 II.Namespace + "::" + II.TheDef->getName();
2365 if (N->getTypeNum(0) != MVT::isVoid)
2366 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2368 Code += ", MVT::Flag";
2369 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2370 Code += ", Tmp" + utostr(Ops[i]);
2371 if (HasInFlag || HasImpInputs)
2373 emitCode(Code + ");");
2374 emitCode("} else {");
2375 Code = " return CodeGenMap[N] = CurDAG->getTargetNode(" +
2376 II.Namespace + "::" + II.TheDef->getName();
2377 if (N->getTypeNum(0) != MVT::isVoid)
2378 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2380 Code += ", MVT::Flag";
2381 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2382 Code += ", Tmp" + utostr(Ops[i]);
2383 if (HasInFlag || HasImpInputs)
2385 emitCode(Code + ");");
2389 return std::make_pair(1, ResNo);
2390 } else if (Op->isSubClassOf("SDNodeXForm")) {
2391 assert(N->getNumChildren() == 1 && "node xform should have one child!");
2392 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
2393 unsigned ResNo = TmpNo++;
2394 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2395 + "(Tmp" + utostr(OpVal) + ".Val);");
2397 emitCode("CodeGenMap[N] = Tmp" +utostr(ResNo) + ";");
2398 emitCode("return Tmp" + utostr(ResNo) + ";");
2400 return std::make_pair(1, ResNo);
2404 throw std::string("Unknown node in result pattern!");
2408 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2409 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2410 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2411 /// for, this returns true otherwise false if Pat has all types.
2412 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2413 const std::string &Prefix) {
2415 if (!Pat->hasTypeSet()) {
2416 // Move a type over from 'other' to 'pat'.
2417 Pat->setTypes(Other->getExtTypes());
2418 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
2419 getName(Pat->getTypeNum(0)));
2424 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2425 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2426 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2427 Prefix + utostr(OpNo)))
2433 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2435 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2436 bool &ChainEmitted, bool isRoot = false) {
2437 const CodeGenTarget &T = ISE.getTargetInfo();
2439 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2440 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2441 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
2442 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2443 TreePatternNode *Child = N->getChild(i);
2444 if (!Child->isLeaf()) {
2445 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
2447 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2448 if (!Child->getName().empty()) {
2449 std::string Name = RootName + utostr(OpNo);
2450 if (Duplicates.find(Name) != Duplicates.end())
2451 // A duplicate! Do not emit a copy for this node.
2455 Record *RR = DI->getDef();
2456 if (RR->isSubClassOf("Register")) {
2457 MVT::ValueType RVT = getRegisterValueType(RR, T);
2458 if (RVT == MVT::Flag) {
2459 emitCode("InFlag = Select(" + RootName + utostr(OpNo) + ");");
2461 if (!ChainEmitted) {
2462 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
2463 ChainEmitted = true;
2465 emitCode("SDOperand " + RootName + "CR" + utostr(i) + ";");
2466 emitCode(RootName + "CR" + utostr(i) +
2467 " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(" +
2468 ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
2469 "), Select(" + RootName + utostr(OpNo) + "), InFlag);");
2470 emitCode("Chain = " + RootName + "CR" + utostr(i) +
2472 emitCode("InFlag = " + RootName + "CR" + utostr(i) +
2480 if (HasInFlag || HasOptInFlag) {
2483 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2487 emitCode(Code + "InFlag = Select(" + RootName + ".getOperand(" +
2488 utostr(OpNo) + "));");
2490 emitCode(" HasOptInFlag = true;");
2496 /// EmitCopyFromRegs - Emit code to copy result to physical registers
2497 /// as specified by the instruction. It returns true if any copy is
2499 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
2500 bool RetVal = false;
2501 Record *Op = N->getOperator();
2502 if (Op->isSubClassOf("Instruction")) {
2503 const DAGInstruction &Inst = ISE.getInstruction(Op);
2504 const CodeGenTarget &CGT = ISE.getTargetInfo();
2505 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2506 unsigned NumImpResults = Inst.getNumImpResults();
2507 for (unsigned i = 0; i < NumImpResults; i++) {
2508 Record *RR = Inst.getImpResult(i);
2509 if (RR->isSubClassOf("Register")) {
2510 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2511 if (RVT != MVT::Flag) {
2512 if (!ChainEmitted) {
2513 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
2514 ChainEmitted = true;
2516 emitCode("Result = CurDAG->getCopyFromReg(Chain, " +
2517 ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
2519 emitCode("Chain = Result.getValue(1);");
2520 emitCode("InFlag = Result.getValue(2);");
2530 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2531 /// stream to match the pattern, and generate the code for the match if it
2532 /// succeeds. Returns true if the pattern is not guaranteed to match.
2533 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2534 std::vector<std::pair<bool, std::string> > &GeneratedCode) {
2535 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2536 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2539 // Emit the matcher, capturing named arguments in VariableMap.
2540 bool FoundChain = false;
2541 Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", FoundChain,
2544 // TP - Get *SOME* tree pattern, we don't care which.
2545 TreePattern &TP = *PatternFragments.begin()->second;
2547 // At this point, we know that we structurally match the pattern, but the
2548 // types of the nodes may not match. Figure out the fewest number of type
2549 // comparisons we need to emit. For example, if there is only one integer
2550 // type supported by a target, there should be no type comparisons at all for
2551 // integer patterns!
2553 // To figure out the fewest number of type checks needed, clone the pattern,
2554 // remove the types, then perform type inference on the pattern as a whole.
2555 // If there are unresolved types, emit an explicit check for those types,
2556 // apply the type to the tree, then rerun type inference. Iterate until all
2557 // types are resolved.
2559 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2560 RemoveAllTypes(Pat);
2563 // Resolve/propagate as many types as possible.
2565 bool MadeChange = true;
2567 MadeChange = Pat->ApplyTypeConstraints(TP,
2568 true/*Ignore reg constraints*/);
2570 assert(0 && "Error: could not find consistent types for something we"
2571 " already decided was ok!");
2575 // Insert a check for an unresolved type and add it to the tree. If we find
2576 // an unresolved type to add a check for, this returns true and we iterate,
2577 // otherwise we are done.
2578 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2580 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
2586 /// CompareByRecordName - An ordering predicate that implements less-than by
2587 /// comparing the names records.
2588 struct CompareByRecordName {
2589 bool operator()(const Record *LHS, const Record *RHS) const {
2590 // Sort by name first.
2591 if (LHS->getName() < RHS->getName()) return true;
2592 // If both names are equal, sort by pointer.
2593 return LHS->getName() == RHS->getName() && LHS < RHS;
2598 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
2599 std::string InstNS = Target.inst_begin()->second.Namespace;
2600 if (!InstNS.empty()) InstNS += "::";
2602 // Group the patterns by their top-level opcodes.
2603 std::map<Record*, std::vector<PatternToMatch*>,
2604 CompareByRecordName> PatternsByOpcode;
2605 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2606 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2607 if (!Node->isLeaf()) {
2608 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2610 const ComplexPattern *CP;
2612 dynamic_cast<IntInit*>(Node->getLeafValue())) {
2613 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2614 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2615 std::vector<Record*> OpNodes = CP->getRootNodes();
2616 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2617 PatternsByOpcode[OpNodes[j]]
2618 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
2621 std::cerr << "Unrecognized opcode '";
2623 std::cerr << "' on tree pattern '";
2625 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
2626 std::cerr << "'!\n";
2632 // Emit one Select_* method for each top-level opcode. We do this instead of
2633 // emitting one giant switch statement to support compilers where this will
2634 // result in the recursive functions taking less stack space.
2635 for (std::map<Record*, std::vector<PatternToMatch*>,
2636 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2637 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2638 OS << "SDOperand Select_" << PBOI->first->getName() << "(SDOperand N) {\n";
2640 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2641 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2642 assert(!Patterns.empty() && "No patterns but map has entry?");
2644 // We want to emit all of the matching code now. However, we want to emit
2645 // the matches in order of minimal cost. Sort the patterns so the least
2646 // cost one is at the start.
2647 std::stable_sort(Patterns.begin(), Patterns.end(),
2648 PatternSortingPredicate(*this));
2650 bool mightNotMatch = true;
2651 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2652 PatternToMatch &Pattern = *Patterns[i];
2653 std::vector<std::pair<bool, std::string> > GeneratedCode;
2654 EmitCodeForPattern(Pattern, GeneratedCode);
2656 static unsigned PatternCount = 0;
2657 unsigned PatternNo = PatternCount++;
2659 OS << " { // Pattern #" << PatternNo << ": ";
2660 Pattern.getSrcPattern()->print(OS);
2661 OS << "\n // Emits: ";
2662 Pattern.getDstPattern()->print(OS);
2664 OS << " // Pattern complexity = "
2665 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
2666 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
2668 // Actually output the generated code now.
2669 mightNotMatch = false;
2670 unsigned Indent = 4;
2671 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
2672 if (!GeneratedCode[j].first) {
2674 OS << std::string(Indent, ' ') << GeneratedCode[j].second << "\n";
2676 mightNotMatch = true;
2677 OS << std::string(Indent, ' ')
2678 << "if (" << GeneratedCode[j].second << ") {\n";
2682 for (; Indent != 4; Indent -= 2)
2683 OS << std::string(Indent-2, ' ') << "}\n";
2687 if (!mightNotMatch && i != Patterns.size()-1) {
2688 std::cerr << "Pattern "
2689 << Patterns[i+1]->getDstPattern()->getOperator()->getName()
2690 << " is impossible to select!\n";
2696 OS << " std::cerr << \"Cannot yet select: \";\n"
2697 << " N.Val->dump(CurDAG);\n"
2698 << " std::cerr << '\\n';\n"
2704 // Emit boilerplate.
2705 OS << "SDOperand Select_INLINEASM(SDOperand N) {\n"
2706 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
2707 << " Ops[0] = Select(N.getOperand(0)); // Select the chain.\n\n"
2708 << " // Select the flag operand.\n"
2709 << " if (Ops.back().getValueType() == MVT::Flag)\n"
2710 << " Ops.back() = Select(Ops.back());\n"
2711 << " std::vector<MVT::ValueType> VTs;\n"
2712 << " VTs.push_back(MVT::Other);\n"
2713 << " VTs.push_back(MVT::Flag);\n"
2714 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
2715 << " CodeGenMap[N.getValue(0)] = New;\n"
2716 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2717 << " return New.getValue(N.ResNo);\n"
2720 OS << "// The main instruction selector code.\n"
2721 << "SDOperand SelectCode(SDOperand N) {\n"
2722 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
2723 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2724 << "INSTRUCTION_LIST_END))\n"
2725 << " return N; // Already selected.\n\n"
2726 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
2727 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
2728 << " switch (N.getOpcode()) {\n"
2729 << " default: break;\n"
2730 << " case ISD::EntryToken: // These leaves remain the same.\n"
2731 << " case ISD::BasicBlock:\n"
2732 << " case ISD::Register:\n"
2734 << " case ISD::AssertSext:\n"
2735 << " case ISD::AssertZext: {\n"
2736 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2737 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2738 << " return Tmp0;\n"
2740 << " case ISD::TokenFactor:\n"
2741 << " if (N.getNumOperands() == 2) {\n"
2742 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2743 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2744 << " return CodeGenMap[N] =\n"
2745 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2747 << " std::vector<SDOperand> Ops;\n"
2748 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2749 << " Ops.push_back(Select(N.getOperand(i)));\n"
2750 << " return CodeGenMap[N] = \n"
2751 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2753 << " case ISD::CopyFromReg: {\n"
2754 << " SDOperand Chain = Select(N.getOperand(0));\n"
2755 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2756 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
2757 << " if (N.Val->getNumValues() == 2) {\n"
2758 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2759 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
2760 << " CodeGenMap[N.getValue(0)] = New;\n"
2761 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2762 << " return New.getValue(N.ResNo);\n"
2764 << " SDOperand Flag(0, 0);\n"
2765 << " if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
2766 << " if (Chain == N.getOperand(0) &&\n"
2767 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
2768 << " return N; // No change\n"
2769 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
2770 << " CodeGenMap[N.getValue(0)] = New;\n"
2771 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2772 << " CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
2773 << " return New.getValue(N.ResNo);\n"
2776 << " case ISD::CopyToReg: {\n"
2777 << " SDOperand Chain = Select(N.getOperand(0));\n"
2778 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2779 << " SDOperand Val = Select(N.getOperand(2));\n"
2780 << " SDOperand Result = N;\n"
2781 << " if (N.Val->getNumValues() == 1) {\n"
2782 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
2783 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
2784 << " return CodeGenMap[N] = Result;\n"
2786 << " SDOperand Flag(0, 0);\n"
2787 << " if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
2788 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
2789 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
2790 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
2791 << " CodeGenMap[N.getValue(0)] = Result;\n"
2792 << " CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
2793 << " return Result.getValue(N.ResNo);\n"
2796 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n";
2799 // Loop over all of the case statements, emiting a call to each method we
2801 for (std::map<Record*, std::vector<PatternToMatch*>,
2802 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2803 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2804 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2805 OS << " case " << OpcodeInfo.getEnumName() << ": "
2806 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
2807 << "return Select_" << PBOI->first->getName() << "(N);\n";
2810 OS << " } // end of big switch.\n\n"
2811 << " std::cerr << \"Cannot yet select: \";\n"
2812 << " N.Val->dump(CurDAG);\n"
2813 << " std::cerr << '\\n';\n"
2818 void DAGISelEmitter::run(std::ostream &OS) {
2819 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2822 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2823 << "// *** instruction selector class. These functions are really "
2826 OS << "// Instance var to keep track of multiply used nodes that have \n"
2827 << "// already been selected.\n"
2828 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2831 ParseNodeTransforms(OS);
2832 ParseComplexPatterns();
2833 ParsePatternFragments(OS);
2834 ParseInstructions();
2837 // Generate variants. For example, commutative patterns can match
2838 // multiple ways. Add them to PatternsToMatch as well.
2842 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2843 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2844 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
2845 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
2849 // At this point, we have full information about the 'Patterns' we need to
2850 // parse, both implicitly from instructions as well as from explicit pattern
2851 // definitions. Emit the resultant instruction selector.
2852 EmitInstructionSelector(OS);
2854 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2855 E = PatternFragments.end(); I != E; ++I)
2857 PatternFragments.clear();
2859 Instructions.clear();