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(const 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(const 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");
106 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
107 ConstraintType = SDTCisIntVectorOfSameSize;
108 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
109 R->getValueAsInt("OtherOpNum");
111 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
116 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
117 /// N, which has NumResults results.
118 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
120 unsigned NumResults) const {
121 assert(NumResults <= 1 &&
122 "We only work with nodes with zero or one result so far!");
124 if (OpNo < NumResults)
125 return N; // FIXME: need value #
127 return N->getChild(OpNo-NumResults);
130 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
131 /// constraint to the nodes operands. This returns true if it makes a
132 /// change, false otherwise. If a type contradiction is found, throw an
134 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
135 const SDNodeInfo &NodeInfo,
136 TreePattern &TP) const {
137 unsigned NumResults = NodeInfo.getNumResults();
138 assert(NumResults <= 1 &&
139 "We only work with nodes with zero or one result so far!");
141 // Check that the number of operands is sane.
142 if (NodeInfo.getNumOperands() >= 0) {
143 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
144 TP.error(N->getOperator()->getName() + " node requires exactly " +
145 itostr(NodeInfo.getNumOperands()) + " operands!");
148 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
150 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
152 switch (ConstraintType) {
153 default: assert(0 && "Unknown constraint type!");
155 // Operand must be a particular type.
156 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
158 // Operand must be same as target pointer type.
159 return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
162 // If there is only one integer type supported, this must be it.
163 std::vector<MVT::ValueType> IntVTs =
164 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
166 // If we found exactly one supported integer type, apply it.
167 if (IntVTs.size() == 1)
168 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
169 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
172 // If there is only one FP type supported, this must be it.
173 std::vector<MVT::ValueType> FPVTs =
174 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
176 // If we found exactly one supported FP type, apply it.
177 if (FPVTs.size() == 1)
178 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
179 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
182 TreePatternNode *OtherNode =
183 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
184 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
185 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
187 case SDTCisVTSmallerThanOp: {
188 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
189 // have an integer type that is smaller than the VT.
190 if (!NodeToApply->isLeaf() ||
191 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
192 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
193 ->isSubClassOf("ValueType"))
194 TP.error(N->getOperator()->getName() + " expects a VT operand!");
196 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
197 if (!MVT::isInteger(VT))
198 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
200 TreePatternNode *OtherNode =
201 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
203 // It must be integer.
204 bool MadeChange = false;
205 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
207 // This code only handles nodes that have one type set. Assert here so
208 // that we can change this if we ever need to deal with multiple value
209 // types at this point.
210 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
211 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
212 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
215 case SDTCisOpSmallerThanOp: {
216 TreePatternNode *BigOperand =
217 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
219 // Both operands must be integer or FP, but we don't care which.
220 bool MadeChange = false;
222 // This code does not currently handle nodes which have multiple types,
223 // where some types are integer, and some are fp. Assert that this is not
225 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
226 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
227 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
228 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
229 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
230 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
231 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
232 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
233 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
234 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
235 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
236 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
237 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
239 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
241 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
242 VTs = FilterVTs(VTs, MVT::isInteger);
243 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
244 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
249 switch (VTs.size()) {
250 default: // Too many VT's to pick from.
251 case 0: break; // No info yet.
253 // Only one VT of this flavor. Cannot ever satisify the constraints.
254 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
256 // If we have exactly two possible types, the little operand must be the
257 // small one, the big operand should be the big one. Common with
258 // float/double for example.
259 assert(VTs[0] < VTs[1] && "Should be sorted!");
260 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
261 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
266 case SDTCisIntVectorOfSameSize: {
267 TreePatternNode *OtherOperand =
268 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
270 if (OtherOperand->hasTypeSet()) {
271 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
272 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
273 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
274 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
275 return NodeToApply->UpdateNodeType(IVT, TP);
284 //===----------------------------------------------------------------------===//
285 // SDNodeInfo implementation
287 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
288 EnumName = R->getValueAsString("Opcode");
289 SDClassName = R->getValueAsString("SDClass");
290 Record *TypeProfile = R->getValueAsDef("TypeProfile");
291 NumResults = TypeProfile->getValueAsInt("NumResults");
292 NumOperands = TypeProfile->getValueAsInt("NumOperands");
294 // Parse the properties.
296 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
297 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
298 if (PropList[i]->getName() == "SDNPCommutative") {
299 Properties |= 1 << SDNPCommutative;
300 } else if (PropList[i]->getName() == "SDNPAssociative") {
301 Properties |= 1 << SDNPAssociative;
302 } else if (PropList[i]->getName() == "SDNPHasChain") {
303 Properties |= 1 << SDNPHasChain;
304 } else if (PropList[i]->getName() == "SDNPOutFlag") {
305 Properties |= 1 << SDNPOutFlag;
306 } else if (PropList[i]->getName() == "SDNPInFlag") {
307 Properties |= 1 << SDNPInFlag;
308 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
309 Properties |= 1 << SDNPOptInFlag;
311 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
312 << "' on node '" << R->getName() << "'!\n";
318 // Parse the type constraints.
319 std::vector<Record*> ConstraintList =
320 TypeProfile->getValueAsListOfDefs("Constraints");
321 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
324 //===----------------------------------------------------------------------===//
325 // TreePatternNode implementation
328 TreePatternNode::~TreePatternNode() {
329 #if 0 // FIXME: implement refcounted tree nodes!
330 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
335 /// UpdateNodeType - Set the node type of N to VT if VT contains
336 /// information. If N already contains a conflicting type, then throw an
337 /// exception. This returns true if any information was updated.
339 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
341 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
343 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
345 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
350 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
351 assert(hasTypeSet() && "should be handled above!");
352 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
353 if (getExtTypes() == FVTs)
358 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
359 assert(hasTypeSet() && "should be handled above!");
360 std::vector<unsigned char> FVTs =
361 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
362 if (getExtTypes() == FVTs)
368 // If we know this is an int or fp type, and we are told it is a specific one,
371 // Similarly, we should probably set the type here to the intersection of
372 // {isInt|isFP} and ExtVTs
373 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
374 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
382 TP.error("Type inference contradiction found in node!");
384 TP.error("Type inference contradiction found in node " +
385 getOperator()->getName() + "!");
387 return true; // unreachable
391 void TreePatternNode::print(std::ostream &OS) const {
393 OS << *getLeafValue();
395 OS << "(" << getOperator()->getName();
398 // FIXME: At some point we should handle printing all the value types for
399 // nodes that are multiply typed.
400 switch (getExtTypeNum(0)) {
401 case MVT::Other: OS << ":Other"; break;
402 case MVT::isInt: OS << ":isInt"; break;
403 case MVT::isFP : OS << ":isFP"; break;
404 case MVT::isUnknown: ; /*OS << ":?";*/ break;
405 default: OS << ":" << getTypeNum(0); break;
409 if (getNumChildren() != 0) {
411 getChild(0)->print(OS);
412 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
414 getChild(i)->print(OS);
420 if (!PredicateFn.empty())
421 OS << "<<P:" << PredicateFn << ">>";
423 OS << "<<X:" << TransformFn->getName() << ">>";
424 if (!getName().empty())
425 OS << ":$" << getName();
428 void TreePatternNode::dump() const {
432 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
433 /// the specified node. For this comparison, all of the state of the node
434 /// is considered, except for the assigned name. Nodes with differing names
435 /// that are otherwise identical are considered isomorphic.
436 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
437 if (N == this) return true;
438 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
439 getPredicateFn() != N->getPredicateFn() ||
440 getTransformFn() != N->getTransformFn())
444 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
445 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
446 return DI->getDef() == NDI->getDef();
447 return getLeafValue() == N->getLeafValue();
450 if (N->getOperator() != getOperator() ||
451 N->getNumChildren() != getNumChildren()) return false;
452 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
453 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
458 /// clone - Make a copy of this tree and all of its children.
460 TreePatternNode *TreePatternNode::clone() const {
461 TreePatternNode *New;
463 New = new TreePatternNode(getLeafValue());
465 std::vector<TreePatternNode*> CChildren;
466 CChildren.reserve(Children.size());
467 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
468 CChildren.push_back(getChild(i)->clone());
469 New = new TreePatternNode(getOperator(), CChildren);
471 New->setName(getName());
472 New->setTypes(getExtTypes());
473 New->setPredicateFn(getPredicateFn());
474 New->setTransformFn(getTransformFn());
478 /// SubstituteFormalArguments - Replace the formal arguments in this tree
479 /// with actual values specified by ArgMap.
480 void TreePatternNode::
481 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
482 if (isLeaf()) return;
484 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
485 TreePatternNode *Child = getChild(i);
486 if (Child->isLeaf()) {
487 Init *Val = Child->getLeafValue();
488 if (dynamic_cast<DefInit*>(Val) &&
489 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
490 // We found a use of a formal argument, replace it with its value.
491 Child = ArgMap[Child->getName()];
492 assert(Child && "Couldn't find formal argument!");
496 getChild(i)->SubstituteFormalArguments(ArgMap);
502 /// InlinePatternFragments - If this pattern refers to any pattern
503 /// fragments, inline them into place, giving us a pattern without any
504 /// PatFrag references.
505 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
506 if (isLeaf()) return this; // nothing to do.
507 Record *Op = getOperator();
509 if (!Op->isSubClassOf("PatFrag")) {
510 // Just recursively inline children nodes.
511 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
512 setChild(i, getChild(i)->InlinePatternFragments(TP));
516 // Otherwise, we found a reference to a fragment. First, look up its
517 // TreePattern record.
518 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
520 // Verify that we are passing the right number of operands.
521 if (Frag->getNumArgs() != Children.size())
522 TP.error("'" + Op->getName() + "' fragment requires " +
523 utostr(Frag->getNumArgs()) + " operands!");
525 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
527 // Resolve formal arguments to their actual value.
528 if (Frag->getNumArgs()) {
529 // Compute the map of formal to actual arguments.
530 std::map<std::string, TreePatternNode*> ArgMap;
531 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
532 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
534 FragTree->SubstituteFormalArguments(ArgMap);
537 FragTree->setName(getName());
538 FragTree->UpdateNodeType(getExtTypes(), TP);
540 // Get a new copy of this fragment to stitch into here.
541 //delete this; // FIXME: implement refcounting!
545 /// getImplicitType - Check to see if the specified record has an implicit
546 /// type which should be applied to it. This infer the type of register
547 /// references from the register file information, for example.
549 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
551 // Some common return values
552 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
553 std::vector<unsigned char> Other(1, MVT::Other);
555 // Check to see if this is a register or a register class...
556 if (R->isSubClassOf("RegisterClass")) {
559 const CodeGenRegisterClass &RC =
560 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
561 return ConvertVTs(RC.getValueTypes());
562 } else if (R->isSubClassOf("PatFrag")) {
563 // Pattern fragment types will be resolved when they are inlined.
565 } else if (R->isSubClassOf("Register")) {
568 // If the register appears in exactly one regclass, and the regclass has one
569 // value type, use it as the known type.
570 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
571 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
572 return ConvertVTs(RC->getValueTypes());
574 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
575 // Using a VTSDNode or CondCodeSDNode.
577 } else if (R->isSubClassOf("ComplexPattern")) {
580 std::vector<unsigned char>
581 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
583 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
588 TP.error("Unknown node flavor used in pattern: " + R->getName());
592 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
593 /// this node and its children in the tree. This returns true if it makes a
594 /// change, false otherwise. If a type contradiction is found, throw an
596 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
597 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
599 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
600 // If it's a regclass or something else known, include the type.
601 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
602 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
603 // Int inits are always integers. :)
604 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
607 // At some point, it may make sense for this tree pattern to have
608 // multiple types. Assert here that it does not, so we revisit this
609 // code when appropriate.
610 assert(getExtTypes().size() == 1 && "TreePattern has too many types!");
612 unsigned Size = MVT::getSizeInBits(getTypeNum(0));
613 // Make sure that the value is representable for this type.
615 int Val = (II->getValue() << (32-Size)) >> (32-Size);
616 if (Val != II->getValue())
617 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
618 "' is out of range for type 'MVT::" +
619 getEnumName(getTypeNum(0)) + "'!");
628 // special handling for set, which isn't really an SDNode.
629 if (getOperator()->getName() == "set") {
630 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
631 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
632 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
634 // Types of operands must match.
635 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
636 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
637 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
639 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
640 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
641 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
643 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
644 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
645 bool MadeChange = false;
647 // Apply the result type to the node.
648 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
650 if (getNumChildren() != Int.ArgVTs.size())
651 TP.error("Intrinsic '" + Int.Name + "' expects " +
652 utostr(Int.ArgVTs.size()-1) + " operands, not " +
653 utostr(getNumChildren()-1) + " operands!");
655 // Apply type info to the intrinsic ID.
656 MVT::ValueType PtrTy = ISE.getTargetInfo().getPointerType();
657 MadeChange |= getChild(0)->UpdateNodeType(PtrTy, TP);
659 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
660 MVT::ValueType OpVT = Int.ArgVTs[i];
661 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
662 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
665 } else if (getOperator()->isSubClassOf("SDNode")) {
666 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
668 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
669 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
670 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
671 // Branch, etc. do not produce results and top-level forms in instr pattern
672 // must have void types.
673 if (NI.getNumResults() == 0)
674 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
676 // If this is a vector_shuffle operation, apply types to the build_vector
677 // operation. The types of the integers don't matter, but this ensures they
678 // won't get checked.
679 if (getOperator()->getName() == "vector_shuffle" &&
680 getChild(2)->getOperator()->getName() == "build_vector") {
681 TreePatternNode *BV = getChild(2);
682 const std::vector<MVT::ValueType> &LegalVTs
683 = ISE.getTargetInfo().getLegalValueTypes();
684 MVT::ValueType LegalIntVT = MVT::Other;
685 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
686 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
687 LegalIntVT = LegalVTs[i];
690 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
692 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
693 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
696 } else if (getOperator()->isSubClassOf("Instruction")) {
697 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
698 bool MadeChange = false;
699 unsigned NumResults = Inst.getNumResults();
701 assert(NumResults <= 1 &&
702 "Only supports zero or one result instrs!");
703 // Apply the result type to the node
704 if (NumResults == 0) {
705 MadeChange = UpdateNodeType(MVT::isVoid, TP);
707 Record *ResultNode = Inst.getResult(0);
708 assert(ResultNode->isSubClassOf("RegisterClass") &&
709 "Operands should be register classes!");
711 const CodeGenRegisterClass &RC =
712 ISE.getTargetInfo().getRegisterClass(ResultNode);
713 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
716 if (getNumChildren() != Inst.getNumOperands())
717 TP.error("Instruction '" + getOperator()->getName() + " expects " +
718 utostr(Inst.getNumOperands()) + " operands, not " +
719 utostr(getNumChildren()) + " operands!");
720 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
721 Record *OperandNode = Inst.getOperand(i);
723 if (OperandNode->isSubClassOf("RegisterClass")) {
724 const CodeGenRegisterClass &RC =
725 ISE.getTargetInfo().getRegisterClass(OperandNode);
726 //VT = RC.getValueTypeNum(0);
727 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
729 } else if (OperandNode->isSubClassOf("Operand")) {
730 VT = getValueType(OperandNode->getValueAsDef("Type"));
731 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
733 assert(0 && "Unknown operand type!");
736 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
740 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
742 // Node transforms always take one operand.
743 if (getNumChildren() != 1)
744 TP.error("Node transform '" + getOperator()->getName() +
745 "' requires one operand!");
747 // If either the output or input of the xform does not have exact
748 // type info. We assume they must be the same. Otherwise, it is perfectly
749 // legal to transform from one type to a completely different type.
750 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
751 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
752 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
759 /// canPatternMatch - If it is impossible for this pattern to match on this
760 /// target, fill in Reason and return false. Otherwise, return true. This is
761 /// used as a santity check for .td files (to prevent people from writing stuff
762 /// that can never possibly work), and to prevent the pattern permuter from
763 /// generating stuff that is useless.
764 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
765 if (isLeaf()) return true;
767 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
768 if (!getChild(i)->canPatternMatch(Reason, ISE))
771 // If this is an intrinsic, handle cases that would make it not match. For
772 // example, if an operand is required to be an immediate.
773 if (getOperator()->isSubClassOf("Intrinsic")) {
778 // If this node is a commutative operator, check that the LHS isn't an
780 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
781 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
782 // Scan all of the operands of the node and make sure that only the last one
783 // is a constant node.
784 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
785 if (!getChild(i)->isLeaf() &&
786 getChild(i)->getOperator()->getName() == "imm") {
787 Reason = "Immediate value must be on the RHS of commutative operators!";
795 //===----------------------------------------------------------------------===//
796 // TreePattern implementation
799 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
800 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
801 isInputPattern = isInput;
802 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
803 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
806 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
807 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
808 isInputPattern = isInput;
809 Trees.push_back(ParseTreePattern(Pat));
812 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
813 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
814 isInputPattern = isInput;
815 Trees.push_back(Pat);
820 void TreePattern::error(const std::string &Msg) const {
822 throw "In " + TheRecord->getName() + ": " + Msg;
825 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
826 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
827 if (!OpDef) error("Pattern has unexpected operator type!");
828 Record *Operator = OpDef->getDef();
830 if (Operator->isSubClassOf("ValueType")) {
831 // If the operator is a ValueType, then this must be "type cast" of a leaf
833 if (Dag->getNumArgs() != 1)
834 error("Type cast only takes one operand!");
836 Init *Arg = Dag->getArg(0);
837 TreePatternNode *New;
838 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
839 Record *R = DI->getDef();
840 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
841 Dag->setArg(0, new DagInit(DI,
842 std::vector<std::pair<Init*, std::string> >()));
843 return ParseTreePattern(Dag);
845 New = new TreePatternNode(DI);
846 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
847 New = ParseTreePattern(DI);
848 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
849 New = new TreePatternNode(II);
850 if (!Dag->getArgName(0).empty())
851 error("Constant int argument should not have a name!");
852 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
853 // Turn this into an IntInit.
854 Init *II = BI->convertInitializerTo(new IntRecTy());
855 if (II == 0 || !dynamic_cast<IntInit*>(II))
856 error("Bits value must be constants!");
858 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
859 if (!Dag->getArgName(0).empty())
860 error("Constant int argument should not have a name!");
863 error("Unknown leaf value for tree pattern!");
867 // Apply the type cast.
868 New->UpdateNodeType(getValueType(Operator), *this);
869 New->setName(Dag->getArgName(0));
873 // Verify that this is something that makes sense for an operator.
874 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
875 !Operator->isSubClassOf("Instruction") &&
876 !Operator->isSubClassOf("SDNodeXForm") &&
877 !Operator->isSubClassOf("Intrinsic") &&
878 Operator->getName() != "set")
879 error("Unrecognized node '" + Operator->getName() + "'!");
881 // Check to see if this is something that is illegal in an input pattern.
882 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
883 Operator->isSubClassOf("SDNodeXForm")))
884 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
886 std::vector<TreePatternNode*> Children;
888 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
889 Init *Arg = Dag->getArg(i);
890 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
891 Children.push_back(ParseTreePattern(DI));
892 if (Children.back()->getName().empty())
893 Children.back()->setName(Dag->getArgName(i));
894 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
895 Record *R = DefI->getDef();
896 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
897 // TreePatternNode if its own.
898 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
899 Dag->setArg(i, new DagInit(DefI,
900 std::vector<std::pair<Init*, std::string> >()));
901 --i; // Revisit this node...
903 TreePatternNode *Node = new TreePatternNode(DefI);
904 Node->setName(Dag->getArgName(i));
905 Children.push_back(Node);
908 if (R->getName() == "node") {
909 if (Dag->getArgName(i).empty())
910 error("'node' argument requires a name to match with operand list");
911 Args.push_back(Dag->getArgName(i));
914 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
915 TreePatternNode *Node = new TreePatternNode(II);
916 if (!Dag->getArgName(i).empty())
917 error("Constant int argument should not have a name!");
918 Children.push_back(Node);
919 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
920 // Turn this into an IntInit.
921 Init *II = BI->convertInitializerTo(new IntRecTy());
922 if (II == 0 || !dynamic_cast<IntInit*>(II))
923 error("Bits value must be constants!");
925 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
926 if (!Dag->getArgName(i).empty())
927 error("Constant int argument should not have a name!");
928 Children.push_back(Node);
933 error("Unknown leaf value for tree pattern!");
937 // If the operator is an intrinsic, then this is just syntactic sugar for for
938 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
939 // convert the intrinsic name to a number.
940 if (Operator->isSubClassOf("Intrinsic")) {
941 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
942 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
944 // If this intrinsic returns void, it must have side-effects and thus a
946 if (Int.ArgVTs[0] == MVT::isVoid) {
947 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
948 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
949 // Has side-effects, requires chain.
950 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
952 // Otherwise, no chain.
953 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
956 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
957 Children.insert(Children.begin(), IIDNode);
960 return new TreePatternNode(Operator, Children);
963 /// InferAllTypes - Infer/propagate as many types throughout the expression
964 /// patterns as possible. Return true if all types are infered, false
965 /// otherwise. Throw an exception if a type contradiction is found.
966 bool TreePattern::InferAllTypes() {
967 bool MadeChange = true;
970 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
971 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
974 bool HasUnresolvedTypes = false;
975 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
976 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
977 return !HasUnresolvedTypes;
980 void TreePattern::print(std::ostream &OS) const {
981 OS << getRecord()->getName();
983 OS << "(" << Args[0];
984 for (unsigned i = 1, e = Args.size(); i != e; ++i)
985 OS << ", " << Args[i];
990 if (Trees.size() > 1)
992 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
998 if (Trees.size() > 1)
1002 void TreePattern::dump() const { print(std::cerr); }
1006 //===----------------------------------------------------------------------===//
1007 // DAGISelEmitter implementation
1010 // Parse all of the SDNode definitions for the target, populating SDNodes.
1011 void DAGISelEmitter::ParseNodeInfo() {
1012 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1013 while (!Nodes.empty()) {
1014 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1018 // Get the buildin intrinsic nodes.
1019 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1020 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1021 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1024 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1025 /// map, and emit them to the file as functions.
1026 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1027 OS << "\n// Node transformations.\n";
1028 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1029 while (!Xforms.empty()) {
1030 Record *XFormNode = Xforms.back();
1031 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1032 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1033 SDNodeXForms.insert(std::make_pair(XFormNode,
1034 std::make_pair(SDNode, Code)));
1036 if (!Code.empty()) {
1037 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1038 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1040 OS << "inline SDOperand Transform_" << XFormNode->getName()
1041 << "(SDNode *" << C2 << ") {\n";
1042 if (ClassName != "SDNode")
1043 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1044 OS << Code << "\n}\n";
1051 void DAGISelEmitter::ParseComplexPatterns() {
1052 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1053 while (!AMs.empty()) {
1054 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1060 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1061 /// file, building up the PatternFragments map. After we've collected them all,
1062 /// inline fragments together as necessary, so that there are no references left
1063 /// inside a pattern fragment to a pattern fragment.
1065 /// This also emits all of the predicate functions to the output file.
1067 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
1068 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1070 // First step, parse all of the fragments and emit predicate functions.
1071 OS << "\n// Predicate functions.\n";
1072 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1073 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1074 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1075 PatternFragments[Fragments[i]] = P;
1077 // Validate the argument list, converting it to map, to discard duplicates.
1078 std::vector<std::string> &Args = P->getArgList();
1079 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1081 if (OperandsMap.count(""))
1082 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1084 // Parse the operands list.
1085 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1086 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1087 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
1088 P->error("Operands list should start with '(ops ... '!");
1090 // Copy over the arguments.
1092 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1093 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1094 static_cast<DefInit*>(OpsList->getArg(j))->
1095 getDef()->getName() != "node")
1096 P->error("Operands list should all be 'node' values.");
1097 if (OpsList->getArgName(j).empty())
1098 P->error("Operands list should have names for each operand!");
1099 if (!OperandsMap.count(OpsList->getArgName(j)))
1100 P->error("'" + OpsList->getArgName(j) +
1101 "' does not occur in pattern or was multiply specified!");
1102 OperandsMap.erase(OpsList->getArgName(j));
1103 Args.push_back(OpsList->getArgName(j));
1106 if (!OperandsMap.empty())
1107 P->error("Operands list does not contain an entry for operand '" +
1108 *OperandsMap.begin() + "'!");
1110 // If there is a code init for this fragment, emit the predicate code and
1111 // keep track of the fact that this fragment uses it.
1112 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1113 if (!Code.empty()) {
1114 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
1115 std::string ClassName =
1116 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1117 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1119 OS << "inline bool Predicate_" << Fragments[i]->getName()
1120 << "(SDNode *" << C2 << ") {\n";
1121 if (ClassName != "SDNode")
1122 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1123 OS << Code << "\n}\n";
1124 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1127 // If there is a node transformation corresponding to this, keep track of
1129 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1130 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1131 P->getOnlyTree()->setTransformFn(Transform);
1136 // Now that we've parsed all of the tree fragments, do a closure on them so
1137 // that there are not references to PatFrags left inside of them.
1138 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1139 E = PatternFragments.end(); I != E; ++I) {
1140 TreePattern *ThePat = I->second;
1141 ThePat->InlinePatternFragments();
1143 // Infer as many types as possible. Don't worry about it if we don't infer
1144 // all of them, some may depend on the inputs of the pattern.
1146 ThePat->InferAllTypes();
1148 // If this pattern fragment is not supported by this target (no types can
1149 // satisfy its constraints), just ignore it. If the bogus pattern is
1150 // actually used by instructions, the type consistency error will be
1154 // If debugging, print out the pattern fragment result.
1155 DEBUG(ThePat->dump());
1159 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1160 /// instruction input. Return true if this is a real use.
1161 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1162 std::map<std::string, TreePatternNode*> &InstInputs,
1163 std::vector<Record*> &InstImpInputs) {
1164 // No name -> not interesting.
1165 if (Pat->getName().empty()) {
1166 if (Pat->isLeaf()) {
1167 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1168 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1169 I->error("Input " + DI->getDef()->getName() + " must be named!");
1170 else if (DI && DI->getDef()->isSubClassOf("Register"))
1171 InstImpInputs.push_back(DI->getDef());
1177 if (Pat->isLeaf()) {
1178 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1179 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1182 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1183 Rec = Pat->getOperator();
1186 // SRCVALUE nodes are ignored.
1187 if (Rec->getName() == "srcvalue")
1190 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1195 if (Slot->isLeaf()) {
1196 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1198 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1199 SlotRec = Slot->getOperator();
1202 // Ensure that the inputs agree if we've already seen this input.
1204 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1205 if (Slot->getExtTypes() != Pat->getExtTypes())
1206 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1211 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1212 /// part of "I", the instruction), computing the set of inputs and outputs of
1213 /// the pattern. Report errors if we see anything naughty.
1214 void DAGISelEmitter::
1215 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1216 std::map<std::string, TreePatternNode*> &InstInputs,
1217 std::map<std::string, TreePatternNode*>&InstResults,
1218 std::vector<Record*> &InstImpInputs,
1219 std::vector<Record*> &InstImpResults) {
1220 if (Pat->isLeaf()) {
1221 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1222 if (!isUse && Pat->getTransformFn())
1223 I->error("Cannot specify a transform function for a non-input value!");
1225 } else if (Pat->getOperator()->getName() != "set") {
1226 // If this is not a set, verify that the children nodes are not void typed,
1228 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1229 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1230 I->error("Cannot have void nodes inside of patterns!");
1231 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1232 InstImpInputs, InstImpResults);
1235 // If this is a non-leaf node with no children, treat it basically as if
1236 // it were a leaf. This handles nodes like (imm).
1238 if (Pat->getNumChildren() == 0)
1239 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1241 if (!isUse && Pat->getTransformFn())
1242 I->error("Cannot specify a transform function for a non-input value!");
1246 // Otherwise, this is a set, validate and collect instruction results.
1247 if (Pat->getNumChildren() == 0)
1248 I->error("set requires operands!");
1249 else if (Pat->getNumChildren() & 1)
1250 I->error("set requires an even number of operands");
1252 if (Pat->getTransformFn())
1253 I->error("Cannot specify a transform function on a set node!");
1255 // Check the set destinations.
1256 unsigned NumValues = Pat->getNumChildren()/2;
1257 for (unsigned i = 0; i != NumValues; ++i) {
1258 TreePatternNode *Dest = Pat->getChild(i);
1259 if (!Dest->isLeaf())
1260 I->error("set destination should be a register!");
1262 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1264 I->error("set destination should be a register!");
1266 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1267 if (Dest->getName().empty())
1268 I->error("set destination must have a name!");
1269 if (InstResults.count(Dest->getName()))
1270 I->error("cannot set '" + Dest->getName() +"' multiple times");
1271 InstResults[Dest->getName()] = Dest;
1272 } else if (Val->getDef()->isSubClassOf("Register")) {
1273 InstImpResults.push_back(Val->getDef());
1275 I->error("set destination should be a register!");
1278 // Verify and collect info from the computation.
1279 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1280 InstInputs, InstResults,
1281 InstImpInputs, InstImpResults);
1285 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1286 /// any fragments involved. This populates the Instructions list with fully
1287 /// resolved instructions.
1288 void DAGISelEmitter::ParseInstructions() {
1289 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1291 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1294 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1295 LI = Instrs[i]->getValueAsListInit("Pattern");
1297 // If there is no pattern, only collect minimal information about the
1298 // instruction for its operand list. We have to assume that there is one
1299 // result, as we have no detailed info.
1300 if (!LI || LI->getSize() == 0) {
1301 std::vector<Record*> Results;
1302 std::vector<Record*> Operands;
1304 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1306 if (InstInfo.OperandList.size() != 0) {
1307 // FIXME: temporary hack...
1308 if (InstInfo.noResults) {
1309 // These produce no results
1310 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1311 Operands.push_back(InstInfo.OperandList[j].Rec);
1313 // Assume the first operand is the result.
1314 Results.push_back(InstInfo.OperandList[0].Rec);
1316 // The rest are inputs.
1317 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1318 Operands.push_back(InstInfo.OperandList[j].Rec);
1322 // Create and insert the instruction.
1323 std::vector<Record*> ImpResults;
1324 std::vector<Record*> ImpOperands;
1325 Instructions.insert(std::make_pair(Instrs[i],
1326 DAGInstruction(0, Results, Operands, ImpResults,
1328 continue; // no pattern.
1331 // Parse the instruction.
1332 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1333 // Inline pattern fragments into it.
1334 I->InlinePatternFragments();
1336 // Infer as many types as possible. If we cannot infer all of them, we can
1337 // never do anything with this instruction pattern: report it to the user.
1338 if (!I->InferAllTypes())
1339 I->error("Could not infer all types in pattern!");
1341 // InstInputs - Keep track of all of the inputs of the instruction, along
1342 // with the record they are declared as.
1343 std::map<std::string, TreePatternNode*> InstInputs;
1345 // InstResults - Keep track of all the virtual registers that are 'set'
1346 // in the instruction, including what reg class they are.
1347 std::map<std::string, TreePatternNode*> InstResults;
1349 std::vector<Record*> InstImpInputs;
1350 std::vector<Record*> InstImpResults;
1352 // Verify that the top-level forms in the instruction are of void type, and
1353 // fill in the InstResults map.
1354 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1355 TreePatternNode *Pat = I->getTree(j);
1356 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1357 I->error("Top-level forms in instruction pattern should have"
1360 // Find inputs and outputs, and verify the structure of the uses/defs.
1361 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1362 InstImpInputs, InstImpResults);
1365 // Now that we have inputs and outputs of the pattern, inspect the operands
1366 // list for the instruction. This determines the order that operands are
1367 // added to the machine instruction the node corresponds to.
1368 unsigned NumResults = InstResults.size();
1370 // Parse the operands list from the (ops) list, validating it.
1371 std::vector<std::string> &Args = I->getArgList();
1372 assert(Args.empty() && "Args list should still be empty here!");
1373 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1375 // Check that all of the results occur first in the list.
1376 std::vector<Record*> Results;
1377 TreePatternNode *Res0Node = NULL;
1378 for (unsigned i = 0; i != NumResults; ++i) {
1379 if (i == CGI.OperandList.size())
1380 I->error("'" + InstResults.begin()->first +
1381 "' set but does not appear in operand list!");
1382 const std::string &OpName = CGI.OperandList[i].Name;
1384 // Check that it exists in InstResults.
1385 TreePatternNode *RNode = InstResults[OpName];
1387 I->error("Operand $" + OpName + " does not exist in operand list!");
1391 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1393 I->error("Operand $" + OpName + " should be a set destination: all "
1394 "outputs must occur before inputs in operand list!");
1396 if (CGI.OperandList[i].Rec != R)
1397 I->error("Operand $" + OpName + " class mismatch!");
1399 // Remember the return type.
1400 Results.push_back(CGI.OperandList[i].Rec);
1402 // Okay, this one checks out.
1403 InstResults.erase(OpName);
1406 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1407 // the copy while we're checking the inputs.
1408 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1410 std::vector<TreePatternNode*> ResultNodeOperands;
1411 std::vector<Record*> Operands;
1412 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1413 const std::string &OpName = CGI.OperandList[i].Name;
1415 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1417 if (!InstInputsCheck.count(OpName))
1418 I->error("Operand $" + OpName +
1419 " does not appear in the instruction pattern");
1420 TreePatternNode *InVal = InstInputsCheck[OpName];
1421 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1423 if (InVal->isLeaf() &&
1424 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1425 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1426 if (CGI.OperandList[i].Rec != InRec &&
1427 !InRec->isSubClassOf("ComplexPattern"))
1428 I->error("Operand $" + OpName + "'s register class disagrees"
1429 " between the operand and pattern");
1431 Operands.push_back(CGI.OperandList[i].Rec);
1433 // Construct the result for the dest-pattern operand list.
1434 TreePatternNode *OpNode = InVal->clone();
1436 // No predicate is useful on the result.
1437 OpNode->setPredicateFn("");
1439 // Promote the xform function to be an explicit node if set.
1440 if (Record *Xform = OpNode->getTransformFn()) {
1441 OpNode->setTransformFn(0);
1442 std::vector<TreePatternNode*> Children;
1443 Children.push_back(OpNode);
1444 OpNode = new TreePatternNode(Xform, Children);
1447 ResultNodeOperands.push_back(OpNode);
1450 if (!InstInputsCheck.empty())
1451 I->error("Input operand $" + InstInputsCheck.begin()->first +
1452 " occurs in pattern but not in operands list!");
1454 TreePatternNode *ResultPattern =
1455 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1456 // Copy fully inferred output node type to instruction result pattern.
1458 ResultPattern->setTypes(Res0Node->getExtTypes());
1460 // Create and insert the instruction.
1461 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1462 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1464 // Use a temporary tree pattern to infer all types and make sure that the
1465 // constructed result is correct. This depends on the instruction already
1466 // being inserted into the Instructions map.
1467 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1468 Temp.InferAllTypes();
1470 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1471 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1476 // If we can, convert the instructions to be patterns that are matched!
1477 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1478 E = Instructions.end(); II != E; ++II) {
1479 DAGInstruction &TheInst = II->second;
1480 TreePattern *I = TheInst.getPattern();
1481 if (I == 0) continue; // No pattern.
1483 if (I->getNumTrees() != 1) {
1484 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1487 TreePatternNode *Pattern = I->getTree(0);
1488 TreePatternNode *SrcPattern;
1489 if (Pattern->getOperator()->getName() == "set") {
1490 if (Pattern->getNumChildren() != 2)
1491 continue; // Not a set of a single value (not handled so far)
1493 SrcPattern = Pattern->getChild(1)->clone();
1495 // Not a set (store or something?)
1496 SrcPattern = Pattern;
1500 if (!SrcPattern->canPatternMatch(Reason, *this))
1501 I->error("Instruction can never match: " + Reason);
1503 Record *Instr = II->first;
1504 TreePatternNode *DstPattern = TheInst.getResultPattern();
1506 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1507 SrcPattern, DstPattern,
1508 Instr->getValueAsInt("AddedComplexity")));
1512 void DAGISelEmitter::ParsePatterns() {
1513 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1515 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1516 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1517 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1519 // Inline pattern fragments into it.
1520 Pattern->InlinePatternFragments();
1522 // Infer as many types as possible. If we cannot infer all of them, we can
1523 // never do anything with this pattern: report it to the user.
1524 if (!Pattern->InferAllTypes())
1525 Pattern->error("Could not infer all types in pattern!");
1527 // Validate that the input pattern is correct.
1529 std::map<std::string, TreePatternNode*> InstInputs;
1530 std::map<std::string, TreePatternNode*> InstResults;
1531 std::vector<Record*> InstImpInputs;
1532 std::vector<Record*> InstImpResults;
1533 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1534 InstInputs, InstResults,
1535 InstImpInputs, InstImpResults);
1538 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1539 if (LI->getSize() == 0) continue; // no pattern.
1541 // Parse the instruction.
1542 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1544 // Inline pattern fragments into it.
1545 Result->InlinePatternFragments();
1547 // Infer as many types as possible. If we cannot infer all of them, we can
1548 // never do anything with this pattern: report it to the user.
1549 if (!Result->InferAllTypes())
1550 Result->error("Could not infer all types in pattern result!");
1552 if (Result->getNumTrees() != 1)
1553 Result->error("Cannot handle instructions producing instructions "
1554 "with temporaries yet!");
1556 // Promote the xform function to be an explicit node if set.
1557 std::vector<TreePatternNode*> ResultNodeOperands;
1558 TreePatternNode *DstPattern = Result->getOnlyTree();
1559 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1560 TreePatternNode *OpNode = DstPattern->getChild(ii);
1561 if (Record *Xform = OpNode->getTransformFn()) {
1562 OpNode->setTransformFn(0);
1563 std::vector<TreePatternNode*> Children;
1564 Children.push_back(OpNode);
1565 OpNode = new TreePatternNode(Xform, Children);
1567 ResultNodeOperands.push_back(OpNode);
1569 DstPattern = Result->getOnlyTree();
1570 if (!DstPattern->isLeaf())
1571 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1572 ResultNodeOperands);
1573 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1574 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1575 Temp.InferAllTypes();
1578 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1579 Pattern->error("Pattern can never match: " + Reason);
1582 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1583 Pattern->getOnlyTree(),
1585 Patterns[i]->getValueAsInt("AddedComplexity")));
1589 /// CombineChildVariants - Given a bunch of permutations of each child of the
1590 /// 'operator' node, put them together in all possible ways.
1591 static void CombineChildVariants(TreePatternNode *Orig,
1592 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1593 std::vector<TreePatternNode*> &OutVariants,
1594 DAGISelEmitter &ISE) {
1595 // Make sure that each operand has at least one variant to choose from.
1596 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1597 if (ChildVariants[i].empty())
1600 // The end result is an all-pairs construction of the resultant pattern.
1601 std::vector<unsigned> Idxs;
1602 Idxs.resize(ChildVariants.size());
1603 bool NotDone = true;
1605 // Create the variant and add it to the output list.
1606 std::vector<TreePatternNode*> NewChildren;
1607 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1608 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1609 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1611 // Copy over properties.
1612 R->setName(Orig->getName());
1613 R->setPredicateFn(Orig->getPredicateFn());
1614 R->setTransformFn(Orig->getTransformFn());
1615 R->setTypes(Orig->getExtTypes());
1617 // If this pattern cannot every match, do not include it as a variant.
1618 std::string ErrString;
1619 if (!R->canPatternMatch(ErrString, ISE)) {
1622 bool AlreadyExists = false;
1624 // Scan to see if this pattern has already been emitted. We can get
1625 // duplication due to things like commuting:
1626 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1627 // which are the same pattern. Ignore the dups.
1628 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1629 if (R->isIsomorphicTo(OutVariants[i])) {
1630 AlreadyExists = true;
1637 OutVariants.push_back(R);
1640 // Increment indices to the next permutation.
1642 // Look for something we can increment without causing a wrap-around.
1643 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1644 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1645 NotDone = true; // Found something to increment.
1653 /// CombineChildVariants - A helper function for binary operators.
1655 static void CombineChildVariants(TreePatternNode *Orig,
1656 const std::vector<TreePatternNode*> &LHS,
1657 const std::vector<TreePatternNode*> &RHS,
1658 std::vector<TreePatternNode*> &OutVariants,
1659 DAGISelEmitter &ISE) {
1660 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1661 ChildVariants.push_back(LHS);
1662 ChildVariants.push_back(RHS);
1663 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1667 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1668 std::vector<TreePatternNode *> &Children) {
1669 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1670 Record *Operator = N->getOperator();
1672 // Only permit raw nodes.
1673 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1674 N->getTransformFn()) {
1675 Children.push_back(N);
1679 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1680 Children.push_back(N->getChild(0));
1682 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1684 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1685 Children.push_back(N->getChild(1));
1687 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1690 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1691 /// the (potentially recursive) pattern by using algebraic laws.
1693 static void GenerateVariantsOf(TreePatternNode *N,
1694 std::vector<TreePatternNode*> &OutVariants,
1695 DAGISelEmitter &ISE) {
1696 // We cannot permute leaves.
1698 OutVariants.push_back(N);
1702 // Look up interesting info about the node.
1703 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1705 // If this node is associative, reassociate.
1706 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1707 // Reassociate by pulling together all of the linked operators
1708 std::vector<TreePatternNode*> MaximalChildren;
1709 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1711 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1713 if (MaximalChildren.size() == 3) {
1714 // Find the variants of all of our maximal children.
1715 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1716 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1717 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1718 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1720 // There are only two ways we can permute the tree:
1721 // (A op B) op C and A op (B op C)
1722 // Within these forms, we can also permute A/B/C.
1724 // Generate legal pair permutations of A/B/C.
1725 std::vector<TreePatternNode*> ABVariants;
1726 std::vector<TreePatternNode*> BAVariants;
1727 std::vector<TreePatternNode*> ACVariants;
1728 std::vector<TreePatternNode*> CAVariants;
1729 std::vector<TreePatternNode*> BCVariants;
1730 std::vector<TreePatternNode*> CBVariants;
1731 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1732 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1733 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1734 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1735 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1736 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1738 // Combine those into the result: (x op x) op x
1739 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1740 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1741 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1742 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1743 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1744 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1746 // Combine those into the result: x op (x op x)
1747 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1748 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1749 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1750 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1751 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1752 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1757 // Compute permutations of all children.
1758 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1759 ChildVariants.resize(N->getNumChildren());
1760 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1761 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1763 // Build all permutations based on how the children were formed.
1764 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1766 // If this node is commutative, consider the commuted order.
1767 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1768 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1769 // Consider the commuted order.
1770 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1776 // GenerateVariants - Generate variants. For example, commutative patterns can
1777 // match multiple ways. Add them to PatternsToMatch as well.
1778 void DAGISelEmitter::GenerateVariants() {
1780 DEBUG(std::cerr << "Generating instruction variants.\n");
1782 // Loop over all of the patterns we've collected, checking to see if we can
1783 // generate variants of the instruction, through the exploitation of
1784 // identities. This permits the target to provide agressive matching without
1785 // the .td file having to contain tons of variants of instructions.
1787 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1788 // intentionally do not reconsider these. Any variants of added patterns have
1789 // already been added.
1791 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1792 std::vector<TreePatternNode*> Variants;
1793 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1795 assert(!Variants.empty() && "Must create at least original variant!");
1796 Variants.erase(Variants.begin()); // Remove the original pattern.
1798 if (Variants.empty()) // No variants for this pattern.
1801 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1802 PatternsToMatch[i].getSrcPattern()->dump();
1805 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1806 TreePatternNode *Variant = Variants[v];
1808 DEBUG(std::cerr << " VAR#" << v << ": ";
1812 // Scan to see if an instruction or explicit pattern already matches this.
1813 bool AlreadyExists = false;
1814 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1815 // Check to see if this variant already exists.
1816 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1817 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1818 AlreadyExists = true;
1822 // If we already have it, ignore the variant.
1823 if (AlreadyExists) continue;
1825 // Otherwise, add it to the list of patterns we have.
1827 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1828 Variant, PatternsToMatch[i].getDstPattern(),
1829 PatternsToMatch[i].getAddedComplexity()));
1832 DEBUG(std::cerr << "\n");
1837 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1839 static bool NodeIsComplexPattern(TreePatternNode *N)
1841 return (N->isLeaf() &&
1842 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1843 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1844 isSubClassOf("ComplexPattern"));
1847 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1848 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1849 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1850 DAGISelEmitter &ISE)
1853 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1854 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1855 isSubClassOf("ComplexPattern")) {
1856 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1862 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1863 /// patterns before small ones. This is used to determine the size of a
1865 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1866 assert(isExtIntegerInVTs(P->getExtTypes()) ||
1867 isExtFloatingPointInVTs(P->getExtTypes()) ||
1868 P->getExtTypeNum(0) == MVT::isVoid ||
1869 P->getExtTypeNum(0) == MVT::Flag &&
1870 "Not a valid pattern node to size!");
1871 unsigned Size = 2; // The node itself.
1872 // If the root node is a ConstantSDNode, increases its size.
1873 // e.g. (set R32:$dst, 0).
1874 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1877 // FIXME: This is a hack to statically increase the priority of patterns
1878 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1879 // Later we can allow complexity / cost for each pattern to be (optionally)
1880 // specified. To get best possible pattern match we'll need to dynamically
1881 // calculate the complexity of all patterns a dag can potentially map to.
1882 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1884 Size += AM->getNumOperands() * 2;
1886 // If this node has some predicate function that must match, it adds to the
1887 // complexity of this node.
1888 if (!P->getPredicateFn().empty())
1891 // Count children in the count if they are also nodes.
1892 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1893 TreePatternNode *Child = P->getChild(i);
1894 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1895 Size += getPatternSize(Child, ISE);
1896 else if (Child->isLeaf()) {
1897 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1898 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
1899 else if (NodeIsComplexPattern(Child))
1900 Size += getPatternSize(Child, ISE);
1901 else if (!Child->getPredicateFn().empty())
1909 /// getResultPatternCost - Compute the number of instructions for this pattern.
1910 /// This is a temporary hack. We should really include the instruction
1911 /// latencies in this calculation.
1912 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
1913 if (P->isLeaf()) return 0;
1916 Record *Op = P->getOperator();
1917 if (Op->isSubClassOf("Instruction")) {
1919 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1920 if (II.usesCustomDAGSchedInserter)
1923 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1924 Cost += getResultPatternCost(P->getChild(i), ISE);
1928 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1929 // In particular, we want to match maximal patterns first and lowest cost within
1930 // a particular complexity first.
1931 struct PatternSortingPredicate {
1932 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1933 DAGISelEmitter &ISE;
1935 bool operator()(PatternToMatch *LHS,
1936 PatternToMatch *RHS) {
1937 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1938 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1939 LHSSize += LHS->getAddedComplexity();
1940 RHSSize += RHS->getAddedComplexity();
1941 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1942 if (LHSSize < RHSSize) return false;
1944 // If the patterns have equal complexity, compare generated instruction cost
1945 return getResultPatternCost(LHS->getDstPattern(), ISE) <
1946 getResultPatternCost(RHS->getDstPattern(), ISE);
1950 /// getRegisterValueType - Look up and return the first ValueType of specified
1951 /// RegisterClass record
1952 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1953 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1954 return RC->getValueTypeNum(0);
1959 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1960 /// type information from it.
1961 static void RemoveAllTypes(TreePatternNode *N) {
1964 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1965 RemoveAllTypes(N->getChild(i));
1968 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1969 Record *N = Records.getDef(Name);
1970 if (!N || !N->isSubClassOf("SDNode")) {
1971 std::cerr << "Error getting SDNode '" << Name << "'!\n";
1977 /// NodeHasProperty - return true if TreePatternNode has the specified
1979 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1980 DAGISelEmitter &ISE)
1982 if (N->isLeaf()) return false;
1983 Record *Operator = N->getOperator();
1984 if (!Operator->isSubClassOf("SDNode")) return false;
1986 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1987 return NodeInfo.hasProperty(Property);
1990 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1991 DAGISelEmitter &ISE)
1993 if (NodeHasProperty(N, Property, ISE))
1996 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1997 TreePatternNode *Child = N->getChild(i);
1998 if (PatternHasProperty(Child, Property, ISE))
2005 class PatternCodeEmitter {
2007 DAGISelEmitter &ISE;
2010 ListInit *Predicates;
2013 // Instruction selector pattern.
2014 TreePatternNode *Pattern;
2015 // Matched instruction.
2016 TreePatternNode *Instruction;
2018 // Node to name mapping
2019 std::map<std::string, std::string> VariableMap;
2020 // Node to operator mapping
2021 std::map<std::string, Record*> OperatorMap;
2022 // Names of all the folded nodes which produce chains.
2023 std::vector<std::pair<std::string, unsigned> > FoldedChains;
2024 std::set<std::string> Duplicates;
2026 /// GeneratedCode - This is the buffer that we emit code to. The first bool
2027 /// indicates whether this is an exit predicate (something that should be
2028 /// tested, and if true, the match fails) [when true] or normal code to emit
2030 std::vector<std::pair<bool, std::string> > &GeneratedCode;
2031 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2032 /// the set of patterns for each top-level opcode.
2033 std::set<std::pair<bool, std::string> > &GeneratedDecl;
2035 std::string ChainName;
2040 void emitCheck(const std::string &S) {
2042 GeneratedCode.push_back(std::make_pair(true, S));
2044 void emitCode(const std::string &S) {
2046 GeneratedCode.push_back(std::make_pair(false, S));
2048 void emitDecl(const std::string &S, bool isSDNode=false) {
2049 assert(!S.empty() && "Invalid declaration");
2050 GeneratedDecl.insert(std::make_pair(isSDNode, S));
2053 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2054 TreePatternNode *pattern, TreePatternNode *instr,
2055 std::vector<std::pair<bool, std::string> > &gc,
2056 std::set<std::pair<bool, std::string> > &gd,
2058 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2059 GeneratedCode(gc), GeneratedDecl(gd),
2060 NewTF(false), DoReplace(dorep), TmpNo(0) {}
2062 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2063 /// if the match fails. At this point, we already know that the opcode for N
2064 /// matches, and the SDNode for the result has the RootName specified name.
2065 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2066 const std::string &RootName, const std::string &ParentName,
2067 const std::string &ChainSuffix, bool &FoundChain) {
2068 bool isRoot = (P == NULL);
2069 // Emit instruction predicates. Each predicate is just a string for now.
2071 std::string PredicateCheck;
2072 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2073 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2074 Record *Def = Pred->getDef();
2075 if (!Def->isSubClassOf("Predicate")) {
2077 assert(0 && "Unknown predicate type!");
2079 if (!PredicateCheck.empty())
2080 PredicateCheck += " || ";
2081 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2085 emitCheck(PredicateCheck);
2089 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2090 emitCheck("cast<ConstantSDNode>(" + RootName +
2091 ")->getSignExtended() == " + itostr(II->getValue()));
2093 } else if (!NodeIsComplexPattern(N)) {
2094 assert(0 && "Cannot match this as a leaf value!");
2099 // If this node has a name associated with it, capture it in VariableMap. If
2100 // we already saw this in the pattern, emit code to verify dagness.
2101 if (!N->getName().empty()) {
2102 std::string &VarMapEntry = VariableMap[N->getName()];
2103 if (VarMapEntry.empty()) {
2104 VarMapEntry = RootName;
2106 // If we get here, this is a second reference to a specific name. Since
2107 // we already have checked that the first reference is valid, we don't
2108 // have to recursively match it, just check that it's the same as the
2109 // previously named thing.
2110 emitCheck(VarMapEntry + " == " + RootName);
2115 OperatorMap[N->getName()] = N->getOperator();
2119 // Emit code to load the child nodes and match their contents recursively.
2121 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2122 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2123 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
2124 bool EmittedUseCheck = false;
2125 bool EmittedSlctedCheck = false;
2130 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2131 // Multiple uses of actual result?
2132 emitCheck(RootName + ".hasOneUse()");
2133 EmittedUseCheck = true;
2134 // hasOneUse() check is not strong enough. If the original node has
2135 // already been selected, it may have been replaced with another.
2136 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
2137 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2140 EmittedSlctedCheck = true;
2142 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2144 // This a workaround for this problem:
2149 // [XX]--/ \- [flag : cmp]
2154 // cmp + br should be considered as a single node as they are flagged
2155 // together. So, if the ld is folded into the cmp, the XX node in the
2156 // graph is now both an operand and a use of the ld/cmp/br node.
2157 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2158 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2160 // If the immediate use can somehow reach this node through another
2161 // path, then can't fold it either or it will create a cycle.
2162 // e.g. In the following diagram, XX can reach ld through YY. If
2163 // ld is folded into XX, then YY is both a predecessor and a successor
2173 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2174 if (PInfo.getNumOperands() > 1 ||
2175 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2176 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2177 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2178 if (PInfo.getNumOperands() > 1) {
2179 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2182 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2183 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2190 ChainName = "Chain" + ChainSuffix;
2191 emitDecl(ChainName);
2193 // FIXME: temporary workaround for a common case where chain
2194 // is a TokenFactor and the previous "inner" chain is an operand.
2196 emitDecl("OldTF", true);
2197 emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2198 RootName + ".Val, Chain.Val, OldTF)).Val");
2201 emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2206 // Don't fold any node which reads or writes a flag and has multiple uses.
2207 // FIXME: We really need to separate the concepts of flag and "glue". Those
2208 // real flag results, e.g. X86CMP output, can have multiple uses.
2209 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2212 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2213 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2214 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
2215 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2216 if (!EmittedUseCheck) {
2217 // Multiple uses of actual result?
2218 emitCheck(RootName + ".hasOneUse()");
2220 if (!EmittedSlctedCheck)
2221 // hasOneUse() check is not strong enough. If the original node has
2222 // already been selected, it may have been replaced with another.
2223 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
2224 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2228 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2229 emitDecl(RootName + utostr(OpNo));
2230 emitCode(RootName + utostr(OpNo) + " = " +
2231 RootName + ".getOperand(" +utostr(OpNo) + ");");
2232 TreePatternNode *Child = N->getChild(i);
2234 if (!Child->isLeaf()) {
2235 // If it's not a leaf, recursively match.
2236 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2237 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
2238 CInfo.getEnumName());
2239 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2240 ChainSuffix + utostr(OpNo), FoundChain);
2241 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2242 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2243 CInfo.getNumResults()));
2245 // If this child has a name associated with it, capture it in VarMap. If
2246 // we already saw this in the pattern, emit code to verify dagness.
2247 if (!Child->getName().empty()) {
2248 std::string &VarMapEntry = VariableMap[Child->getName()];
2249 if (VarMapEntry.empty()) {
2250 VarMapEntry = RootName + utostr(OpNo);
2252 // If we get here, this is a second reference to a specific name.
2253 // Since we already have checked that the first reference is valid,
2254 // we don't have to recursively match it, just check that it's the
2255 // same as the previously named thing.
2256 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2257 Duplicates.insert(RootName + utostr(OpNo));
2262 // Handle leaves of various types.
2263 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2264 Record *LeafRec = DI->getDef();
2265 if (LeafRec->isSubClassOf("RegisterClass")) {
2266 // Handle register references. Nothing to do here.
2267 } else if (LeafRec->isSubClassOf("Register")) {
2268 // Handle register references.
2269 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2270 // Handle complex pattern. Nothing to do here.
2271 } else if (LeafRec->getName() == "srcvalue") {
2272 // Place holder for SRCVALUE nodes. Nothing to do here.
2273 } else if (LeafRec->isSubClassOf("ValueType")) {
2274 // Make sure this is the specified value type.
2275 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2276 ")->getVT() == MVT::" + LeafRec->getName());
2277 } else if (LeafRec->isSubClassOf("CondCode")) {
2278 // Make sure this is the specified cond code.
2279 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2280 ")->get() == ISD::" + LeafRec->getName());
2284 assert(0 && "Unknown leaf type!");
2286 } else if (IntInit *II =
2287 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2288 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2289 unsigned CTmp = TmpNo++;
2290 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2291 RootName + utostr(OpNo) + ")->getSignExtended();");
2293 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2296 assert(0 && "Unknown leaf type!");
2301 // If there is a node predicate for this, emit the call.
2302 if (!N->getPredicateFn().empty())
2303 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2306 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2307 /// we actually have to build a DAG!
2308 std::pair<unsigned, unsigned>
2309 EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2310 bool isRoot = false) {
2311 // This is something selected from the pattern we matched.
2312 if (!N->getName().empty()) {
2313 std::string &Val = VariableMap[N->getName()];
2314 assert(!Val.empty() &&
2315 "Variable referenced but not defined and not caught earlier!");
2316 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2317 // Already selected this operand, just return the tmpval.
2318 return std::make_pair(1, atoi(Val.c_str()+3));
2321 const ComplexPattern *CP;
2322 unsigned ResNo = TmpNo++;
2323 unsigned NumRes = 1;
2324 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2325 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2326 std::string CastType;
2327 switch (N->getTypeNum(0)) {
2328 default: assert(0 && "Unknown type for constant node!");
2329 case MVT::i1: CastType = "bool"; break;
2330 case MVT::i8: CastType = "unsigned char"; break;
2331 case MVT::i16: CastType = "unsigned short"; break;
2332 case MVT::i32: CastType = "unsigned"; break;
2333 case MVT::i64: CastType = "uint64_t"; break;
2335 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
2336 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
2337 emitDecl("Tmp" + utostr(ResNo));
2338 emitCode("Tmp" + utostr(ResNo) +
2339 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
2340 "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2341 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2342 Record *Op = OperatorMap[N->getName()];
2343 // Transform ExternalSymbol to TargetExternalSymbol
2344 if (Op && Op->getName() == "externalsym") {
2345 emitDecl("Tmp" + utostr(ResNo));
2346 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2347 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2348 Val + ")->getSymbol(), MVT::" +
2349 getEnumName(N->getTypeNum(0)) + ");");
2351 emitDecl("Tmp" + utostr(ResNo));
2352 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2354 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2355 Record *Op = OperatorMap[N->getName()];
2356 // Transform GlobalAddress to TargetGlobalAddress
2357 if (Op && Op->getName() == "globaladdr") {
2358 emitDecl("Tmp" + utostr(ResNo));
2359 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2360 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2361 ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2364 emitDecl("Tmp" + utostr(ResNo));
2365 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2367 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2368 emitDecl("Tmp" + utostr(ResNo));
2369 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2370 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2371 emitDecl("Tmp" + utostr(ResNo));
2372 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2373 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2374 std::string Fn = CP->getSelectFunc();
2375 NumRes = CP->getNumOperands();
2376 for (unsigned i = 0; i < NumRes; ++i)
2377 emitDecl("Tmp" + utostr(i+ResNo));
2379 std::string Code = Fn + "(" + Val;
2380 for (unsigned i = 0; i < NumRes; i++)
2381 Code += ", Tmp" + utostr(i + ResNo);
2382 emitCheck(Code + ")");
2384 for (unsigned i = 0; i < NumRes; ++i)
2385 emitCode("Select(Tmp" + utostr(i+ResNo) + ", Tmp" +
2386 utostr(i+ResNo) + ");");
2388 TmpNo = ResNo + NumRes;
2390 emitDecl("Tmp" + utostr(ResNo));
2391 // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2392 // node even if it isn't one. Don't select it.
2394 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2396 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
2398 if (isRoot && N->isLeaf()) {
2399 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2400 emitCode("return;");
2403 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2404 // value if used multiple times by this pattern result.
2405 Val = "Tmp"+utostr(ResNo);
2406 return std::make_pair(NumRes, ResNo);
2409 // If this is an explicit register reference, handle it.
2410 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2411 unsigned ResNo = TmpNo++;
2412 if (DI->getDef()->isSubClassOf("Register")) {
2413 emitDecl("Tmp" + utostr(ResNo));
2414 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2415 ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2416 getEnumName(N->getTypeNum(0)) + ");");
2417 return std::make_pair(1, ResNo);
2419 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2420 unsigned ResNo = TmpNo++;
2421 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2422 emitDecl("Tmp" + utostr(ResNo));
2423 emitCode("Tmp" + utostr(ResNo) +
2424 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2425 ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2426 return std::make_pair(1, ResNo);
2430 assert(0 && "Unknown leaf type!");
2431 return std::make_pair(1, ~0U);
2434 Record *Op = N->getOperator();
2435 if (Op->isSubClassOf("Instruction")) {
2436 const CodeGenTarget &CGT = ISE.getTargetInfo();
2437 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2438 const DAGInstruction &Inst = ISE.getInstruction(Op);
2439 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2440 bool HasImpResults = Inst.getNumImpResults() > 0;
2441 bool HasOptInFlag = isRoot &&
2442 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2443 bool HasInFlag = isRoot &&
2444 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2445 bool NodeHasOutFlag = HasImpResults ||
2446 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2448 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2449 bool HasChain = II.hasCtrlDep ||
2450 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
2452 if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
2455 emitCode("bool HasOptInFlag = false;");
2457 // How many results is this pattern expected to produce?
2458 unsigned PatResults = 0;
2459 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2460 MVT::ValueType VT = Pattern->getTypeNum(i);
2461 if (VT != MVT::isVoid && VT != MVT::Flag)
2465 // Determine operand emission order. Complex pattern first.
2466 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2467 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2468 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2469 TreePatternNode *Child = N->getChild(i);
2471 EmitOrder.push_back(std::make_pair(i, Child));
2472 OI = EmitOrder.begin();
2473 } else if (NodeIsComplexPattern(Child)) {
2474 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2476 EmitOrder.push_back(std::make_pair(i, Child));
2480 // Emit all of the operands.
2481 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2482 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2483 unsigned OpOrder = EmitOrder[i].first;
2484 TreePatternNode *Child = EmitOrder[i].second;
2485 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2486 NumTemps[OpOrder] = NumTemp;
2489 // List all the operands in the right order.
2490 std::vector<unsigned> Ops;
2491 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2492 for (unsigned j = 0; j < NumTemps[i].first; j++)
2493 Ops.push_back(NumTemps[i].second + j);
2496 // Emit all the chain and CopyToReg stuff.
2497 bool ChainEmitted = HasChain;
2499 emitCode("Select(" + ChainName + ", " + ChainName + ");");
2500 if (HasInFlag || HasOptInFlag || HasImpInputs)
2501 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
2503 unsigned NumResults = Inst.getNumResults();
2504 unsigned ResNo = TmpNo++;
2506 emitDecl("Tmp" + utostr(ResNo));
2508 "Tmp" + utostr(ResNo) + " = SDOperand(CurDAG->getTargetNode(" +
2509 II.Namespace + "::" + II.TheDef->getName();
2510 if (N->getTypeNum(0) != MVT::isVoid)
2511 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2513 Code += ", MVT::Flag";
2515 unsigned LastOp = 0;
2516 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2518 Code += ", Tmp" + utostr(LastOp);
2520 emitCode(Code + "), 0);");
2522 // Must have at least one result
2523 emitCode(ChainName + " = Tmp" + utostr(LastOp) + ".getValue(" +
2524 utostr(NumResults) + ");");
2526 } else if (HasChain || NodeHasOutFlag) {
2528 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
2529 emitDecl("ResNode", true);
2530 emitCode("if (HasOptInFlag)");
2531 std::string Code = " ResNode = CurDAG->getTargetNode(" +
2532 II.Namespace + "::" + II.TheDef->getName();
2534 // Output order: results, chain, flags
2536 if (NumResults > 0) {
2537 if (N->getTypeNum(0) != MVT::isVoid)
2538 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2541 Code += ", MVT::Other";
2543 Code += ", MVT::Flag";
2546 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2547 Code += ", Tmp" + utostr(Ops[i]);
2548 if (HasChain) Code += ", " + ChainName;
2549 emitCode(Code + ", InFlag);");
2552 Code = " ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
2553 II.TheDef->getName();
2555 // Output order: results, chain, flags
2557 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2558 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2560 Code += ", MVT::Other";
2562 Code += ", MVT::Flag";
2565 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2566 Code += ", Tmp" + utostr(Ops[i]);
2567 if (HasChain) Code += ", " + ChainName + ");";
2570 emitDecl("ResNode", true);
2571 std::string Code = "ResNode = CurDAG->getTargetNode(" +
2572 II.Namespace + "::" + II.TheDef->getName();
2574 // Output order: results, chain, flags
2576 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2577 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2579 Code += ", MVT::Other";
2581 Code += ", MVT::Flag";
2584 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2585 Code += ", Tmp" + utostr(Ops[i]);
2586 if (HasChain) Code += ", " + ChainName;
2587 if (HasInFlag || HasImpInputs) Code += ", InFlag";
2588 emitCode(Code + ");");
2592 emitCode("if (OldTF) "
2593 "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2594 ChainName + ".Val, 0);");
2596 for (unsigned i = 0; i < NumResults; i++)
2597 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2598 utostr(i) + ", ResNode, " + utostr(i) + ");");
2601 emitCode("InFlag = SDOperand(ResNode, " +
2602 utostr(NumResults + (unsigned)HasChain) + ");");
2604 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2605 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2611 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2612 utostr(PatResults) + ", ResNode, " +
2613 utostr(NumResults) + ");");
2615 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2616 utostr(PatResults) + ", " + "ResNode, " +
2617 utostr(NumResults) + ");");
2620 if (FoldedChains.size() > 0) {
2622 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2623 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2624 FoldedChains[j].first + ".Val, " +
2625 utostr(FoldedChains[j].second) + ", ResNode, " +
2626 utostr(NumResults) + ");");
2628 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2630 FoldedChains[j].first + ".Val, " +
2631 utostr(FoldedChains[j].second) + ", ";
2632 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
2633 utostr(NumResults) + ");");
2638 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2639 utostr(PatResults + (unsigned)NodeHasChain) +
2640 ", InFlag.Val, InFlag.ResNo);");
2642 // User does not expect the instruction would produce a chain!
2643 bool AddedChain = HasChain && !NodeHasChain;
2644 if (AddedChain && NodeHasOutFlag) {
2645 if (PatResults == 0) {
2646 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
2648 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2649 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2651 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
2654 emitCode("Result = SDOperand(ResNode, N.ResNo);");
2657 // If this instruction is the root, and if there is only one use of it,
2658 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2659 emitCode("if (N.Val->hasOneUse()) {");
2660 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, " +
2661 II.Namespace + "::" + II.TheDef->getName();
2662 if (N->getTypeNum(0) != MVT::isVoid)
2663 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2665 Code += ", MVT::Flag";
2666 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2667 Code += ", Tmp" + utostr(Ops[i]);
2668 if (HasInFlag || HasImpInputs)
2670 emitCode(Code + ");");
2671 emitCode("} else {");
2672 emitDecl("ResNode", true);
2673 Code = " ResNode = CurDAG->getTargetNode(" +
2674 II.Namespace + "::" + II.TheDef->getName();
2675 if (N->getTypeNum(0) != MVT::isVoid)
2676 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2678 Code += ", MVT::Flag";
2679 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2680 Code += ", Tmp" + utostr(Ops[i]);
2681 if (HasInFlag || HasImpInputs)
2683 emitCode(Code + ");");
2684 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2686 emitCode(" Result = SDOperand(ResNode, 0);");
2691 emitCode("return;");
2692 return std::make_pair(1, ResNo);
2693 } else if (Op->isSubClassOf("SDNodeXForm")) {
2694 assert(N->getNumChildren() == 1 && "node xform should have one child!");
2695 // PatLeaf node - the operand may or may not be a leaf node. But it should
2697 unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
2698 unsigned ResNo = TmpNo++;
2699 emitDecl("Tmp" + utostr(ResNo));
2700 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2701 + "(Tmp" + utostr(OpVal) + ".Val);");
2703 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2704 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2705 utostr(ResNo) + ".ResNo);");
2706 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2707 emitCode("return;");
2709 return std::make_pair(1, ResNo);
2713 throw std::string("Unknown node in result pattern!");
2717 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2718 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2719 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2720 /// for, this returns true otherwise false if Pat has all types.
2721 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2722 const std::string &Prefix) {
2724 if (!Pat->hasTypeSet()) {
2725 // Move a type over from 'other' to 'pat'.
2726 Pat->setTypes(Other->getExtTypes());
2727 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
2728 getName(Pat->getTypeNum(0)));
2733 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2734 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2735 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2736 Prefix + utostr(OpNo)))
2742 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2744 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2745 bool &ChainEmitted, bool isRoot = false) {
2746 const CodeGenTarget &T = ISE.getTargetInfo();
2748 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2749 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2750 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
2751 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2752 TreePatternNode *Child = N->getChild(i);
2753 if (!Child->isLeaf()) {
2754 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
2756 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2757 if (!Child->getName().empty()) {
2758 std::string Name = RootName + utostr(OpNo);
2759 if (Duplicates.find(Name) != Duplicates.end())
2760 // A duplicate! Do not emit a copy for this node.
2764 Record *RR = DI->getDef();
2765 if (RR->isSubClassOf("Register")) {
2766 MVT::ValueType RVT = getRegisterValueType(RR, T);
2767 if (RVT == MVT::Flag) {
2768 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
2770 if (!ChainEmitted) {
2772 emitCode("Chain = CurDAG->getEntryNode();");
2773 ChainName = "Chain";
2774 ChainEmitted = true;
2776 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2777 RootName + utostr(OpNo) + ");");
2778 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
2779 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2780 ", MVT::" + getEnumName(RVT) + "), " +
2781 RootName + utostr(OpNo) + ", InFlag).Val;");
2782 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2783 emitCode("InFlag = SDOperand(ResNode, 1);");
2790 if (HasInFlag || HasOptInFlag) {
2793 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2797 emitCode(Code + "Select(InFlag, " + RootName +
2798 ".getOperand(" + utostr(OpNo) + "));");
2800 emitCode(" HasOptInFlag = true;");
2806 /// EmitCopyFromRegs - Emit code to copy result to physical registers
2807 /// as specified by the instruction. It returns true if any copy is
2809 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
2810 bool RetVal = false;
2811 Record *Op = N->getOperator();
2812 if (Op->isSubClassOf("Instruction")) {
2813 const DAGInstruction &Inst = ISE.getInstruction(Op);
2814 const CodeGenTarget &CGT = ISE.getTargetInfo();
2815 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2816 unsigned NumImpResults = Inst.getNumImpResults();
2817 for (unsigned i = 0; i < NumImpResults; i++) {
2818 Record *RR = Inst.getImpResult(i);
2819 if (RR->isSubClassOf("Register")) {
2820 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2821 if (RVT != MVT::Flag) {
2822 if (!ChainEmitted) {
2824 emitCode("Chain = CurDAG->getEntryNode();");
2825 ChainEmitted = true;
2826 ChainName = "Chain";
2828 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
2829 ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
2831 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2832 emitCode("InFlag = SDOperand(ResNode, 2);");
2842 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2843 /// stream to match the pattern, and generate the code for the match if it
2844 /// succeeds. Returns true if the pattern is not guaranteed to match.
2845 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2846 std::vector<std::pair<bool, std::string> > &GeneratedCode,
2847 std::set<std::pair<bool, std::string> > &GeneratedDecl,
2849 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2850 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2851 GeneratedCode, GeneratedDecl, DoReplace);
2853 // Emit the matcher, capturing named arguments in VariableMap.
2854 bool FoundChain = false;
2855 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
2857 // TP - Get *SOME* tree pattern, we don't care which.
2858 TreePattern &TP = *PatternFragments.begin()->second;
2860 // At this point, we know that we structurally match the pattern, but the
2861 // types of the nodes may not match. Figure out the fewest number of type
2862 // comparisons we need to emit. For example, if there is only one integer
2863 // type supported by a target, there should be no type comparisons at all for
2864 // integer patterns!
2866 // To figure out the fewest number of type checks needed, clone the pattern,
2867 // remove the types, then perform type inference on the pattern as a whole.
2868 // If there are unresolved types, emit an explicit check for those types,
2869 // apply the type to the tree, then rerun type inference. Iterate until all
2870 // types are resolved.
2872 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2873 RemoveAllTypes(Pat);
2876 // Resolve/propagate as many types as possible.
2878 bool MadeChange = true;
2880 MadeChange = Pat->ApplyTypeConstraints(TP,
2881 true/*Ignore reg constraints*/);
2883 assert(0 && "Error: could not find consistent types for something we"
2884 " already decided was ok!");
2888 // Insert a check for an unresolved type and add it to the tree. If we find
2889 // an unresolved type to add a check for, this returns true and we iterate,
2890 // otherwise we are done.
2891 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2893 Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
2897 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
2898 /// a line causes any of them to be empty, remove them and return true when
2900 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
2901 std::vector<std::pair<bool, std::string> > > >
2903 bool ErasedPatterns = false;
2904 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2905 Patterns[i].second.pop_back();
2906 if (Patterns[i].second.empty()) {
2907 Patterns.erase(Patterns.begin()+i);
2909 ErasedPatterns = true;
2912 return ErasedPatterns;
2915 /// EmitPatterns - Emit code for at least one pattern, but try to group common
2916 /// code together between the patterns.
2917 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
2918 std::vector<std::pair<bool, std::string> > > >
2919 &Patterns, unsigned Indent,
2921 typedef std::pair<bool, std::string> CodeLine;
2922 typedef std::vector<CodeLine> CodeList;
2923 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2925 if (Patterns.empty()) return;
2927 // Figure out how many patterns share the next code line. Explicitly copy
2928 // FirstCodeLine so that we don't invalidate a reference when changing
2930 const CodeLine FirstCodeLine = Patterns.back().second.back();
2931 unsigned LastMatch = Patterns.size()-1;
2932 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2935 // If not all patterns share this line, split the list into two pieces. The
2936 // first chunk will use this line, the second chunk won't.
2937 if (LastMatch != 0) {
2938 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2939 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2941 // FIXME: Emit braces?
2942 if (Shared.size() == 1) {
2943 PatternToMatch &Pattern = *Shared.back().first;
2944 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2945 Pattern.getSrcPattern()->print(OS);
2946 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2947 Pattern.getDstPattern()->print(OS);
2949 unsigned AddedComplexity = Pattern.getAddedComplexity();
2950 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2951 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
2953 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
2955 if (!FirstCodeLine.first) {
2956 OS << std::string(Indent, ' ') << "{\n";
2959 EmitPatterns(Shared, Indent, OS);
2960 if (!FirstCodeLine.first) {
2962 OS << std::string(Indent, ' ') << "}\n";
2965 if (Other.size() == 1) {
2966 PatternToMatch &Pattern = *Other.back().first;
2967 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2968 Pattern.getSrcPattern()->print(OS);
2969 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2970 Pattern.getDstPattern()->print(OS);
2972 unsigned AddedComplexity = Pattern.getAddedComplexity();
2973 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2974 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
2976 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
2978 EmitPatterns(Other, Indent, OS);
2982 // Remove this code from all of the patterns that share it.
2983 bool ErasedPatterns = EraseCodeLine(Patterns);
2985 bool isPredicate = FirstCodeLine.first;
2987 // Otherwise, every pattern in the list has this line. Emit it.
2990 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
2992 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
2994 // If the next code line is another predicate, and if all of the pattern
2995 // in this group share the same next line, emit it inline now. Do this
2996 // until we run out of common predicates.
2997 while (!ErasedPatterns && Patterns.back().second.back().first) {
2998 // Check that all of fhe patterns in Patterns end with the same predicate.
2999 bool AllEndWithSamePredicate = true;
3000 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3001 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3002 AllEndWithSamePredicate = false;
3005 // If all of the predicates aren't the same, we can't share them.
3006 if (!AllEndWithSamePredicate) break;
3008 // Otherwise we can. Emit it shared now.
3009 OS << " &&\n" << std::string(Indent+4, ' ')
3010 << Patterns.back().second.back().second;
3011 ErasedPatterns = EraseCodeLine(Patterns);
3018 EmitPatterns(Patterns, Indent, OS);
3021 OS << std::string(Indent-2, ' ') << "}\n";
3027 /// CompareByRecordName - An ordering predicate that implements less-than by
3028 /// comparing the names records.
3029 struct CompareByRecordName {
3030 bool operator()(const Record *LHS, const Record *RHS) const {
3031 // Sort by name first.
3032 if (LHS->getName() < RHS->getName()) return true;
3033 // If both names are equal, sort by pointer.
3034 return LHS->getName() == RHS->getName() && LHS < RHS;
3039 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
3040 std::string InstNS = Target.inst_begin()->second.Namespace;
3041 if (!InstNS.empty()) InstNS += "::";
3043 // Group the patterns by their top-level opcodes.
3044 std::map<Record*, std::vector<PatternToMatch*>,
3045 CompareByRecordName> PatternsByOpcode;
3046 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3047 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3048 if (!Node->isLeaf()) {
3049 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3051 const ComplexPattern *CP;
3053 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3054 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3055 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3056 std::vector<Record*> OpNodes = CP->getRootNodes();
3057 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3058 PatternsByOpcode[OpNodes[j]]
3059 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
3062 std::cerr << "Unrecognized opcode '";
3064 std::cerr << "' on tree pattern '";
3066 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3067 std::cerr << "'!\n";
3073 // Emit one Select_* method for each top-level opcode. We do this instead of
3074 // emitting one giant switch statement to support compilers where this will
3075 // result in the recursive functions taking less stack space.
3076 for (std::map<Record*, std::vector<PatternToMatch*>,
3077 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3078 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3079 const std::string &OpName = PBOI->first->getName();
3080 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
3082 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3084 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3085 OpcodeInfo.getNumResults() > 0);
3088 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
3089 << " && N.getValue(0).hasOneUse()) {\n"
3090 << " SDOperand Dummy = "
3091 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
3092 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3093 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3094 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3095 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3096 << " Result = Dummy;\n"
3101 std::vector<PatternToMatch*> &Patterns = PBOI->second;
3102 assert(!Patterns.empty() && "No patterns but map has entry?");
3104 // We want to emit all of the matching code now. However, we want to emit
3105 // the matches in order of minimal cost. Sort the patterns so the least
3106 // cost one is at the start.
3107 std::stable_sort(Patterns.begin(), Patterns.end(),
3108 PatternSortingPredicate(*this));
3110 typedef std::vector<std::pair<bool, std::string> > CodeList;
3111 typedef std::set<std::string> DeclSet;
3113 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3114 std::set<std::pair<bool, std::string> > GeneratedDecl;
3115 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3116 CodeList GeneratedCode;
3117 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3119 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3122 // Scan the code to see if all of the patterns are reachable and if it is
3123 // possible that the last one might not match.
3124 bool mightNotMatch = true;
3125 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3126 CodeList &GeneratedCode = CodeForPatterns[i].second;
3127 mightNotMatch = false;
3129 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3130 if (GeneratedCode[j].first) { // predicate.
3131 mightNotMatch = true;
3136 // If this pattern definitely matches, and if it isn't the last one, the
3137 // patterns after it CANNOT ever match. Error out.
3138 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3139 std::cerr << "Pattern '";
3140 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3141 std::cerr << "' is impossible to select!\n";
3146 // Print all declarations.
3147 for (std::set<std::pair<bool, std::string> >::iterator
3148 I = GeneratedDecl.begin(), E = GeneratedDecl.end(); I != E; ++I)
3150 OS << " SDNode *" << I->second << ";\n";
3152 OS << " SDOperand " << I->second << "(0, 0);\n";
3154 // Loop through and reverse all of the CodeList vectors, as we will be
3155 // accessing them from their logical front, but accessing the end of a
3156 // vector is more efficient.
3157 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3158 CodeList &GeneratedCode = CodeForPatterns[i].second;
3159 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3162 // Next, reverse the list of patterns itself for the same reason.
3163 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3165 // Emit all of the patterns now, grouped together to share code.
3166 EmitPatterns(CodeForPatterns, 2, OS);
3168 // If the last pattern has predicates (which could fail) emit code to catch
3169 // the case where nothing handles a pattern.
3170 if (mightNotMatch) {
3171 OS << " std::cerr << \"Cannot yet select: \";\n";
3172 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3173 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3174 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3175 OS << " N.Val->dump(CurDAG);\n";
3177 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3178 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3179 << " std::cerr << \"intrinsic %\"<< "
3180 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3182 OS << " std::cerr << '\\n';\n"
3188 // Emit boilerplate.
3189 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
3190 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3191 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
3192 << " // Select the flag operand.\n"
3193 << " if (Ops.back().getValueType() == MVT::Flag)\n"
3194 << " Select(Ops.back(), Ops.back());\n"
3195 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3196 << " std::vector<MVT::ValueType> VTs;\n"
3197 << " VTs.push_back(MVT::Other);\n"
3198 << " VTs.push_back(MVT::Flag);\n"
3199 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
3200 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3201 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
3202 << " Result = New.getValue(N.ResNo);\n"
3206 OS << "// The main instruction selector code.\n"
3207 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
3208 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3209 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3210 << "INSTRUCTION_LIST_END)) {\n"
3212 << " return; // Already selected.\n"
3214 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
3215 << " if (CGMI != CodeGenMap.end()) {\n"
3216 << " Result = CGMI->second;\n"
3219 << " switch (N.getOpcode()) {\n"
3220 << " default: break;\n"
3221 << " case ISD::EntryToken: // These leaves remain the same.\n"
3222 << " case ISD::BasicBlock:\n"
3223 << " case ISD::Register:\n"
3224 << " case ISD::HANDLENODE:\n"
3225 << " case ISD::TargetConstant:\n"
3226 << " case ISD::TargetConstantPool:\n"
3227 << " case ISD::TargetFrameIndex:\n"
3228 << " case ISD::TargetJumpTable:\n"
3229 << " case ISD::TargetGlobalAddress: {\n"
3233 << " case ISD::AssertSext:\n"
3234 << " case ISD::AssertZext: {\n"
3235 << " SDOperand Tmp0;\n"
3236 << " Select(Tmp0, N.getOperand(0));\n"
3237 << " if (!N.Val->hasOneUse())\n"
3238 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3239 << "Tmp0.Val, Tmp0.ResNo);\n"
3240 << " Result = Tmp0;\n"
3243 << " case ISD::TokenFactor:\n"
3244 << " if (N.getNumOperands() == 2) {\n"
3245 << " SDOperand Op0, Op1;\n"
3246 << " Select(Op0, N.getOperand(0));\n"
3247 << " Select(Op1, N.getOperand(1));\n"
3249 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
3250 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3251 << "Result.Val, Result.ResNo);\n"
3253 << " std::vector<SDOperand> Ops;\n"
3254 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3255 << " SDOperand Val;\n"
3256 << " Select(Val, N.getOperand(i));\n"
3257 << " Ops.push_back(Val);\n"
3260 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3261 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3262 << "Result.Val, Result.ResNo);\n"
3265 << " case ISD::CopyFromReg: {\n"
3266 << " SDOperand Chain;\n"
3267 << " Select(Chain, N.getOperand(0));\n"
3268 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3269 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
3270 << " if (N.Val->getNumValues() == 2) {\n"
3271 << " if (Chain == N.getOperand(0)) {\n"
3272 << " Result = N; // No change\n"
3275 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
3276 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3278 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3280 << " Result = New.getValue(N.ResNo);\n"
3283 << " SDOperand Flag;\n"
3284 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
3285 << " if (Chain == N.getOperand(0) &&\n"
3286 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3287 << " Result = N; // No change\n"
3290 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
3291 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3293 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3295 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3297 << " Result = New.getValue(N.ResNo);\n"
3301 << " case ISD::CopyToReg: {\n"
3302 << " SDOperand Chain;\n"
3303 << " Select(Chain, N.getOperand(0));\n"
3304 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3305 << " SDOperand Val;\n"
3306 << " Select(Val, N.getOperand(2));\n"
3308 << " if (N.Val->getNumValues() == 1) {\n"
3309 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
3310 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
3311 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3312 << "Result.Val, 0);\n"
3314 << " SDOperand Flag(0, 0);\n"
3315 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
3316 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
3317 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
3318 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
3319 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3320 << "Result.Val, 0);\n"
3321 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3322 << "Result.Val, 1);\n"
3323 << " Result = Result.getValue(N.ResNo);\n"
3327 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
3330 // Loop over all of the case statements, emiting a call to each method we
3332 for (std::map<Record*, std::vector<PatternToMatch*>,
3333 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3334 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3335 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3336 OS << " case " << OpcodeInfo.getEnumName() << ": "
3337 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
3338 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
3341 OS << " } // end of big switch.\n\n"
3342 << " std::cerr << \"Cannot yet select: \";\n"
3343 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3344 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3345 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
3346 << " N.Val->dump(CurDAG);\n"
3348 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3349 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3350 << " std::cerr << \"intrinsic %\"<< "
3351 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3353 << " std::cerr << '\\n';\n"
3358 void DAGISelEmitter::run(std::ostream &OS) {
3359 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3362 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3363 << "// *** instruction selector class. These functions are really "
3366 OS << "// Instance var to keep track of multiply used nodes that have \n"
3367 << "// already been selected.\n"
3368 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
3370 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
3371 << "// and their place handle nodes.\n";
3372 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3373 OS << "// Instance var to keep track of mapping of place handle nodes\n"
3374 << "// and their replacement nodes.\n";
3375 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3378 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3379 << "std::set<SDNode *> &Visited) {\n";
3380 OS << " if (found || !Visited.insert(Use).second) return;\n";
3381 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3382 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3383 OS << " if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3384 OS << " if (N != Def) {\n";
3385 OS << " findNonImmUse(N, Def, found, Visited);\n";
3386 OS << " } else {\n";
3387 OS << " found = true;\n";
3395 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3396 OS << " std::set<SDNode *> Visited;\n";
3397 OS << " bool found = false;\n";
3398 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3399 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3400 OS << " if (N != Def) {\n";
3401 OS << " findNonImmUse(N, Def, found, Visited);\n";
3402 OS << " if (found) break;\n";
3405 OS << " return found;\n";
3409 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
3410 << "// handle node in ReplaceMap.\n";
3411 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3412 << "unsigned RNum) {\n";
3413 OS << " SDOperand N(H, HNum);\n";
3414 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3415 OS << " if (HMI != HandleMap.end()) {\n";
3416 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
3417 OS << " HandleMap.erase(N);\n";
3422 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3423 OS << "// handles.Some handles do not yet have replacements because the\n";
3424 OS << "// nodes they replacements have only dead readers.\n";
3425 OS << "void SelectDanglingHandles() {\n";
3426 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3427 << "HandleMap.begin(),\n"
3428 << " E = HandleMap.end(); I != E; ++I) {\n";
3429 OS << " SDOperand N = I->first;\n";
3430 OS << " SDOperand R;\n";
3431 OS << " Select(R, N.getValue(0));\n";
3432 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
3436 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
3437 OS << "// specific nodes.\n";
3438 OS << "void ReplaceHandles() {\n";
3439 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3440 << "ReplaceMap.begin(),\n"
3441 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3442 OS << " SDOperand From = I->first;\n";
3443 OS << " SDOperand To = I->second;\n";
3444 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3445 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3446 OS << " SDNode *Use = *UI;\n";
3447 OS << " std::vector<SDOperand> Ops;\n";
3448 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3449 OS << " SDOperand O = Use->getOperand(i);\n";
3450 OS << " if (O.Val == From.Val)\n";
3451 OS << " Ops.push_back(To);\n";
3453 OS << " Ops.push_back(O);\n";
3455 OS << " SDOperand U = SDOperand(Use, 0);\n";
3456 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3462 OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3463 OS << "// if the folding were to happen. This is called when, for example,\n";
3464 OS << "// a load is folded into a store. If the store's chain is the load,\n";
3465 OS << "// then the resulting node's input chain would be the load's input\n";
3466 OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3467 OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3468 OS << "// with the other operands along with the input chain of the load.\n";
3469 OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3470 << "SDNode *Chain, SDNode* &OldTF) {\n";
3471 OS << " OldTF = NULL;\n";
3472 OS << " if (N == Chain) {\n";
3473 OS << " return N->getOperand(0);\n";
3474 OS << " } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3475 OS << " N->isOperand(Chain)) {\n";
3476 OS << " SDOperand Ch = SDOperand(Chain, 0);\n";
3477 OS << " std::map<SDOperand, SDOperand>::iterator CGMI = "
3478 << "CodeGenMap.find(Ch);\n";
3479 OS << " if (CGMI != CodeGenMap.end())\n";
3480 OS << " return SDOperand(0, 0);\n";
3481 OS << " OldTF = Chain;\n";
3482 OS << " std::vector<SDOperand> Ops;\n";
3483 OS << " for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3484 OS << " SDOperand Op = Chain->getOperand(i);\n";
3485 OS << " if (Op.Val == N)\n";
3486 OS << " Ops.push_back(N->getOperand(0));\n";
3488 OS << " Ops.push_back(Op);\n";
3490 OS << " return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3492 OS << " return SDOperand(0, 0);\n";
3496 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3497 OS << "SDOperand SelectRoot(SDOperand N) {\n";
3498 OS << " SDOperand ResNode;\n";
3499 OS << " Select(ResNode, N);\n";
3500 OS << " SelectDanglingHandles();\n";
3501 OS << " ReplaceHandles();\n";
3502 OS << " ReplaceMap.clear();\n";
3503 OS << " return ResNode;\n";
3506 Intrinsics = LoadIntrinsics(Records);
3508 ParseNodeTransforms(OS);
3509 ParseComplexPatterns();
3510 ParsePatternFragments(OS);
3511 ParseInstructions();
3514 // Generate variants. For example, commutative patterns can match
3515 // multiple ways. Add them to PatternsToMatch as well.
3519 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3520 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3521 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3522 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
3526 // At this point, we have full information about the 'Patterns' we need to
3527 // parse, both implicitly from instructions as well as from explicit pattern
3528 // definitions. Emit the resultant instruction selector.
3529 EmitInstructionSelector(OS);
3531 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3532 E = PatternFragments.end(); I != E; ++I)
3534 PatternFragments.clear();
3536 Instructions.clear();