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 } else if (getOperator()->isSubClassOf("Instruction")) {
677 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
678 bool MadeChange = false;
679 unsigned NumResults = Inst.getNumResults();
681 assert(NumResults <= 1 &&
682 "Only supports zero or one result instrs!");
683 // Apply the result type to the node
684 if (NumResults == 0) {
685 MadeChange = UpdateNodeType(MVT::isVoid, TP);
687 Record *ResultNode = Inst.getResult(0);
688 assert(ResultNode->isSubClassOf("RegisterClass") &&
689 "Operands should be register classes!");
691 const CodeGenRegisterClass &RC =
692 ISE.getTargetInfo().getRegisterClass(ResultNode);
693 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
696 if (getNumChildren() != Inst.getNumOperands())
697 TP.error("Instruction '" + getOperator()->getName() + " expects " +
698 utostr(Inst.getNumOperands()) + " operands, not " +
699 utostr(getNumChildren()) + " operands!");
700 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
701 Record *OperandNode = Inst.getOperand(i);
703 if (OperandNode->isSubClassOf("RegisterClass")) {
704 const CodeGenRegisterClass &RC =
705 ISE.getTargetInfo().getRegisterClass(OperandNode);
706 //VT = RC.getValueTypeNum(0);
707 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
709 } else if (OperandNode->isSubClassOf("Operand")) {
710 VT = getValueType(OperandNode->getValueAsDef("Type"));
711 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
713 assert(0 && "Unknown operand type!");
716 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
720 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
722 // Node transforms always take one operand.
723 if (getNumChildren() != 1)
724 TP.error("Node transform '" + getOperator()->getName() +
725 "' requires one operand!");
727 // If either the output or input of the xform does not have exact
728 // type info. We assume they must be the same. Otherwise, it is perfectly
729 // legal to transform from one type to a completely different type.
730 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
731 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
732 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
739 /// canPatternMatch - If it is impossible for this pattern to match on this
740 /// target, fill in Reason and return false. Otherwise, return true. This is
741 /// used as a santity check for .td files (to prevent people from writing stuff
742 /// that can never possibly work), and to prevent the pattern permuter from
743 /// generating stuff that is useless.
744 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
745 if (isLeaf()) return true;
747 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
748 if (!getChild(i)->canPatternMatch(Reason, ISE))
751 // If this is an intrinsic, handle cases that would make it not match. For
752 // example, if an operand is required to be an immediate.
753 if (getOperator()->isSubClassOf("Intrinsic")) {
758 // If this node is a commutative operator, check that the LHS isn't an
760 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
761 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
762 // Scan all of the operands of the node and make sure that only the last one
763 // is a constant node.
764 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
765 if (!getChild(i)->isLeaf() &&
766 getChild(i)->getOperator()->getName() == "imm") {
767 Reason = "Immediate value must be on the RHS of commutative operators!";
775 //===----------------------------------------------------------------------===//
776 // TreePattern implementation
779 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
780 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
781 isInputPattern = isInput;
782 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
783 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
786 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
787 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
788 isInputPattern = isInput;
789 Trees.push_back(ParseTreePattern(Pat));
792 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
793 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
794 isInputPattern = isInput;
795 Trees.push_back(Pat);
800 void TreePattern::error(const std::string &Msg) const {
802 throw "In " + TheRecord->getName() + ": " + Msg;
805 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
806 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
807 if (!OpDef) error("Pattern has unexpected operator type!");
808 Record *Operator = OpDef->getDef();
810 if (Operator->isSubClassOf("ValueType")) {
811 // If the operator is a ValueType, then this must be "type cast" of a leaf
813 if (Dag->getNumArgs() != 1)
814 error("Type cast only takes one operand!");
816 Init *Arg = Dag->getArg(0);
817 TreePatternNode *New;
818 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
819 Record *R = DI->getDef();
820 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
821 Dag->setArg(0, new DagInit(DI,
822 std::vector<std::pair<Init*, std::string> >()));
823 return ParseTreePattern(Dag);
825 New = new TreePatternNode(DI);
826 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
827 New = ParseTreePattern(DI);
828 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
829 New = new TreePatternNode(II);
830 if (!Dag->getArgName(0).empty())
831 error("Constant int argument should not have a name!");
832 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
833 // Turn this into an IntInit.
834 Init *II = BI->convertInitializerTo(new IntRecTy());
835 if (II == 0 || !dynamic_cast<IntInit*>(II))
836 error("Bits value must be constants!");
838 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
839 if (!Dag->getArgName(0).empty())
840 error("Constant int argument should not have a name!");
843 error("Unknown leaf value for tree pattern!");
847 // Apply the type cast.
848 New->UpdateNodeType(getValueType(Operator), *this);
849 New->setName(Dag->getArgName(0));
853 // Verify that this is something that makes sense for an operator.
854 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
855 !Operator->isSubClassOf("Instruction") &&
856 !Operator->isSubClassOf("SDNodeXForm") &&
857 !Operator->isSubClassOf("Intrinsic") &&
858 Operator->getName() != "set")
859 error("Unrecognized node '" + Operator->getName() + "'!");
861 // Check to see if this is something that is illegal in an input pattern.
862 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
863 Operator->isSubClassOf("SDNodeXForm")))
864 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
866 std::vector<TreePatternNode*> Children;
868 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
869 Init *Arg = Dag->getArg(i);
870 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
871 Children.push_back(ParseTreePattern(DI));
872 if (Children.back()->getName().empty())
873 Children.back()->setName(Dag->getArgName(i));
874 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
875 Record *R = DefI->getDef();
876 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
877 // TreePatternNode if its own.
878 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
879 Dag->setArg(i, new DagInit(DefI,
880 std::vector<std::pair<Init*, std::string> >()));
881 --i; // Revisit this node...
883 TreePatternNode *Node = new TreePatternNode(DefI);
884 Node->setName(Dag->getArgName(i));
885 Children.push_back(Node);
888 if (R->getName() == "node") {
889 if (Dag->getArgName(i).empty())
890 error("'node' argument requires a name to match with operand list");
891 Args.push_back(Dag->getArgName(i));
894 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
895 TreePatternNode *Node = new TreePatternNode(II);
896 if (!Dag->getArgName(i).empty())
897 error("Constant int argument should not have a name!");
898 Children.push_back(Node);
899 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
900 // Turn this into an IntInit.
901 Init *II = BI->convertInitializerTo(new IntRecTy());
902 if (II == 0 || !dynamic_cast<IntInit*>(II))
903 error("Bits value must be constants!");
905 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
906 if (!Dag->getArgName(i).empty())
907 error("Constant int argument should not have a name!");
908 Children.push_back(Node);
913 error("Unknown leaf value for tree pattern!");
917 // If the operator is an intrinsic, then this is just syntactic sugar for for
918 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
919 // convert the intrinsic name to a number.
920 if (Operator->isSubClassOf("Intrinsic")) {
921 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
922 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
924 // If this intrinsic returns void, it must have side-effects and thus a
926 if (Int.ArgVTs[0] == MVT::isVoid) {
927 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
928 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
929 // Has side-effects, requires chain.
930 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
932 // Otherwise, no chain.
933 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
936 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
937 Children.insert(Children.begin(), IIDNode);
940 return new TreePatternNode(Operator, Children);
943 /// InferAllTypes - Infer/propagate as many types throughout the expression
944 /// patterns as possible. Return true if all types are infered, false
945 /// otherwise. Throw an exception if a type contradiction is found.
946 bool TreePattern::InferAllTypes() {
947 bool MadeChange = true;
950 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
951 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
954 bool HasUnresolvedTypes = false;
955 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
956 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
957 return !HasUnresolvedTypes;
960 void TreePattern::print(std::ostream &OS) const {
961 OS << getRecord()->getName();
963 OS << "(" << Args[0];
964 for (unsigned i = 1, e = Args.size(); i != e; ++i)
965 OS << ", " << Args[i];
970 if (Trees.size() > 1)
972 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
978 if (Trees.size() > 1)
982 void TreePattern::dump() const { print(std::cerr); }
986 //===----------------------------------------------------------------------===//
987 // DAGISelEmitter implementation
990 // Parse all of the SDNode definitions for the target, populating SDNodes.
991 void DAGISelEmitter::ParseNodeInfo() {
992 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
993 while (!Nodes.empty()) {
994 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
998 // Get the buildin intrinsic nodes.
999 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1000 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1001 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1004 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1005 /// map, and emit them to the file as functions.
1006 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1007 OS << "\n// Node transformations.\n";
1008 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1009 while (!Xforms.empty()) {
1010 Record *XFormNode = Xforms.back();
1011 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1012 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1013 SDNodeXForms.insert(std::make_pair(XFormNode,
1014 std::make_pair(SDNode, Code)));
1016 if (!Code.empty()) {
1017 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1018 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1020 OS << "inline SDOperand Transform_" << XFormNode->getName()
1021 << "(SDNode *" << C2 << ") {\n";
1022 if (ClassName != "SDNode")
1023 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1024 OS << Code << "\n}\n";
1031 void DAGISelEmitter::ParseComplexPatterns() {
1032 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1033 while (!AMs.empty()) {
1034 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1040 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1041 /// file, building up the PatternFragments map. After we've collected them all,
1042 /// inline fragments together as necessary, so that there are no references left
1043 /// inside a pattern fragment to a pattern fragment.
1045 /// This also emits all of the predicate functions to the output file.
1047 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
1048 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1050 // First step, parse all of the fragments and emit predicate functions.
1051 OS << "\n// Predicate functions.\n";
1052 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1053 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1054 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1055 PatternFragments[Fragments[i]] = P;
1057 // Validate the argument list, converting it to map, to discard duplicates.
1058 std::vector<std::string> &Args = P->getArgList();
1059 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1061 if (OperandsMap.count(""))
1062 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1064 // Parse the operands list.
1065 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1066 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1067 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
1068 P->error("Operands list should start with '(ops ... '!");
1070 // Copy over the arguments.
1072 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1073 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1074 static_cast<DefInit*>(OpsList->getArg(j))->
1075 getDef()->getName() != "node")
1076 P->error("Operands list should all be 'node' values.");
1077 if (OpsList->getArgName(j).empty())
1078 P->error("Operands list should have names for each operand!");
1079 if (!OperandsMap.count(OpsList->getArgName(j)))
1080 P->error("'" + OpsList->getArgName(j) +
1081 "' does not occur in pattern or was multiply specified!");
1082 OperandsMap.erase(OpsList->getArgName(j));
1083 Args.push_back(OpsList->getArgName(j));
1086 if (!OperandsMap.empty())
1087 P->error("Operands list does not contain an entry for operand '" +
1088 *OperandsMap.begin() + "'!");
1090 // If there is a code init for this fragment, emit the predicate code and
1091 // keep track of the fact that this fragment uses it.
1092 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1093 if (!Code.empty()) {
1094 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
1095 std::string ClassName =
1096 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1097 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1099 OS << "inline bool Predicate_" << Fragments[i]->getName()
1100 << "(SDNode *" << C2 << ") {\n";
1101 if (ClassName != "SDNode")
1102 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1103 OS << Code << "\n}\n";
1104 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1107 // If there is a node transformation corresponding to this, keep track of
1109 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1110 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1111 P->getOnlyTree()->setTransformFn(Transform);
1116 // Now that we've parsed all of the tree fragments, do a closure on them so
1117 // that there are not references to PatFrags left inside of them.
1118 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1119 E = PatternFragments.end(); I != E; ++I) {
1120 TreePattern *ThePat = I->second;
1121 ThePat->InlinePatternFragments();
1123 // Infer as many types as possible. Don't worry about it if we don't infer
1124 // all of them, some may depend on the inputs of the pattern.
1126 ThePat->InferAllTypes();
1128 // If this pattern fragment is not supported by this target (no types can
1129 // satisfy its constraints), just ignore it. If the bogus pattern is
1130 // actually used by instructions, the type consistency error will be
1134 // If debugging, print out the pattern fragment result.
1135 DEBUG(ThePat->dump());
1139 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1140 /// instruction input. Return true if this is a real use.
1141 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1142 std::map<std::string, TreePatternNode*> &InstInputs,
1143 std::vector<Record*> &InstImpInputs) {
1144 // No name -> not interesting.
1145 if (Pat->getName().empty()) {
1146 if (Pat->isLeaf()) {
1147 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1148 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1149 I->error("Input " + DI->getDef()->getName() + " must be named!");
1150 else if (DI && DI->getDef()->isSubClassOf("Register"))
1151 InstImpInputs.push_back(DI->getDef());
1157 if (Pat->isLeaf()) {
1158 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1159 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1162 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1163 Rec = Pat->getOperator();
1166 // SRCVALUE nodes are ignored.
1167 if (Rec->getName() == "srcvalue")
1170 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1175 if (Slot->isLeaf()) {
1176 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1178 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1179 SlotRec = Slot->getOperator();
1182 // Ensure that the inputs agree if we've already seen this input.
1184 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1185 if (Slot->getExtTypes() != Pat->getExtTypes())
1186 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1191 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1192 /// part of "I", the instruction), computing the set of inputs and outputs of
1193 /// the pattern. Report errors if we see anything naughty.
1194 void DAGISelEmitter::
1195 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1196 std::map<std::string, TreePatternNode*> &InstInputs,
1197 std::map<std::string, TreePatternNode*>&InstResults,
1198 std::vector<Record*> &InstImpInputs,
1199 std::vector<Record*> &InstImpResults) {
1200 if (Pat->isLeaf()) {
1201 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1202 if (!isUse && Pat->getTransformFn())
1203 I->error("Cannot specify a transform function for a non-input value!");
1205 } else if (Pat->getOperator()->getName() != "set") {
1206 // If this is not a set, verify that the children nodes are not void typed,
1208 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1209 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1210 I->error("Cannot have void nodes inside of patterns!");
1211 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1212 InstImpInputs, InstImpResults);
1215 // If this is a non-leaf node with no children, treat it basically as if
1216 // it were a leaf. This handles nodes like (imm).
1218 if (Pat->getNumChildren() == 0)
1219 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1221 if (!isUse && Pat->getTransformFn())
1222 I->error("Cannot specify a transform function for a non-input value!");
1226 // Otherwise, this is a set, validate and collect instruction results.
1227 if (Pat->getNumChildren() == 0)
1228 I->error("set requires operands!");
1229 else if (Pat->getNumChildren() & 1)
1230 I->error("set requires an even number of operands");
1232 if (Pat->getTransformFn())
1233 I->error("Cannot specify a transform function on a set node!");
1235 // Check the set destinations.
1236 unsigned NumValues = Pat->getNumChildren()/2;
1237 for (unsigned i = 0; i != NumValues; ++i) {
1238 TreePatternNode *Dest = Pat->getChild(i);
1239 if (!Dest->isLeaf())
1240 I->error("set destination should be a register!");
1242 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1244 I->error("set destination should be a register!");
1246 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1247 if (Dest->getName().empty())
1248 I->error("set destination must have a name!");
1249 if (InstResults.count(Dest->getName()))
1250 I->error("cannot set '" + Dest->getName() +"' multiple times");
1251 InstResults[Dest->getName()] = Dest;
1252 } else if (Val->getDef()->isSubClassOf("Register")) {
1253 InstImpResults.push_back(Val->getDef());
1255 I->error("set destination should be a register!");
1258 // Verify and collect info from the computation.
1259 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1260 InstInputs, InstResults,
1261 InstImpInputs, InstImpResults);
1265 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1266 /// any fragments involved. This populates the Instructions list with fully
1267 /// resolved instructions.
1268 void DAGISelEmitter::ParseInstructions() {
1269 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1271 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1274 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1275 LI = Instrs[i]->getValueAsListInit("Pattern");
1277 // If there is no pattern, only collect minimal information about the
1278 // instruction for its operand list. We have to assume that there is one
1279 // result, as we have no detailed info.
1280 if (!LI || LI->getSize() == 0) {
1281 std::vector<Record*> Results;
1282 std::vector<Record*> Operands;
1284 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1286 if (InstInfo.OperandList.size() != 0) {
1287 // FIXME: temporary hack...
1288 if (InstInfo.noResults) {
1289 // These produce no results
1290 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1291 Operands.push_back(InstInfo.OperandList[j].Rec);
1293 // Assume the first operand is the result.
1294 Results.push_back(InstInfo.OperandList[0].Rec);
1296 // The rest are inputs.
1297 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1298 Operands.push_back(InstInfo.OperandList[j].Rec);
1302 // Create and insert the instruction.
1303 std::vector<Record*> ImpResults;
1304 std::vector<Record*> ImpOperands;
1305 Instructions.insert(std::make_pair(Instrs[i],
1306 DAGInstruction(0, Results, Operands, ImpResults,
1308 continue; // no pattern.
1311 // Parse the instruction.
1312 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1313 // Inline pattern fragments into it.
1314 I->InlinePatternFragments();
1316 // Infer as many types as possible. If we cannot infer all of them, we can
1317 // never do anything with this instruction pattern: report it to the user.
1318 if (!I->InferAllTypes())
1319 I->error("Could not infer all types in pattern!");
1321 // InstInputs - Keep track of all of the inputs of the instruction, along
1322 // with the record they are declared as.
1323 std::map<std::string, TreePatternNode*> InstInputs;
1325 // InstResults - Keep track of all the virtual registers that are 'set'
1326 // in the instruction, including what reg class they are.
1327 std::map<std::string, TreePatternNode*> InstResults;
1329 std::vector<Record*> InstImpInputs;
1330 std::vector<Record*> InstImpResults;
1332 // Verify that the top-level forms in the instruction are of void type, and
1333 // fill in the InstResults map.
1334 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1335 TreePatternNode *Pat = I->getTree(j);
1336 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1337 I->error("Top-level forms in instruction pattern should have"
1340 // Find inputs and outputs, and verify the structure of the uses/defs.
1341 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1342 InstImpInputs, InstImpResults);
1345 // Now that we have inputs and outputs of the pattern, inspect the operands
1346 // list for the instruction. This determines the order that operands are
1347 // added to the machine instruction the node corresponds to.
1348 unsigned NumResults = InstResults.size();
1350 // Parse the operands list from the (ops) list, validating it.
1351 std::vector<std::string> &Args = I->getArgList();
1352 assert(Args.empty() && "Args list should still be empty here!");
1353 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1355 // Check that all of the results occur first in the list.
1356 std::vector<Record*> Results;
1357 TreePatternNode *Res0Node = NULL;
1358 for (unsigned i = 0; i != NumResults; ++i) {
1359 if (i == CGI.OperandList.size())
1360 I->error("'" + InstResults.begin()->first +
1361 "' set but does not appear in operand list!");
1362 const std::string &OpName = CGI.OperandList[i].Name;
1364 // Check that it exists in InstResults.
1365 TreePatternNode *RNode = InstResults[OpName];
1367 I->error("Operand $" + OpName + " does not exist in operand list!");
1371 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1373 I->error("Operand $" + OpName + " should be a set destination: all "
1374 "outputs must occur before inputs in operand list!");
1376 if (CGI.OperandList[i].Rec != R)
1377 I->error("Operand $" + OpName + " class mismatch!");
1379 // Remember the return type.
1380 Results.push_back(CGI.OperandList[i].Rec);
1382 // Okay, this one checks out.
1383 InstResults.erase(OpName);
1386 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1387 // the copy while we're checking the inputs.
1388 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1390 std::vector<TreePatternNode*> ResultNodeOperands;
1391 std::vector<Record*> Operands;
1392 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1393 const std::string &OpName = CGI.OperandList[i].Name;
1395 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1397 if (!InstInputsCheck.count(OpName))
1398 I->error("Operand $" + OpName +
1399 " does not appear in the instruction pattern");
1400 TreePatternNode *InVal = InstInputsCheck[OpName];
1401 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1403 if (InVal->isLeaf() &&
1404 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1405 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1406 if (CGI.OperandList[i].Rec != InRec &&
1407 !InRec->isSubClassOf("ComplexPattern"))
1408 I->error("Operand $" + OpName + "'s register class disagrees"
1409 " between the operand and pattern");
1411 Operands.push_back(CGI.OperandList[i].Rec);
1413 // Construct the result for the dest-pattern operand list.
1414 TreePatternNode *OpNode = InVal->clone();
1416 // No predicate is useful on the result.
1417 OpNode->setPredicateFn("");
1419 // Promote the xform function to be an explicit node if set.
1420 if (Record *Xform = OpNode->getTransformFn()) {
1421 OpNode->setTransformFn(0);
1422 std::vector<TreePatternNode*> Children;
1423 Children.push_back(OpNode);
1424 OpNode = new TreePatternNode(Xform, Children);
1427 ResultNodeOperands.push_back(OpNode);
1430 if (!InstInputsCheck.empty())
1431 I->error("Input operand $" + InstInputsCheck.begin()->first +
1432 " occurs in pattern but not in operands list!");
1434 TreePatternNode *ResultPattern =
1435 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1436 // Copy fully inferred output node type to instruction result pattern.
1438 ResultPattern->setTypes(Res0Node->getExtTypes());
1440 // Create and insert the instruction.
1441 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1442 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1444 // Use a temporary tree pattern to infer all types and make sure that the
1445 // constructed result is correct. This depends on the instruction already
1446 // being inserted into the Instructions map.
1447 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1448 Temp.InferAllTypes();
1450 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1451 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1456 // If we can, convert the instructions to be patterns that are matched!
1457 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1458 E = Instructions.end(); II != E; ++II) {
1459 DAGInstruction &TheInst = II->second;
1460 TreePattern *I = TheInst.getPattern();
1461 if (I == 0) continue; // No pattern.
1463 if (I->getNumTrees() != 1) {
1464 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1467 TreePatternNode *Pattern = I->getTree(0);
1468 TreePatternNode *SrcPattern;
1469 if (Pattern->getOperator()->getName() == "set") {
1470 if (Pattern->getNumChildren() != 2)
1471 continue; // Not a set of a single value (not handled so far)
1473 SrcPattern = Pattern->getChild(1)->clone();
1475 // Not a set (store or something?)
1476 SrcPattern = Pattern;
1480 if (!SrcPattern->canPatternMatch(Reason, *this))
1481 I->error("Instruction can never match: " + Reason);
1483 Record *Instr = II->first;
1484 TreePatternNode *DstPattern = TheInst.getResultPattern();
1486 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1487 SrcPattern, DstPattern));
1491 void DAGISelEmitter::ParsePatterns() {
1492 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1494 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1495 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1496 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1498 // Inline pattern fragments into it.
1499 Pattern->InlinePatternFragments();
1501 // Infer as many types as possible. If we cannot infer all of them, we can
1502 // never do anything with this pattern: report it to the user.
1503 if (!Pattern->InferAllTypes())
1504 Pattern->error("Could not infer all types in pattern!");
1506 // Validate that the input pattern is correct.
1508 std::map<std::string, TreePatternNode*> InstInputs;
1509 std::map<std::string, TreePatternNode*> InstResults;
1510 std::vector<Record*> InstImpInputs;
1511 std::vector<Record*> InstImpResults;
1512 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1513 InstInputs, InstResults,
1514 InstImpInputs, InstImpResults);
1517 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1518 if (LI->getSize() == 0) continue; // no pattern.
1520 // Parse the instruction.
1521 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1523 // Inline pattern fragments into it.
1524 Result->InlinePatternFragments();
1526 // Infer as many types as possible. If we cannot infer all of them, we can
1527 // never do anything with this pattern: report it to the user.
1528 if (!Result->InferAllTypes())
1529 Result->error("Could not infer all types in pattern result!");
1531 if (Result->getNumTrees() != 1)
1532 Result->error("Cannot handle instructions producing instructions "
1533 "with temporaries yet!");
1535 // Promote the xform function to be an explicit node if set.
1536 std::vector<TreePatternNode*> ResultNodeOperands;
1537 TreePatternNode *DstPattern = Result->getOnlyTree();
1538 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1539 TreePatternNode *OpNode = DstPattern->getChild(ii);
1540 if (Record *Xform = OpNode->getTransformFn()) {
1541 OpNode->setTransformFn(0);
1542 std::vector<TreePatternNode*> Children;
1543 Children.push_back(OpNode);
1544 OpNode = new TreePatternNode(Xform, Children);
1546 ResultNodeOperands.push_back(OpNode);
1548 DstPattern = Result->getOnlyTree();
1549 if (!DstPattern->isLeaf())
1550 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1551 ResultNodeOperands);
1552 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1553 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1554 Temp.InferAllTypes();
1557 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1558 Pattern->error("Pattern can never match: " + Reason);
1561 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1562 Pattern->getOnlyTree(),
1563 Temp.getOnlyTree()));
1567 /// CombineChildVariants - Given a bunch of permutations of each child of the
1568 /// 'operator' node, put them together in all possible ways.
1569 static void CombineChildVariants(TreePatternNode *Orig,
1570 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1571 std::vector<TreePatternNode*> &OutVariants,
1572 DAGISelEmitter &ISE) {
1573 // Make sure that each operand has at least one variant to choose from.
1574 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1575 if (ChildVariants[i].empty())
1578 // The end result is an all-pairs construction of the resultant pattern.
1579 std::vector<unsigned> Idxs;
1580 Idxs.resize(ChildVariants.size());
1581 bool NotDone = true;
1583 // Create the variant and add it to the output list.
1584 std::vector<TreePatternNode*> NewChildren;
1585 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1586 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1587 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1589 // Copy over properties.
1590 R->setName(Orig->getName());
1591 R->setPredicateFn(Orig->getPredicateFn());
1592 R->setTransformFn(Orig->getTransformFn());
1593 R->setTypes(Orig->getExtTypes());
1595 // If this pattern cannot every match, do not include it as a variant.
1596 std::string ErrString;
1597 if (!R->canPatternMatch(ErrString, ISE)) {
1600 bool AlreadyExists = false;
1602 // Scan to see if this pattern has already been emitted. We can get
1603 // duplication due to things like commuting:
1604 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1605 // which are the same pattern. Ignore the dups.
1606 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1607 if (R->isIsomorphicTo(OutVariants[i])) {
1608 AlreadyExists = true;
1615 OutVariants.push_back(R);
1618 // Increment indices to the next permutation.
1620 // Look for something we can increment without causing a wrap-around.
1621 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1622 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1623 NotDone = true; // Found something to increment.
1631 /// CombineChildVariants - A helper function for binary operators.
1633 static void CombineChildVariants(TreePatternNode *Orig,
1634 const std::vector<TreePatternNode*> &LHS,
1635 const std::vector<TreePatternNode*> &RHS,
1636 std::vector<TreePatternNode*> &OutVariants,
1637 DAGISelEmitter &ISE) {
1638 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1639 ChildVariants.push_back(LHS);
1640 ChildVariants.push_back(RHS);
1641 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1645 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1646 std::vector<TreePatternNode *> &Children) {
1647 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1648 Record *Operator = N->getOperator();
1650 // Only permit raw nodes.
1651 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1652 N->getTransformFn()) {
1653 Children.push_back(N);
1657 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1658 Children.push_back(N->getChild(0));
1660 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1662 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1663 Children.push_back(N->getChild(1));
1665 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1668 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1669 /// the (potentially recursive) pattern by using algebraic laws.
1671 static void GenerateVariantsOf(TreePatternNode *N,
1672 std::vector<TreePatternNode*> &OutVariants,
1673 DAGISelEmitter &ISE) {
1674 // We cannot permute leaves.
1676 OutVariants.push_back(N);
1680 // Look up interesting info about the node.
1681 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1683 // If this node is associative, reassociate.
1684 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1685 // Reassociate by pulling together all of the linked operators
1686 std::vector<TreePatternNode*> MaximalChildren;
1687 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1689 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1691 if (MaximalChildren.size() == 3) {
1692 // Find the variants of all of our maximal children.
1693 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1694 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1695 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1696 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1698 // There are only two ways we can permute the tree:
1699 // (A op B) op C and A op (B op C)
1700 // Within these forms, we can also permute A/B/C.
1702 // Generate legal pair permutations of A/B/C.
1703 std::vector<TreePatternNode*> ABVariants;
1704 std::vector<TreePatternNode*> BAVariants;
1705 std::vector<TreePatternNode*> ACVariants;
1706 std::vector<TreePatternNode*> CAVariants;
1707 std::vector<TreePatternNode*> BCVariants;
1708 std::vector<TreePatternNode*> CBVariants;
1709 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1710 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1711 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1712 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1713 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1714 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1716 // Combine those into the result: (x op x) op x
1717 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1718 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1719 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1720 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1721 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1722 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1724 // Combine those into the result: x op (x op x)
1725 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1726 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1727 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1728 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1729 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1730 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1735 // Compute permutations of all children.
1736 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1737 ChildVariants.resize(N->getNumChildren());
1738 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1739 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1741 // Build all permutations based on how the children were formed.
1742 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1744 // If this node is commutative, consider the commuted order.
1745 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1746 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1747 // Consider the commuted order.
1748 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1754 // GenerateVariants - Generate variants. For example, commutative patterns can
1755 // match multiple ways. Add them to PatternsToMatch as well.
1756 void DAGISelEmitter::GenerateVariants() {
1758 DEBUG(std::cerr << "Generating instruction variants.\n");
1760 // Loop over all of the patterns we've collected, checking to see if we can
1761 // generate variants of the instruction, through the exploitation of
1762 // identities. This permits the target to provide agressive matching without
1763 // the .td file having to contain tons of variants of instructions.
1765 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1766 // intentionally do not reconsider these. Any variants of added patterns have
1767 // already been added.
1769 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1770 std::vector<TreePatternNode*> Variants;
1771 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1773 assert(!Variants.empty() && "Must create at least original variant!");
1774 Variants.erase(Variants.begin()); // Remove the original pattern.
1776 if (Variants.empty()) // No variants for this pattern.
1779 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1780 PatternsToMatch[i].getSrcPattern()->dump();
1783 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1784 TreePatternNode *Variant = Variants[v];
1786 DEBUG(std::cerr << " VAR#" << v << ": ";
1790 // Scan to see if an instruction or explicit pattern already matches this.
1791 bool AlreadyExists = false;
1792 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1793 // Check to see if this variant already exists.
1794 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1795 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1796 AlreadyExists = true;
1800 // If we already have it, ignore the variant.
1801 if (AlreadyExists) continue;
1803 // Otherwise, add it to the list of patterns we have.
1805 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1806 Variant, PatternsToMatch[i].getDstPattern()));
1809 DEBUG(std::cerr << "\n");
1814 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1816 static bool NodeIsComplexPattern(TreePatternNode *N)
1818 return (N->isLeaf() &&
1819 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1820 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1821 isSubClassOf("ComplexPattern"));
1824 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1825 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1826 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1827 DAGISelEmitter &ISE)
1830 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1831 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1832 isSubClassOf("ComplexPattern")) {
1833 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1839 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1840 /// patterns before small ones. This is used to determine the size of a
1842 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1843 assert(isExtIntegerInVTs(P->getExtTypes()) ||
1844 isExtFloatingPointInVTs(P->getExtTypes()) ||
1845 P->getExtTypeNum(0) == MVT::isVoid ||
1846 P->getExtTypeNum(0) == MVT::Flag &&
1847 "Not a valid pattern node to size!");
1848 unsigned Size = 2; // The node itself.
1849 // If the root node is a ConstantSDNode, increases its size.
1850 // e.g. (set R32:$dst, 0).
1851 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1854 // FIXME: This is a hack to statically increase the priority of patterns
1855 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1856 // Later we can allow complexity / cost for each pattern to be (optionally)
1857 // specified. To get best possible pattern match we'll need to dynamically
1858 // calculate the complexity of all patterns a dag can potentially map to.
1859 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1861 Size += AM->getNumOperands() * 2;
1863 // If this node has some predicate function that must match, it adds to the
1864 // complexity of this node.
1865 if (!P->getPredicateFn().empty())
1868 // Count children in the count if they are also nodes.
1869 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1870 TreePatternNode *Child = P->getChild(i);
1871 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1872 Size += getPatternSize(Child, ISE);
1873 else if (Child->isLeaf()) {
1874 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1875 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
1876 else if (NodeIsComplexPattern(Child))
1877 Size += getPatternSize(Child, ISE);
1878 else if (!Child->getPredicateFn().empty())
1886 /// getResultPatternCost - Compute the number of instructions for this pattern.
1887 /// This is a temporary hack. We should really include the instruction
1888 /// latencies in this calculation.
1889 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
1890 if (P->isLeaf()) return 0;
1893 Record *Op = P->getOperator();
1894 if (Op->isSubClassOf("Instruction")) {
1896 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1897 if (II.usesCustomDAGSchedInserter)
1900 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1901 Cost += getResultPatternCost(P->getChild(i), ISE);
1905 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1906 // In particular, we want to match maximal patterns first and lowest cost within
1907 // a particular complexity first.
1908 struct PatternSortingPredicate {
1909 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1910 DAGISelEmitter &ISE;
1912 bool operator()(PatternToMatch *LHS,
1913 PatternToMatch *RHS) {
1914 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1915 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1916 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1917 if (LHSSize < RHSSize) return false;
1919 // If the patterns have equal complexity, compare generated instruction cost
1920 return getResultPatternCost(LHS->getDstPattern(), ISE) <
1921 getResultPatternCost(RHS->getDstPattern(), ISE);
1925 /// getRegisterValueType - Look up and return the first ValueType of specified
1926 /// RegisterClass record
1927 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1928 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1929 return RC->getValueTypeNum(0);
1934 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1935 /// type information from it.
1936 static void RemoveAllTypes(TreePatternNode *N) {
1939 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1940 RemoveAllTypes(N->getChild(i));
1943 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1944 Record *N = Records.getDef(Name);
1945 if (!N || !N->isSubClassOf("SDNode")) {
1946 std::cerr << "Error getting SDNode '" << Name << "'!\n";
1952 /// NodeHasProperty - return true if TreePatternNode has the specified
1954 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1955 DAGISelEmitter &ISE)
1957 if (N->isLeaf()) return false;
1958 Record *Operator = N->getOperator();
1959 if (!Operator->isSubClassOf("SDNode")) return false;
1961 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1962 return NodeInfo.hasProperty(Property);
1965 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1966 DAGISelEmitter &ISE)
1968 if (NodeHasProperty(N, Property, ISE))
1971 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1972 TreePatternNode *Child = N->getChild(i);
1973 if (PatternHasProperty(Child, Property, ISE))
1980 class PatternCodeEmitter {
1982 DAGISelEmitter &ISE;
1985 ListInit *Predicates;
1986 // Instruction selector pattern.
1987 TreePatternNode *Pattern;
1988 // Matched instruction.
1989 TreePatternNode *Instruction;
1991 // Node to name mapping
1992 std::map<std::string, std::string> VariableMap;
1993 // Node to operator mapping
1994 std::map<std::string, Record*> OperatorMap;
1995 // Names of all the folded nodes which produce chains.
1996 std::vector<std::pair<std::string, unsigned> > FoldedChains;
1997 std::set<std::string> Duplicates;
1999 /// GeneratedCode - This is the buffer that we emit code to. The first bool
2000 /// indicates whether this is an exit predicate (something that should be
2001 /// tested, and if true, the match fails) [when true] or normal code to emit
2003 std::vector<std::pair<bool, std::string> > &GeneratedCode;
2004 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2005 /// the set of patterns for each top-level opcode.
2006 std::set<std::pair<bool, std::string> > &GeneratedDecl;
2008 std::string ChainName;
2013 void emitCheck(const std::string &S) {
2015 GeneratedCode.push_back(std::make_pair(true, S));
2017 void emitCode(const std::string &S) {
2019 GeneratedCode.push_back(std::make_pair(false, S));
2021 void emitDecl(const std::string &S, bool isSDNode=false) {
2022 assert(!S.empty() && "Invalid declaration");
2023 GeneratedDecl.insert(std::make_pair(isSDNode, S));
2026 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2027 TreePatternNode *pattern, TreePatternNode *instr,
2028 std::vector<std::pair<bool, std::string> > &gc,
2029 std::set<std::pair<bool, std::string> > &gd,
2031 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2032 GeneratedCode(gc), GeneratedDecl(gd),
2033 NewTF(false), DoReplace(dorep), TmpNo(0) {}
2035 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2036 /// if the match fails. At this point, we already know that the opcode for N
2037 /// matches, and the SDNode for the result has the RootName specified name.
2038 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2039 const std::string &RootName, const std::string &ParentName,
2040 const std::string &ChainSuffix, bool &FoundChain) {
2041 bool isRoot = (P == NULL);
2042 // Emit instruction predicates. Each predicate is just a string for now.
2044 std::string PredicateCheck;
2045 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2046 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2047 Record *Def = Pred->getDef();
2048 if (!Def->isSubClassOf("Predicate")) {
2050 assert(0 && "Unknown predicate type!");
2052 if (!PredicateCheck.empty())
2053 PredicateCheck += " || ";
2054 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2058 emitCheck(PredicateCheck);
2062 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2063 emitCheck("cast<ConstantSDNode>(" + RootName +
2064 ")->getSignExtended() == " + itostr(II->getValue()));
2066 } else if (!NodeIsComplexPattern(N)) {
2067 assert(0 && "Cannot match this as a leaf value!");
2072 // If this node has a name associated with it, capture it in VariableMap. If
2073 // we already saw this in the pattern, emit code to verify dagness.
2074 if (!N->getName().empty()) {
2075 std::string &VarMapEntry = VariableMap[N->getName()];
2076 if (VarMapEntry.empty()) {
2077 VarMapEntry = RootName;
2079 // If we get here, this is a second reference to a specific name. Since
2080 // we already have checked that the first reference is valid, we don't
2081 // have to recursively match it, just check that it's the same as the
2082 // previously named thing.
2083 emitCheck(VarMapEntry + " == " + RootName);
2088 OperatorMap[N->getName()] = N->getOperator();
2092 // Emit code to load the child nodes and match their contents recursively.
2094 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2095 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2096 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
2097 bool EmittedUseCheck = false;
2098 bool EmittedSlctedCheck = false;
2103 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2104 // Multiple uses of actual result?
2105 emitCheck(RootName + ".hasOneUse()");
2106 EmittedUseCheck = true;
2107 // hasOneUse() check is not strong enough. If the original node has
2108 // already been selected, it may have been replaced with another.
2109 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
2110 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2113 EmittedSlctedCheck = true;
2115 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2117 // This a workaround for this problem:
2122 // [XX]--/ \- [flag : cmp]
2127 // cmp + br should be considered as a single node as they are flagged
2128 // together. So, if the ld is folded into the cmp, the XX node in the
2129 // graph is now both an operand and a use of the ld/cmp/br node.
2130 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2131 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2133 // If the immediate use can somehow reach this node through another
2134 // path, then can't fold it either or it will create a cycle.
2135 // e.g. In the following diagram, XX can reach ld through YY. If
2136 // ld is folded into XX, then YY is both a predecessor and a successor
2146 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2147 if (PInfo.getNumOperands() > 1 ||
2148 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2149 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2150 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2151 if (PInfo.getNumOperands() > 1) {
2152 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2155 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2156 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2163 ChainName = "Chain" + ChainSuffix;
2164 emitDecl(ChainName);
2166 // FIXME: temporary workaround for a common case where chain
2167 // is a TokenFactor and the previous "inner" chain is an operand.
2169 emitDecl("OldTF", true);
2170 emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2171 RootName + ".Val, Chain.Val, OldTF)).Val");
2174 emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2179 // Don't fold any node which reads or writes a flag and has multiple uses.
2180 // FIXME: We really need to separate the concepts of flag and "glue". Those
2181 // real flag results, e.g. X86CMP output, can have multiple uses.
2182 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2185 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2186 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2187 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
2188 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2189 if (!EmittedUseCheck) {
2190 // Multiple uses of actual result?
2191 emitCheck(RootName + ".hasOneUse()");
2193 if (!EmittedSlctedCheck)
2194 // hasOneUse() check is not strong enough. If the original node has
2195 // already been selected, it may have been replaced with another.
2196 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
2197 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2201 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2202 emitDecl(RootName + utostr(OpNo));
2203 emitCode(RootName + utostr(OpNo) + " = " +
2204 RootName + ".getOperand(" +utostr(OpNo) + ");");
2205 TreePatternNode *Child = N->getChild(i);
2207 if (!Child->isLeaf()) {
2208 // If it's not a leaf, recursively match.
2209 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2210 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
2211 CInfo.getEnumName());
2212 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2213 ChainSuffix + utostr(OpNo), FoundChain);
2214 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2215 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2216 CInfo.getNumResults()));
2218 // If this child has a name associated with it, capture it in VarMap. If
2219 // we already saw this in the pattern, emit code to verify dagness.
2220 if (!Child->getName().empty()) {
2221 std::string &VarMapEntry = VariableMap[Child->getName()];
2222 if (VarMapEntry.empty()) {
2223 VarMapEntry = RootName + utostr(OpNo);
2225 // If we get here, this is a second reference to a specific name.
2226 // Since we already have checked that the first reference is valid,
2227 // we don't have to recursively match it, just check that it's the
2228 // same as the previously named thing.
2229 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2230 Duplicates.insert(RootName + utostr(OpNo));
2235 // Handle leaves of various types.
2236 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2237 Record *LeafRec = DI->getDef();
2238 if (LeafRec->isSubClassOf("RegisterClass")) {
2239 // Handle register references. Nothing to do here.
2240 } else if (LeafRec->isSubClassOf("Register")) {
2241 // Handle register references.
2242 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2243 // Handle complex pattern. Nothing to do here.
2244 } else if (LeafRec->getName() == "srcvalue") {
2245 // Place holder for SRCVALUE nodes. Nothing to do here.
2246 } else if (LeafRec->isSubClassOf("ValueType")) {
2247 // Make sure this is the specified value type.
2248 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2249 ")->getVT() == MVT::" + LeafRec->getName());
2250 } else if (LeafRec->isSubClassOf("CondCode")) {
2251 // Make sure this is the specified cond code.
2252 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2253 ")->get() == ISD::" + LeafRec->getName());
2257 assert(0 && "Unknown leaf type!");
2259 } else if (IntInit *II =
2260 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2261 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2262 unsigned CTmp = TmpNo++;
2263 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2264 RootName + utostr(OpNo) + ")->getSignExtended();");
2266 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2269 assert(0 && "Unknown leaf type!");
2274 // If there is a node predicate for this, emit the call.
2275 if (!N->getPredicateFn().empty())
2276 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2279 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2280 /// we actually have to build a DAG!
2281 std::pair<unsigned, unsigned>
2282 EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2283 bool isRoot = false) {
2284 // This is something selected from the pattern we matched.
2285 if (!N->getName().empty()) {
2286 std::string &Val = VariableMap[N->getName()];
2287 assert(!Val.empty() &&
2288 "Variable referenced but not defined and not caught earlier!");
2289 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2290 // Already selected this operand, just return the tmpval.
2291 return std::make_pair(1, atoi(Val.c_str()+3));
2294 const ComplexPattern *CP;
2295 unsigned ResNo = TmpNo++;
2296 unsigned NumRes = 1;
2297 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2298 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2299 std::string CastType;
2300 switch (N->getTypeNum(0)) {
2301 default: assert(0 && "Unknown type for constant node!");
2302 case MVT::i1: CastType = "bool"; break;
2303 case MVT::i8: CastType = "unsigned char"; break;
2304 case MVT::i16: CastType = "unsigned short"; break;
2305 case MVT::i32: CastType = "unsigned"; break;
2306 case MVT::i64: CastType = "uint64_t"; break;
2308 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
2309 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
2310 emitDecl("Tmp" + utostr(ResNo));
2311 emitCode("Tmp" + utostr(ResNo) +
2312 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
2313 "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2314 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2315 Record *Op = OperatorMap[N->getName()];
2316 // Transform ExternalSymbol to TargetExternalSymbol
2317 if (Op && Op->getName() == "externalsym") {
2318 emitDecl("Tmp" + utostr(ResNo));
2319 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2320 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2321 Val + ")->getSymbol(), MVT::" +
2322 getEnumName(N->getTypeNum(0)) + ");");
2324 emitDecl("Tmp" + utostr(ResNo));
2325 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2327 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2328 Record *Op = OperatorMap[N->getName()];
2329 // Transform GlobalAddress to TargetGlobalAddress
2330 if (Op && Op->getName() == "globaladdr") {
2331 emitDecl("Tmp" + utostr(ResNo));
2332 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2333 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2334 ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2337 emitDecl("Tmp" + utostr(ResNo));
2338 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2340 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2341 emitDecl("Tmp" + utostr(ResNo));
2342 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2343 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2344 emitDecl("Tmp" + utostr(ResNo));
2345 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2346 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2347 std::string Fn = CP->getSelectFunc();
2348 NumRes = CP->getNumOperands();
2349 for (unsigned i = 0; i < NumRes; ++i)
2350 emitDecl("Tmp" + utostr(i+ResNo));
2352 std::string Code = Fn + "(" + Val;
2353 for (unsigned i = 0; i < NumRes; i++)
2354 Code += ", Tmp" + utostr(i + ResNo);
2355 emitCheck(Code + ")");
2357 for (unsigned i = 0; i < NumRes; ++i)
2358 emitCode("Select(Tmp" + utostr(i+ResNo) + ", Tmp" +
2359 utostr(i+ResNo) + ");");
2361 TmpNo = ResNo + NumRes;
2363 emitDecl("Tmp" + utostr(ResNo));
2364 // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2365 // node even if it isn't one. Don't select it.
2367 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2369 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
2371 if (isRoot && N->isLeaf()) {
2372 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2373 emitCode("return;");
2376 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2377 // value if used multiple times by this pattern result.
2378 Val = "Tmp"+utostr(ResNo);
2379 return std::make_pair(NumRes, ResNo);
2382 // If this is an explicit register reference, handle it.
2383 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2384 unsigned ResNo = TmpNo++;
2385 if (DI->getDef()->isSubClassOf("Register")) {
2386 emitDecl("Tmp" + utostr(ResNo));
2387 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2388 ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2389 getEnumName(N->getTypeNum(0)) + ");");
2390 return std::make_pair(1, ResNo);
2392 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2393 unsigned ResNo = TmpNo++;
2394 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2395 emitDecl("Tmp" + utostr(ResNo));
2396 emitCode("Tmp" + utostr(ResNo) +
2397 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2398 ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2399 return std::make_pair(1, ResNo);
2403 assert(0 && "Unknown leaf type!");
2404 return std::make_pair(1, ~0U);
2407 Record *Op = N->getOperator();
2408 if (Op->isSubClassOf("Instruction")) {
2409 const CodeGenTarget &CGT = ISE.getTargetInfo();
2410 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2411 const DAGInstruction &Inst = ISE.getInstruction(Op);
2412 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2413 bool HasImpResults = Inst.getNumImpResults() > 0;
2414 bool HasOptInFlag = isRoot &&
2415 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2416 bool HasInFlag = isRoot &&
2417 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2418 bool NodeHasOutFlag = HasImpResults ||
2419 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2421 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2422 bool HasChain = II.hasCtrlDep ||
2423 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
2425 if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
2428 emitCode("bool HasOptInFlag = false;");
2430 // How many results is this pattern expected to produce?
2431 unsigned PatResults = 0;
2432 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2433 MVT::ValueType VT = Pattern->getTypeNum(i);
2434 if (VT != MVT::isVoid && VT != MVT::Flag)
2438 // Determine operand emission order. Complex pattern first.
2439 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2440 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2441 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2442 TreePatternNode *Child = N->getChild(i);
2444 EmitOrder.push_back(std::make_pair(i, Child));
2445 OI = EmitOrder.begin();
2446 } else if (NodeIsComplexPattern(Child)) {
2447 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2449 EmitOrder.push_back(std::make_pair(i, Child));
2453 // Emit all of the operands.
2454 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2455 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2456 unsigned OpOrder = EmitOrder[i].first;
2457 TreePatternNode *Child = EmitOrder[i].second;
2458 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2459 NumTemps[OpOrder] = NumTemp;
2462 // List all the operands in the right order.
2463 std::vector<unsigned> Ops;
2464 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2465 for (unsigned j = 0; j < NumTemps[i].first; j++)
2466 Ops.push_back(NumTemps[i].second + j);
2469 // Emit all the chain and CopyToReg stuff.
2470 bool ChainEmitted = HasChain;
2472 emitCode("Select(" + ChainName + ", " + ChainName + ");");
2473 if (HasInFlag || HasOptInFlag || HasImpInputs)
2474 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
2476 unsigned NumResults = Inst.getNumResults();
2477 unsigned ResNo = TmpNo++;
2479 emitDecl("Tmp" + utostr(ResNo));
2481 "Tmp" + utostr(ResNo) + " = SDOperand(CurDAG->getTargetNode(" +
2482 II.Namespace + "::" + II.TheDef->getName();
2483 if (N->getTypeNum(0) != MVT::isVoid)
2484 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2486 Code += ", MVT::Flag";
2488 unsigned LastOp = 0;
2489 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2491 Code += ", Tmp" + utostr(LastOp);
2493 emitCode(Code + "), 0);");
2495 // Must have at least one result
2496 emitCode(ChainName + " = Tmp" + utostr(LastOp) + ".getValue(" +
2497 utostr(NumResults) + ");");
2499 } else if (HasChain || NodeHasOutFlag) {
2501 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
2502 emitDecl("ResNode", true);
2503 emitCode("if (HasOptInFlag)");
2504 std::string Code = " ResNode = CurDAG->getTargetNode(" +
2505 II.Namespace + "::" + II.TheDef->getName();
2507 // Output order: results, chain, flags
2509 if (NumResults > 0) {
2510 if (N->getTypeNum(0) != MVT::isVoid)
2511 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2514 Code += ", MVT::Other";
2516 Code += ", MVT::Flag";
2519 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2520 Code += ", Tmp" + utostr(Ops[i]);
2521 if (HasChain) Code += ", " + ChainName;
2522 emitCode(Code + ", InFlag);");
2525 Code = " ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
2526 II.TheDef->getName();
2528 // Output order: results, chain, flags
2530 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2531 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2533 Code += ", MVT::Other";
2535 Code += ", MVT::Flag";
2538 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2539 Code += ", Tmp" + utostr(Ops[i]);
2540 if (HasChain) Code += ", " + ChainName + ");";
2543 emitDecl("ResNode", true);
2544 std::string Code = "ResNode = CurDAG->getTargetNode(" +
2545 II.Namespace + "::" + II.TheDef->getName();
2547 // Output order: results, chain, flags
2549 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2550 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2552 Code += ", MVT::Other";
2554 Code += ", MVT::Flag";
2557 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2558 Code += ", Tmp" + utostr(Ops[i]);
2559 if (HasChain) Code += ", " + ChainName;
2560 if (HasInFlag || HasImpInputs) Code += ", InFlag";
2561 emitCode(Code + ");");
2565 emitCode("if (OldTF) "
2566 "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2567 ChainName + ".Val, 0);");
2569 for (unsigned i = 0; i < NumResults; i++)
2570 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2571 utostr(i) + ", ResNode, " + utostr(i) + ");");
2574 emitCode("InFlag = SDOperand(ResNode, " +
2575 utostr(NumResults + (unsigned)HasChain) + ");");
2577 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2578 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2584 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2585 utostr(PatResults) + ", ResNode, " +
2586 utostr(NumResults) + ");");
2588 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2589 utostr(PatResults) + ", " + "ResNode, " +
2590 utostr(NumResults) + ");");
2593 if (FoldedChains.size() > 0) {
2595 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2596 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2597 FoldedChains[j].first + ".Val, " +
2598 utostr(FoldedChains[j].second) + ", ResNode, " +
2599 utostr(NumResults) + ");");
2601 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2603 FoldedChains[j].first + ".Val, " +
2604 utostr(FoldedChains[j].second) + ", ";
2605 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
2606 utostr(NumResults) + ");");
2611 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2612 utostr(PatResults + (unsigned)NodeHasChain) +
2613 ", InFlag.Val, InFlag.ResNo);");
2615 // User does not expect the instruction would produce a chain!
2616 bool AddedChain = HasChain && !NodeHasChain;
2617 if (AddedChain && NodeHasOutFlag) {
2618 if (PatResults == 0) {
2619 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
2621 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2622 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2624 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
2627 emitCode("Result = SDOperand(ResNode, N.ResNo);");
2630 // If this instruction is the root, and if there is only one use of it,
2631 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2632 emitCode("if (N.Val->hasOneUse()) {");
2633 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, " +
2634 II.Namespace + "::" + II.TheDef->getName();
2635 if (N->getTypeNum(0) != MVT::isVoid)
2636 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2638 Code += ", MVT::Flag";
2639 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2640 Code += ", Tmp" + utostr(Ops[i]);
2641 if (HasInFlag || HasImpInputs)
2643 emitCode(Code + ");");
2644 emitCode("} else {");
2645 emitDecl("ResNode", true);
2646 Code = " ResNode = CurDAG->getTargetNode(" +
2647 II.Namespace + "::" + II.TheDef->getName();
2648 if (N->getTypeNum(0) != MVT::isVoid)
2649 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2651 Code += ", MVT::Flag";
2652 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2653 Code += ", Tmp" + utostr(Ops[i]);
2654 if (HasInFlag || HasImpInputs)
2656 emitCode(Code + ");");
2657 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2659 emitCode(" Result = SDOperand(ResNode, 0);");
2664 emitCode("return;");
2665 return std::make_pair(1, ResNo);
2666 } else if (Op->isSubClassOf("SDNodeXForm")) {
2667 assert(N->getNumChildren() == 1 && "node xform should have one child!");
2668 // PatLeaf node - the operand may or may not be a leaf node. But it should
2670 unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
2671 unsigned ResNo = TmpNo++;
2672 emitDecl("Tmp" + utostr(ResNo));
2673 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2674 + "(Tmp" + utostr(OpVal) + ".Val);");
2676 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2677 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2678 utostr(ResNo) + ".ResNo);");
2679 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2680 emitCode("return;");
2682 return std::make_pair(1, ResNo);
2686 throw std::string("Unknown node in result pattern!");
2690 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2691 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2692 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2693 /// for, this returns true otherwise false if Pat has all types.
2694 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2695 const std::string &Prefix) {
2697 if (!Pat->hasTypeSet()) {
2698 // Move a type over from 'other' to 'pat'.
2699 Pat->setTypes(Other->getExtTypes());
2700 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
2701 getName(Pat->getTypeNum(0)));
2706 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2707 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2708 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2709 Prefix + utostr(OpNo)))
2715 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2717 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2718 bool &ChainEmitted, bool isRoot = false) {
2719 const CodeGenTarget &T = ISE.getTargetInfo();
2721 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2722 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2723 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
2724 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2725 TreePatternNode *Child = N->getChild(i);
2726 if (!Child->isLeaf()) {
2727 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
2729 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2730 if (!Child->getName().empty()) {
2731 std::string Name = RootName + utostr(OpNo);
2732 if (Duplicates.find(Name) != Duplicates.end())
2733 // A duplicate! Do not emit a copy for this node.
2737 Record *RR = DI->getDef();
2738 if (RR->isSubClassOf("Register")) {
2739 MVT::ValueType RVT = getRegisterValueType(RR, T);
2740 if (RVT == MVT::Flag) {
2741 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
2743 if (!ChainEmitted) {
2745 emitCode("Chain = CurDAG->getEntryNode();");
2746 ChainName = "Chain";
2747 ChainEmitted = true;
2749 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2750 RootName + utostr(OpNo) + ");");
2751 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
2752 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2753 ", MVT::" + getEnumName(RVT) + "), " +
2754 RootName + utostr(OpNo) + ", InFlag).Val;");
2755 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2756 emitCode("InFlag = SDOperand(ResNode, 1);");
2763 if (HasInFlag || HasOptInFlag) {
2766 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2770 emitCode(Code + "Select(InFlag, " + RootName +
2771 ".getOperand(" + utostr(OpNo) + "));");
2773 emitCode(" HasOptInFlag = true;");
2779 /// EmitCopyFromRegs - Emit code to copy result to physical registers
2780 /// as specified by the instruction. It returns true if any copy is
2782 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
2783 bool RetVal = false;
2784 Record *Op = N->getOperator();
2785 if (Op->isSubClassOf("Instruction")) {
2786 const DAGInstruction &Inst = ISE.getInstruction(Op);
2787 const CodeGenTarget &CGT = ISE.getTargetInfo();
2788 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2789 unsigned NumImpResults = Inst.getNumImpResults();
2790 for (unsigned i = 0; i < NumImpResults; i++) {
2791 Record *RR = Inst.getImpResult(i);
2792 if (RR->isSubClassOf("Register")) {
2793 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2794 if (RVT != MVT::Flag) {
2795 if (!ChainEmitted) {
2797 emitCode("Chain = CurDAG->getEntryNode();");
2798 ChainEmitted = true;
2799 ChainName = "Chain";
2801 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
2802 ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
2804 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2805 emitCode("InFlag = SDOperand(ResNode, 2);");
2815 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2816 /// stream to match the pattern, and generate the code for the match if it
2817 /// succeeds. Returns true if the pattern is not guaranteed to match.
2818 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2819 std::vector<std::pair<bool, std::string> > &GeneratedCode,
2820 std::set<std::pair<bool, std::string> > &GeneratedDecl,
2822 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2823 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2824 GeneratedCode, GeneratedDecl, DoReplace);
2826 // Emit the matcher, capturing named arguments in VariableMap.
2827 bool FoundChain = false;
2828 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
2830 // TP - Get *SOME* tree pattern, we don't care which.
2831 TreePattern &TP = *PatternFragments.begin()->second;
2833 // At this point, we know that we structurally match the pattern, but the
2834 // types of the nodes may not match. Figure out the fewest number of type
2835 // comparisons we need to emit. For example, if there is only one integer
2836 // type supported by a target, there should be no type comparisons at all for
2837 // integer patterns!
2839 // To figure out the fewest number of type checks needed, clone the pattern,
2840 // remove the types, then perform type inference on the pattern as a whole.
2841 // If there are unresolved types, emit an explicit check for those types,
2842 // apply the type to the tree, then rerun type inference. Iterate until all
2843 // types are resolved.
2845 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2846 RemoveAllTypes(Pat);
2849 // Resolve/propagate as many types as possible.
2851 bool MadeChange = true;
2853 MadeChange = Pat->ApplyTypeConstraints(TP,
2854 true/*Ignore reg constraints*/);
2856 assert(0 && "Error: could not find consistent types for something we"
2857 " already decided was ok!");
2861 // Insert a check for an unresolved type and add it to the tree. If we find
2862 // an unresolved type to add a check for, this returns true and we iterate,
2863 // otherwise we are done.
2864 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2866 Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
2870 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
2871 /// a line causes any of them to be empty, remove them and return true when
2873 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
2874 std::vector<std::pair<bool, std::string> > > >
2876 bool ErasedPatterns = false;
2877 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2878 Patterns[i].second.pop_back();
2879 if (Patterns[i].second.empty()) {
2880 Patterns.erase(Patterns.begin()+i);
2882 ErasedPatterns = true;
2885 return ErasedPatterns;
2888 /// EmitPatterns - Emit code for at least one pattern, but try to group common
2889 /// code together between the patterns.
2890 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
2891 std::vector<std::pair<bool, std::string> > > >
2892 &Patterns, unsigned Indent,
2894 typedef std::pair<bool, std::string> CodeLine;
2895 typedef std::vector<CodeLine> CodeList;
2896 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2898 if (Patterns.empty()) return;
2900 // Figure out how many patterns share the next code line. Explicitly copy
2901 // FirstCodeLine so that we don't invalidate a reference when changing
2903 const CodeLine FirstCodeLine = Patterns.back().second.back();
2904 unsigned LastMatch = Patterns.size()-1;
2905 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2908 // If not all patterns share this line, split the list into two pieces. The
2909 // first chunk will use this line, the second chunk won't.
2910 if (LastMatch != 0) {
2911 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2912 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2914 // FIXME: Emit braces?
2915 if (Shared.size() == 1) {
2916 PatternToMatch &Pattern = *Shared.back().first;
2917 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2918 Pattern.getSrcPattern()->print(OS);
2919 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2920 Pattern.getDstPattern()->print(OS);
2922 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2923 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
2924 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
2926 if (!FirstCodeLine.first) {
2927 OS << std::string(Indent, ' ') << "{\n";
2930 EmitPatterns(Shared, Indent, OS);
2931 if (!FirstCodeLine.first) {
2933 OS << std::string(Indent, ' ') << "}\n";
2936 if (Other.size() == 1) {
2937 PatternToMatch &Pattern = *Other.back().first;
2938 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2939 Pattern.getSrcPattern()->print(OS);
2940 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2941 Pattern.getDstPattern()->print(OS);
2943 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2944 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
2945 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
2947 EmitPatterns(Other, Indent, OS);
2951 // Remove this code from all of the patterns that share it.
2952 bool ErasedPatterns = EraseCodeLine(Patterns);
2954 bool isPredicate = FirstCodeLine.first;
2956 // Otherwise, every pattern in the list has this line. Emit it.
2959 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
2961 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
2963 // If the next code line is another predicate, and if all of the pattern
2964 // in this group share the same next line, emit it inline now. Do this
2965 // until we run out of common predicates.
2966 while (!ErasedPatterns && Patterns.back().second.back().first) {
2967 // Check that all of fhe patterns in Patterns end with the same predicate.
2968 bool AllEndWithSamePredicate = true;
2969 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2970 if (Patterns[i].second.back() != Patterns.back().second.back()) {
2971 AllEndWithSamePredicate = false;
2974 // If all of the predicates aren't the same, we can't share them.
2975 if (!AllEndWithSamePredicate) break;
2977 // Otherwise we can. Emit it shared now.
2978 OS << " &&\n" << std::string(Indent+4, ' ')
2979 << Patterns.back().second.back().second;
2980 ErasedPatterns = EraseCodeLine(Patterns);
2987 EmitPatterns(Patterns, Indent, OS);
2990 OS << std::string(Indent-2, ' ') << "}\n";
2996 /// CompareByRecordName - An ordering predicate that implements less-than by
2997 /// comparing the names records.
2998 struct CompareByRecordName {
2999 bool operator()(const Record *LHS, const Record *RHS) const {
3000 // Sort by name first.
3001 if (LHS->getName() < RHS->getName()) return true;
3002 // If both names are equal, sort by pointer.
3003 return LHS->getName() == RHS->getName() && LHS < RHS;
3008 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
3009 std::string InstNS = Target.inst_begin()->second.Namespace;
3010 if (!InstNS.empty()) InstNS += "::";
3012 // Group the patterns by their top-level opcodes.
3013 std::map<Record*, std::vector<PatternToMatch*>,
3014 CompareByRecordName> PatternsByOpcode;
3015 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3016 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3017 if (!Node->isLeaf()) {
3018 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3020 const ComplexPattern *CP;
3022 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3023 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3024 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3025 std::vector<Record*> OpNodes = CP->getRootNodes();
3026 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3027 PatternsByOpcode[OpNodes[j]]
3028 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
3031 std::cerr << "Unrecognized opcode '";
3033 std::cerr << "' on tree pattern '";
3035 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3036 std::cerr << "'!\n";
3042 // Emit one Select_* method for each top-level opcode. We do this instead of
3043 // emitting one giant switch statement to support compilers where this will
3044 // result in the recursive functions taking less stack space.
3045 for (std::map<Record*, std::vector<PatternToMatch*>,
3046 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3047 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3048 const std::string &OpName = PBOI->first->getName();
3049 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
3051 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3053 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3054 OpcodeInfo.getNumResults() > 0);
3057 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
3058 << " && N.getValue(0).hasOneUse()) {\n"
3059 << " SDOperand Dummy = "
3060 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
3061 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3062 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3063 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3064 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3065 << " Result = Dummy;\n"
3070 std::vector<PatternToMatch*> &Patterns = PBOI->second;
3071 assert(!Patterns.empty() && "No patterns but map has entry?");
3073 // We want to emit all of the matching code now. However, we want to emit
3074 // the matches in order of minimal cost. Sort the patterns so the least
3075 // cost one is at the start.
3076 std::stable_sort(Patterns.begin(), Patterns.end(),
3077 PatternSortingPredicate(*this));
3079 typedef std::vector<std::pair<bool, std::string> > CodeList;
3080 typedef std::set<std::string> DeclSet;
3082 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3083 std::set<std::pair<bool, std::string> > GeneratedDecl;
3084 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3085 CodeList GeneratedCode;
3086 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3088 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3091 // Scan the code to see if all of the patterns are reachable and if it is
3092 // possible that the last one might not match.
3093 bool mightNotMatch = true;
3094 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3095 CodeList &GeneratedCode = CodeForPatterns[i].second;
3096 mightNotMatch = false;
3098 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3099 if (GeneratedCode[j].first) { // predicate.
3100 mightNotMatch = true;
3105 // If this pattern definitely matches, and if it isn't the last one, the
3106 // patterns after it CANNOT ever match. Error out.
3107 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3108 std::cerr << "Pattern '";
3109 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3110 std::cerr << "' is impossible to select!\n";
3115 // Print all declarations.
3116 for (std::set<std::pair<bool, std::string> >::iterator
3117 I = GeneratedDecl.begin(), E = GeneratedDecl.end(); I != E; ++I)
3119 OS << " SDNode *" << I->second << ";\n";
3121 OS << " SDOperand " << I->second << "(0, 0);\n";
3123 // Loop through and reverse all of the CodeList vectors, as we will be
3124 // accessing them from their logical front, but accessing the end of a
3125 // vector is more efficient.
3126 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3127 CodeList &GeneratedCode = CodeForPatterns[i].second;
3128 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3131 // Next, reverse the list of patterns itself for the same reason.
3132 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3134 // Emit all of the patterns now, grouped together to share code.
3135 EmitPatterns(CodeForPatterns, 2, OS);
3137 // If the last pattern has predicates (which could fail) emit code to catch
3138 // the case where nothing handles a pattern.
3139 if (mightNotMatch) {
3140 OS << " std::cerr << \"Cannot yet select: \";\n";
3141 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3142 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3143 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3144 OS << " N.Val->dump(CurDAG);\n";
3146 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3147 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3148 << " std::cerr << \"intrinsic %\"<< "
3149 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3151 OS << " std::cerr << '\\n';\n"
3157 // Emit boilerplate.
3158 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
3159 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3160 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
3161 << " // Select the flag operand.\n"
3162 << " if (Ops.back().getValueType() == MVT::Flag)\n"
3163 << " Select(Ops.back(), Ops.back());\n"
3164 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3165 << " std::vector<MVT::ValueType> VTs;\n"
3166 << " VTs.push_back(MVT::Other);\n"
3167 << " VTs.push_back(MVT::Flag);\n"
3168 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
3169 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3170 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
3171 << " Result = New.getValue(N.ResNo);\n"
3175 OS << "// The main instruction selector code.\n"
3176 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
3177 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3178 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3179 << "INSTRUCTION_LIST_END)) {\n"
3181 << " return; // Already selected.\n"
3183 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
3184 << " if (CGMI != CodeGenMap.end()) {\n"
3185 << " Result = CGMI->second;\n"
3188 << " switch (N.getOpcode()) {\n"
3189 << " default: break;\n"
3190 << " case ISD::EntryToken: // These leaves remain the same.\n"
3191 << " case ISD::BasicBlock:\n"
3192 << " case ISD::Register:\n"
3193 << " case ISD::HANDLENODE:\n"
3194 << " case ISD::TargetConstant:\n"
3195 << " case ISD::TargetConstantPool:\n"
3196 << " case ISD::TargetFrameIndex:\n"
3197 << " case ISD::TargetGlobalAddress: {\n"
3201 << " case ISD::AssertSext:\n"
3202 << " case ISD::AssertZext: {\n"
3203 << " SDOperand Tmp0;\n"
3204 << " Select(Tmp0, N.getOperand(0));\n"
3205 << " if (!N.Val->hasOneUse())\n"
3206 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3207 << "Tmp0.Val, Tmp0.ResNo);\n"
3208 << " Result = Tmp0;\n"
3211 << " case ISD::TokenFactor:\n"
3212 << " if (N.getNumOperands() == 2) {\n"
3213 << " SDOperand Op0, Op1;\n"
3214 << " Select(Op0, N.getOperand(0));\n"
3215 << " Select(Op1, N.getOperand(1));\n"
3217 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
3218 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3219 << "Result.Val, Result.ResNo);\n"
3221 << " std::vector<SDOperand> Ops;\n"
3222 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3223 << " SDOperand Val;\n"
3224 << " Select(Val, N.getOperand(i));\n"
3225 << " Ops.push_back(Val);\n"
3228 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3229 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3230 << "Result.Val, Result.ResNo);\n"
3233 << " case ISD::CopyFromReg: {\n"
3234 << " SDOperand Chain;\n"
3235 << " Select(Chain, N.getOperand(0));\n"
3236 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3237 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
3238 << " if (N.Val->getNumValues() == 2) {\n"
3239 << " if (Chain == N.getOperand(0)) {\n"
3240 << " Result = N; // No change\n"
3243 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
3244 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3246 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3248 << " Result = New.getValue(N.ResNo);\n"
3251 << " SDOperand Flag;\n"
3252 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
3253 << " if (Chain == N.getOperand(0) &&\n"
3254 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3255 << " Result = N; // No change\n"
3258 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
3259 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3261 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3263 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3265 << " Result = New.getValue(N.ResNo);\n"
3269 << " case ISD::CopyToReg: {\n"
3270 << " SDOperand Chain;\n"
3271 << " Select(Chain, N.getOperand(0));\n"
3272 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3273 << " SDOperand Val;\n"
3274 << " Select(Val, N.getOperand(2));\n"
3276 << " if (N.Val->getNumValues() == 1) {\n"
3277 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
3278 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
3279 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3280 << "Result.Val, 0);\n"
3282 << " SDOperand Flag(0, 0);\n"
3283 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
3284 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
3285 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
3286 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
3287 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3288 << "Result.Val, 0);\n"
3289 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3290 << "Result.Val, 1);\n"
3291 << " Result = Result.getValue(N.ResNo);\n"
3295 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
3298 // Loop over all of the case statements, emiting a call to each method we
3300 for (std::map<Record*, std::vector<PatternToMatch*>,
3301 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3302 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3303 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3304 OS << " case " << OpcodeInfo.getEnumName() << ": "
3305 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
3306 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
3309 OS << " } // end of big switch.\n\n"
3310 << " std::cerr << \"Cannot yet select: \";\n"
3311 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3312 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3313 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
3314 << " N.Val->dump(CurDAG);\n"
3316 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3317 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3318 << " std::cerr << \"intrinsic %\"<< "
3319 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3321 << " std::cerr << '\\n';\n"
3326 void DAGISelEmitter::run(std::ostream &OS) {
3327 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3330 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3331 << "// *** instruction selector class. These functions are really "
3334 OS << "// Instance var to keep track of multiply used nodes that have \n"
3335 << "// already been selected.\n"
3336 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
3338 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
3339 << "// and their place handle nodes.\n";
3340 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3341 OS << "// Instance var to keep track of mapping of place handle nodes\n"
3342 << "// and their replacement nodes.\n";
3343 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3346 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3347 << "std::set<SDNode *> &Visited) {\n";
3348 OS << " if (found || !Visited.insert(Use).second) return;\n";
3349 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3350 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3351 OS << " if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3352 OS << " if (N != Def) {\n";
3353 OS << " findNonImmUse(N, Def, found, Visited);\n";
3354 OS << " } else {\n";
3355 OS << " found = true;\n";
3363 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3364 OS << " std::set<SDNode *> Visited;\n";
3365 OS << " bool found = false;\n";
3366 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3367 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3368 OS << " if (N != Def) {\n";
3369 OS << " findNonImmUse(N, Def, found, Visited);\n";
3370 OS << " if (found) break;\n";
3373 OS << " return found;\n";
3377 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
3378 << "// handle node in ReplaceMap.\n";
3379 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3380 << "unsigned RNum) {\n";
3381 OS << " SDOperand N(H, HNum);\n";
3382 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3383 OS << " if (HMI != HandleMap.end()) {\n";
3384 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
3385 OS << " HandleMap.erase(N);\n";
3390 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3391 OS << "// handles.Some handles do not yet have replacements because the\n";
3392 OS << "// nodes they replacements have only dead readers.\n";
3393 OS << "void SelectDanglingHandles() {\n";
3394 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3395 << "HandleMap.begin(),\n"
3396 << " E = HandleMap.end(); I != E; ++I) {\n";
3397 OS << " SDOperand N = I->first;\n";
3398 OS << " SDOperand R;\n";
3399 OS << " Select(R, N.getValue(0));\n";
3400 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
3404 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
3405 OS << "// specific nodes.\n";
3406 OS << "void ReplaceHandles() {\n";
3407 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3408 << "ReplaceMap.begin(),\n"
3409 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3410 OS << " SDOperand From = I->first;\n";
3411 OS << " SDOperand To = I->second;\n";
3412 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3413 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3414 OS << " SDNode *Use = *UI;\n";
3415 OS << " std::vector<SDOperand> Ops;\n";
3416 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3417 OS << " SDOperand O = Use->getOperand(i);\n";
3418 OS << " if (O.Val == From.Val)\n";
3419 OS << " Ops.push_back(To);\n";
3421 OS << " Ops.push_back(O);\n";
3423 OS << " SDOperand U = SDOperand(Use, 0);\n";
3424 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3430 OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3431 OS << "// if the folding were to happen. This is called when, for example,\n";
3432 OS << "// a load is folded into a store. If the store's chain is the load,\n";
3433 OS << "// then the resulting node's input chain would be the load's input\n";
3434 OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3435 OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3436 OS << "// with the other operands along with the input chain of the load.\n";
3437 OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3438 << "SDNode *Chain, SDNode* &OldTF) {\n";
3439 OS << " OldTF = NULL;\n";
3440 OS << " if (N == Chain) {\n";
3441 OS << " return N->getOperand(0);\n";
3442 OS << " } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3443 OS << " N->isOperand(Chain)) {\n";
3444 OS << " SDOperand Ch = SDOperand(Chain, 0);\n";
3445 OS << " std::map<SDOperand, SDOperand>::iterator CGMI = "
3446 << "CodeGenMap.find(Ch);\n";
3447 OS << " if (CGMI != CodeGenMap.end())\n";
3448 OS << " return SDOperand(0, 0);\n";
3449 OS << " OldTF = Chain;\n";
3450 OS << " std::vector<SDOperand> Ops;\n";
3451 OS << " for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3452 OS << " SDOperand Op = Chain->getOperand(i);\n";
3453 OS << " if (Op.Val == N)\n";
3454 OS << " Ops.push_back(N->getOperand(0));\n";
3456 OS << " Ops.push_back(Op);\n";
3458 OS << " return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3460 OS << " return SDOperand(0, 0);\n";
3464 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3465 OS << "SDOperand SelectRoot(SDOperand N) {\n";
3466 OS << " SDOperand ResNode;\n";
3467 OS << " Select(ResNode, N);\n";
3468 OS << " SelectDanglingHandles();\n";
3469 OS << " ReplaceHandles();\n";
3470 OS << " ReplaceMap.clear();\n";
3471 OS << " return ResNode;\n";
3474 Intrinsics = LoadIntrinsics(Records);
3476 ParseNodeTransforms(OS);
3477 ParseComplexPatterns();
3478 ParsePatternFragments(OS);
3479 ParseInstructions();
3482 // Generate variants. For example, commutative patterns can match
3483 // multiple ways. Add them to PatternsToMatch as well.
3487 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3488 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3489 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3490 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
3494 // At this point, we have full information about the 'Patterns' we need to
3495 // parse, both implicitly from instructions as well as from explicit pattern
3496 // definitions. Emit the resultant instruction selector.
3497 EmitInstructionSelector(OS);
3499 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3500 E = PatternFragments.end(); I != E; ++I)
3502 PatternFragments.clear();
3504 Instructions.clear();