1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenDAGPatterns.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/Streams.h"
24 //===----------------------------------------------------------------------===//
25 // Helpers for working with extended types.
27 /// FilterVTs - Filter a list of VT's according to a predicate.
30 static std::vector<MVT::ValueType>
31 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
32 std::vector<MVT::ValueType> Result;
33 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
35 Result.push_back(InVTs[i]);
40 static std::vector<unsigned char>
41 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42 std::vector<unsigned char> Result;
43 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
44 if (Filter((MVT::ValueType)InVTs[i]))
45 Result.push_back(InVTs[i]);
49 static std::vector<unsigned char>
50 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
51 std::vector<unsigned char> Result;
52 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53 Result.push_back(InVTs[i]);
57 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
58 const std::vector<unsigned char> &RHS) {
59 if (LHS.size() > RHS.size()) return false;
60 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
61 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
66 /// isExtIntegerVT - Return true if the specified extended value type vector
67 /// contains isInt or an integer value type.
70 bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
71 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
72 return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty());
75 /// isExtFloatingPointVT - Return true if the specified extended value type
76 /// vector contains isFP or a FP value type.
77 bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
78 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
79 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
81 } // end namespace MVT.
82 } // end namespace llvm.
84 //===----------------------------------------------------------------------===//
85 // SDTypeConstraint implementation
88 SDTypeConstraint::SDTypeConstraint(Record *R) {
89 OperandNo = R->getValueAsInt("OperandNum");
91 if (R->isSubClassOf("SDTCisVT")) {
92 ConstraintType = SDTCisVT;
93 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
94 } else if (R->isSubClassOf("SDTCisPtrTy")) {
95 ConstraintType = SDTCisPtrTy;
96 } else if (R->isSubClassOf("SDTCisInt")) {
97 ConstraintType = SDTCisInt;
98 } else if (R->isSubClassOf("SDTCisFP")) {
99 ConstraintType = SDTCisFP;
100 } else if (R->isSubClassOf("SDTCisSameAs")) {
101 ConstraintType = SDTCisSameAs;
102 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
103 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
104 ConstraintType = SDTCisVTSmallerThanOp;
105 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
106 R->getValueAsInt("OtherOperandNum");
107 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
108 ConstraintType = SDTCisOpSmallerThanOp;
109 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
110 R->getValueAsInt("BigOperandNum");
111 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
112 ConstraintType = SDTCisIntVectorOfSameSize;
113 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
114 R->getValueAsInt("OtherOpNum");
115 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
116 ConstraintType = SDTCisEltOfVec;
117 x.SDTCisEltOfVec_Info.OtherOperandNum =
118 R->getValueAsInt("OtherOpNum");
120 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
125 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
126 /// N, which has NumResults results.
127 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
129 unsigned NumResults) const {
130 assert(NumResults <= 1 &&
131 "We only work with nodes with zero or one result so far!");
133 if (OpNo >= (NumResults + N->getNumChildren())) {
134 cerr << "Invalid operand number " << OpNo << " ";
140 if (OpNo < NumResults)
141 return N; // FIXME: need value #
143 return N->getChild(OpNo-NumResults);
146 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
147 /// constraint to the nodes operands. This returns true if it makes a
148 /// change, false otherwise. If a type contradiction is found, throw an
150 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
151 const SDNodeInfo &NodeInfo,
152 TreePattern &TP) const {
153 unsigned NumResults = NodeInfo.getNumResults();
154 assert(NumResults <= 1 &&
155 "We only work with nodes with zero or one result so far!");
157 // Check that the number of operands is sane. Negative operands -> varargs.
158 if (NodeInfo.getNumOperands() >= 0) {
159 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
160 TP.error(N->getOperator()->getName() + " node requires exactly " +
161 itostr(NodeInfo.getNumOperands()) + " operands!");
164 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
166 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
168 switch (ConstraintType) {
169 default: assert(0 && "Unknown constraint type!");
171 // Operand must be a particular type.
172 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
174 // Operand must be same as target pointer type.
175 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
178 // If there is only one integer type supported, this must be it.
179 std::vector<MVT::ValueType> IntVTs =
180 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
182 // If we found exactly one supported integer type, apply it.
183 if (IntVTs.size() == 1)
184 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
185 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
188 // If there is only one FP type supported, this must be it.
189 std::vector<MVT::ValueType> FPVTs =
190 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
192 // If we found exactly one supported FP type, apply it.
193 if (FPVTs.size() == 1)
194 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
195 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
198 TreePatternNode *OtherNode =
199 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
200 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
201 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
203 case SDTCisVTSmallerThanOp: {
204 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
205 // have an integer type that is smaller than the VT.
206 if (!NodeToApply->isLeaf() ||
207 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
208 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
209 ->isSubClassOf("ValueType"))
210 TP.error(N->getOperator()->getName() + " expects a VT operand!");
212 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
213 if (!MVT::isInteger(VT))
214 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
216 TreePatternNode *OtherNode =
217 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
219 // It must be integer.
220 bool MadeChange = false;
221 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
223 // This code only handles nodes that have one type set. Assert here so
224 // that we can change this if we ever need to deal with multiple value
225 // types at this point.
226 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
227 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
228 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
231 case SDTCisOpSmallerThanOp: {
232 TreePatternNode *BigOperand =
233 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
235 // Both operands must be integer or FP, but we don't care which.
236 bool MadeChange = false;
238 // This code does not currently handle nodes which have multiple types,
239 // where some types are integer, and some are fp. Assert that this is not
241 assert(!(MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
242 MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
243 !(MVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
244 MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
245 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
246 if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
247 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
248 else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
249 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
250 if (MVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
251 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
252 else if (MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
253 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
255 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
257 if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
258 VTs = FilterVTs(VTs, MVT::isInteger);
259 } else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
260 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
265 switch (VTs.size()) {
266 default: // Too many VT's to pick from.
267 case 0: break; // No info yet.
269 // Only one VT of this flavor. Cannot ever satisify the constraints.
270 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
272 // If we have exactly two possible types, the little operand must be the
273 // small one, the big operand should be the big one. Common with
274 // float/double for example.
275 assert(VTs[0] < VTs[1] && "Should be sorted!");
276 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
277 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
282 case SDTCisIntVectorOfSameSize: {
283 TreePatternNode *OtherOperand =
284 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
286 if (OtherOperand->hasTypeSet()) {
287 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
288 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
289 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
290 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
291 return NodeToApply->UpdateNodeType(IVT, TP);
295 case SDTCisEltOfVec: {
296 TreePatternNode *OtherOperand =
297 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
299 if (OtherOperand->hasTypeSet()) {
300 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
301 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
302 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
303 IVT = MVT::getVectorElementType(IVT);
304 return NodeToApply->UpdateNodeType(IVT, TP);
312 //===----------------------------------------------------------------------===//
313 // SDNodeInfo implementation
315 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
316 EnumName = R->getValueAsString("Opcode");
317 SDClassName = R->getValueAsString("SDClass");
318 Record *TypeProfile = R->getValueAsDef("TypeProfile");
319 NumResults = TypeProfile->getValueAsInt("NumResults");
320 NumOperands = TypeProfile->getValueAsInt("NumOperands");
322 // Parse the properties.
324 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
325 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
326 if (PropList[i]->getName() == "SDNPCommutative") {
327 Properties |= 1 << SDNPCommutative;
328 } else if (PropList[i]->getName() == "SDNPAssociative") {
329 Properties |= 1 << SDNPAssociative;
330 } else if (PropList[i]->getName() == "SDNPHasChain") {
331 Properties |= 1 << SDNPHasChain;
332 } else if (PropList[i]->getName() == "SDNPOutFlag") {
333 Properties |= 1 << SDNPOutFlag;
334 } else if (PropList[i]->getName() == "SDNPInFlag") {
335 Properties |= 1 << SDNPInFlag;
336 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
337 Properties |= 1 << SDNPOptInFlag;
338 } else if (PropList[i]->getName() == "SDNPMayStore") {
339 Properties |= 1 << SDNPMayStore;
340 } else if (PropList[i]->getName() == "SDNPMayLoad") {
341 Properties |= 1 << SDNPMayLoad;
342 } else if (PropList[i]->getName() == "SDNPSideEffect") {
343 Properties |= 1 << SDNPSideEffect;
345 cerr << "Unknown SD Node property '" << PropList[i]->getName()
346 << "' on node '" << R->getName() << "'!\n";
352 // Parse the type constraints.
353 std::vector<Record*> ConstraintList =
354 TypeProfile->getValueAsListOfDefs("Constraints");
355 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
358 //===----------------------------------------------------------------------===//
359 // TreePatternNode implementation
362 TreePatternNode::~TreePatternNode() {
363 #if 0 // FIXME: implement refcounted tree nodes!
364 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
369 /// UpdateNodeType - Set the node type of N to VT if VT contains
370 /// information. If N already contains a conflicting type, then throw an
371 /// exception. This returns true if any information was updated.
373 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
375 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
377 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
379 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
384 if (getExtTypeNum(0) == MVT::iPTR) {
385 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
387 if (MVT::isExtIntegerInVTs(ExtVTs)) {
388 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
396 if (ExtVTs[0] == MVT::isInt && MVT::isExtIntegerInVTs(getExtTypes())) {
397 assert(hasTypeSet() && "should be handled above!");
398 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
399 if (getExtTypes() == FVTs)
404 if (ExtVTs[0] == MVT::iPTR && MVT::isExtIntegerInVTs(getExtTypes())) {
405 //assert(hasTypeSet() && "should be handled above!");
406 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
407 if (getExtTypes() == FVTs)
414 if (ExtVTs[0] == MVT::isFP && MVT::isExtFloatingPointInVTs(getExtTypes())) {
415 assert(hasTypeSet() && "should be handled above!");
416 std::vector<unsigned char> FVTs =
417 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
418 if (getExtTypes() == FVTs)
424 // If we know this is an int or fp type, and we are told it is a specific one,
427 // Similarly, we should probably set the type here to the intersection of
428 // {isInt|isFP} and ExtVTs
429 if ((getExtTypeNum(0) == MVT::isInt && MVT::isExtIntegerInVTs(ExtVTs)) ||
430 (getExtTypeNum(0) == MVT::isFP && MVT::isExtFloatingPointInVTs(ExtVTs))){
434 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
442 TP.error("Type inference contradiction found in node!");
444 TP.error("Type inference contradiction found in node " +
445 getOperator()->getName() + "!");
447 return true; // unreachable
451 void TreePatternNode::print(std::ostream &OS) const {
453 OS << *getLeafValue();
455 OS << "(" << getOperator()->getName();
458 // FIXME: At some point we should handle printing all the value types for
459 // nodes that are multiply typed.
460 switch (getExtTypeNum(0)) {
461 case MVT::Other: OS << ":Other"; break;
462 case MVT::isInt: OS << ":isInt"; break;
463 case MVT::isFP : OS << ":isFP"; break;
464 case MVT::isUnknown: ; /*OS << ":?";*/ break;
465 case MVT::iPTR: OS << ":iPTR"; break;
467 std::string VTName = llvm::getName(getTypeNum(0));
468 // Strip off MVT:: prefix if present.
469 if (VTName.substr(0,5) == "MVT::")
470 VTName = VTName.substr(5);
477 if (getNumChildren() != 0) {
479 getChild(0)->print(OS);
480 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
482 getChild(i)->print(OS);
488 if (!PredicateFn.empty())
489 OS << "<<P:" << PredicateFn << ">>";
491 OS << "<<X:" << TransformFn->getName() << ">>";
492 if (!getName().empty())
493 OS << ":$" << getName();
496 void TreePatternNode::dump() const {
497 print(*cerr.stream());
500 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
501 /// the specified node. For this comparison, all of the state of the node
502 /// is considered, except for the assigned name. Nodes with differing names
503 /// that are otherwise identical are considered isomorphic.
504 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
505 if (N == this) return true;
506 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
507 getPredicateFn() != N->getPredicateFn() ||
508 getTransformFn() != N->getTransformFn())
512 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
513 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
514 return DI->getDef() == NDI->getDef();
515 return getLeafValue() == N->getLeafValue();
518 if (N->getOperator() != getOperator() ||
519 N->getNumChildren() != getNumChildren()) return false;
520 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
521 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
526 /// clone - Make a copy of this tree and all of its children.
528 TreePatternNode *TreePatternNode::clone() const {
529 TreePatternNode *New;
531 New = new TreePatternNode(getLeafValue());
533 std::vector<TreePatternNode*> CChildren;
534 CChildren.reserve(Children.size());
535 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
536 CChildren.push_back(getChild(i)->clone());
537 New = new TreePatternNode(getOperator(), CChildren);
539 New->setName(getName());
540 New->setTypes(getExtTypes());
541 New->setPredicateFn(getPredicateFn());
542 New->setTransformFn(getTransformFn());
546 /// SubstituteFormalArguments - Replace the formal arguments in this tree
547 /// with actual values specified by ArgMap.
548 void TreePatternNode::
549 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
550 if (isLeaf()) return;
552 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
553 TreePatternNode *Child = getChild(i);
554 if (Child->isLeaf()) {
555 Init *Val = Child->getLeafValue();
556 if (dynamic_cast<DefInit*>(Val) &&
557 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
558 // We found a use of a formal argument, replace it with its value.
559 Child = ArgMap[Child->getName()];
560 assert(Child && "Couldn't find formal argument!");
564 getChild(i)->SubstituteFormalArguments(ArgMap);
570 /// InlinePatternFragments - If this pattern refers to any pattern
571 /// fragments, inline them into place, giving us a pattern without any
572 /// PatFrag references.
573 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
574 if (isLeaf()) return this; // nothing to do.
575 Record *Op = getOperator();
577 if (!Op->isSubClassOf("PatFrag")) {
578 // Just recursively inline children nodes.
579 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
580 setChild(i, getChild(i)->InlinePatternFragments(TP));
584 // Otherwise, we found a reference to a fragment. First, look up its
585 // TreePattern record.
586 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
588 // Verify that we are passing the right number of operands.
589 if (Frag->getNumArgs() != Children.size())
590 TP.error("'" + Op->getName() + "' fragment requires " +
591 utostr(Frag->getNumArgs()) + " operands!");
593 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
595 // Resolve formal arguments to their actual value.
596 if (Frag->getNumArgs()) {
597 // Compute the map of formal to actual arguments.
598 std::map<std::string, TreePatternNode*> ArgMap;
599 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
600 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
602 FragTree->SubstituteFormalArguments(ArgMap);
605 FragTree->setName(getName());
606 FragTree->UpdateNodeType(getExtTypes(), TP);
608 // Get a new copy of this fragment to stitch into here.
609 //delete this; // FIXME: implement refcounting!
613 /// getImplicitType - Check to see if the specified record has an implicit
614 /// type which should be applied to it. This infer the type of register
615 /// references from the register file information, for example.
617 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
619 // Some common return values
620 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
621 std::vector<unsigned char> Other(1, MVT::Other);
623 // Check to see if this is a register or a register class...
624 if (R->isSubClassOf("RegisterClass")) {
627 const CodeGenRegisterClass &RC =
628 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
629 return ConvertVTs(RC.getValueTypes());
630 } else if (R->isSubClassOf("PatFrag")) {
631 // Pattern fragment types will be resolved when they are inlined.
633 } else if (R->isSubClassOf("Register")) {
636 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
637 return T.getRegisterVTs(R);
638 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
639 // Using a VTSDNode or CondCodeSDNode.
641 } else if (R->isSubClassOf("ComplexPattern")) {
644 std::vector<unsigned char>
645 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
647 } else if (R->getName() == "ptr_rc") {
648 Other[0] = MVT::iPTR;
650 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
651 R->getName() == "zero_reg") {
656 TP.error("Unknown node flavor used in pattern: " + R->getName());
661 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
662 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
663 const CodeGenIntrinsic *TreePatternNode::
664 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
665 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
666 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
667 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
671 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
672 return &CDP.getIntrinsicInfo(IID);
676 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
677 /// this node and its children in the tree. This returns true if it makes a
678 /// change, false otherwise. If a type contradiction is found, throw an
680 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
681 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
683 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
684 // If it's a regclass or something else known, include the type.
685 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
686 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
687 // Int inits are always integers. :)
688 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
691 // At some point, it may make sense for this tree pattern to have
692 // multiple types. Assert here that it does not, so we revisit this
693 // code when appropriate.
694 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
695 MVT::ValueType VT = getTypeNum(0);
696 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
697 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
700 if (VT != MVT::iPTR) {
701 unsigned Size = MVT::getSizeInBits(VT);
702 // Make sure that the value is representable for this type.
704 int Val = (II->getValue() << (32-Size)) >> (32-Size);
705 if (Val != II->getValue()) {
706 // If sign-extended doesn't fit, does it fit as unsigned?
707 unsigned ValueMask = unsigned(MVT::getIntVTBitMask(VT));
708 unsigned UnsignedVal = unsigned(II->getValue());
710 if ((ValueMask & UnsignedVal) != UnsignedVal) {
711 TP.error("Integer value '" + itostr(II->getValue())+
712 "' is out of range for type '" +
713 getEnumName(getTypeNum(0)) + "'!");
725 // special handling for set, which isn't really an SDNode.
726 if (getOperator()->getName() == "set") {
727 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
728 unsigned NC = getNumChildren();
729 bool MadeChange = false;
730 for (unsigned i = 0; i < NC-1; ++i) {
731 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
732 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
734 // Types of operands must match.
735 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
737 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
739 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
742 } else if (getOperator()->getName() == "implicit" ||
743 getOperator()->getName() == "parallel") {
744 bool MadeChange = false;
745 for (unsigned i = 0; i < getNumChildren(); ++i)
746 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
747 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
749 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
750 bool MadeChange = false;
752 // Apply the result type to the node.
753 MadeChange = UpdateNodeType(Int->ArgVTs[0], TP);
755 if (getNumChildren() != Int->ArgVTs.size())
756 TP.error("Intrinsic '" + Int->Name + "' expects " +
757 utostr(Int->ArgVTs.size()-1) + " operands, not " +
758 utostr(getNumChildren()-1) + " operands!");
760 // Apply type info to the intrinsic ID.
761 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
763 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
764 MVT::ValueType OpVT = Int->ArgVTs[i];
765 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
766 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
769 } else if (getOperator()->isSubClassOf("SDNode")) {
770 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
772 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
773 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
774 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
775 // Branch, etc. do not produce results and top-level forms in instr pattern
776 // must have void types.
777 if (NI.getNumResults() == 0)
778 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
780 // If this is a vector_shuffle operation, apply types to the build_vector
781 // operation. The types of the integers don't matter, but this ensures they
782 // won't get checked.
783 if (getOperator()->getName() == "vector_shuffle" &&
784 getChild(2)->getOperator()->getName() == "build_vector") {
785 TreePatternNode *BV = getChild(2);
786 const std::vector<MVT::ValueType> &LegalVTs
787 = CDP.getTargetInfo().getLegalValueTypes();
788 MVT::ValueType LegalIntVT = MVT::Other;
789 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
790 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
791 LegalIntVT = LegalVTs[i];
794 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
796 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
797 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
800 } else if (getOperator()->isSubClassOf("Instruction")) {
801 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
802 bool MadeChange = false;
803 unsigned NumResults = Inst.getNumResults();
805 assert(NumResults <= 1 &&
806 "Only supports zero or one result instrs!");
808 CodeGenInstruction &InstInfo =
809 CDP.getTargetInfo().getInstruction(getOperator()->getName());
810 // Apply the result type to the node
811 if (NumResults == 0 || InstInfo.NumDefs == 0) {
812 MadeChange = UpdateNodeType(MVT::isVoid, TP);
814 Record *ResultNode = Inst.getResult(0);
816 if (ResultNode->getName() == "ptr_rc") {
817 std::vector<unsigned char> VT;
818 VT.push_back(MVT::iPTR);
819 MadeChange = UpdateNodeType(VT, TP);
821 assert(ResultNode->isSubClassOf("RegisterClass") &&
822 "Operands should be register classes!");
824 const CodeGenRegisterClass &RC =
825 CDP.getTargetInfo().getRegisterClass(ResultNode);
826 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
830 unsigned ChildNo = 0;
831 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
832 Record *OperandNode = Inst.getOperand(i);
834 // If the instruction expects a predicate or optional def operand, we
835 // codegen this by setting the operand to it's default value if it has a
836 // non-empty DefaultOps field.
837 if ((OperandNode->isSubClassOf("PredicateOperand") ||
838 OperandNode->isSubClassOf("OptionalDefOperand")) &&
839 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
842 // Verify that we didn't run out of provided operands.
843 if (ChildNo >= getNumChildren())
844 TP.error("Instruction '" + getOperator()->getName() +
845 "' expects more operands than were provided.");
848 TreePatternNode *Child = getChild(ChildNo++);
849 if (OperandNode->isSubClassOf("RegisterClass")) {
850 const CodeGenRegisterClass &RC =
851 CDP.getTargetInfo().getRegisterClass(OperandNode);
852 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
853 } else if (OperandNode->isSubClassOf("Operand")) {
854 VT = getValueType(OperandNode->getValueAsDef("Type"));
855 MadeChange |= Child->UpdateNodeType(VT, TP);
856 } else if (OperandNode->getName() == "ptr_rc") {
857 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
859 assert(0 && "Unknown operand type!");
862 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
865 if (ChildNo != getNumChildren())
866 TP.error("Instruction '" + getOperator()->getName() +
867 "' was provided too many operands!");
871 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
873 // Node transforms always take one operand.
874 if (getNumChildren() != 1)
875 TP.error("Node transform '" + getOperator()->getName() +
876 "' requires one operand!");
878 // If either the output or input of the xform does not have exact
879 // type info. We assume they must be the same. Otherwise, it is perfectly
880 // legal to transform from one type to a completely different type.
881 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
882 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
883 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
890 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
891 /// RHS of a commutative operation, not the on LHS.
892 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
893 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
895 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
901 /// canPatternMatch - If it is impossible for this pattern to match on this
902 /// target, fill in Reason and return false. Otherwise, return true. This is
903 /// used as a santity check for .td files (to prevent people from writing stuff
904 /// that can never possibly work), and to prevent the pattern permuter from
905 /// generating stuff that is useless.
906 bool TreePatternNode::canPatternMatch(std::string &Reason,
907 CodeGenDAGPatterns &CDP){
908 if (isLeaf()) return true;
910 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
911 if (!getChild(i)->canPatternMatch(Reason, CDP))
914 // If this is an intrinsic, handle cases that would make it not match. For
915 // example, if an operand is required to be an immediate.
916 if (getOperator()->isSubClassOf("Intrinsic")) {
921 // If this node is a commutative operator, check that the LHS isn't an
923 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
924 if (NodeInfo.hasProperty(SDNPCommutative)) {
925 // Scan all of the operands of the node and make sure that only the last one
926 // is a constant node, unless the RHS also is.
927 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
928 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
929 if (OnlyOnRHSOfCommutative(getChild(i))) {
930 Reason="Immediate value must be on the RHS of commutative operators!";
939 //===----------------------------------------------------------------------===//
940 // TreePattern implementation
943 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
944 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
945 isInputPattern = isInput;
946 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
947 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
950 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
951 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
952 isInputPattern = isInput;
953 Trees.push_back(ParseTreePattern(Pat));
956 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
957 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
958 isInputPattern = isInput;
959 Trees.push_back(Pat);
964 void TreePattern::error(const std::string &Msg) const {
966 throw "In " + TheRecord->getName() + ": " + Msg;
969 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
970 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
971 if (!OpDef) error("Pattern has unexpected operator type!");
972 Record *Operator = OpDef->getDef();
974 if (Operator->isSubClassOf("ValueType")) {
975 // If the operator is a ValueType, then this must be "type cast" of a leaf
977 if (Dag->getNumArgs() != 1)
978 error("Type cast only takes one operand!");
980 Init *Arg = Dag->getArg(0);
981 TreePatternNode *New;
982 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
983 Record *R = DI->getDef();
984 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
985 Dag->setArg(0, new DagInit(DI,
986 std::vector<std::pair<Init*, std::string> >()));
987 return ParseTreePattern(Dag);
989 New = new TreePatternNode(DI);
990 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
991 New = ParseTreePattern(DI);
992 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
993 New = new TreePatternNode(II);
994 if (!Dag->getArgName(0).empty())
995 error("Constant int argument should not have a name!");
996 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
997 // Turn this into an IntInit.
998 Init *II = BI->convertInitializerTo(new IntRecTy());
999 if (II == 0 || !dynamic_cast<IntInit*>(II))
1000 error("Bits value must be constants!");
1002 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1003 if (!Dag->getArgName(0).empty())
1004 error("Constant int argument should not have a name!");
1007 error("Unknown leaf value for tree pattern!");
1011 // Apply the type cast.
1012 New->UpdateNodeType(getValueType(Operator), *this);
1013 New->setName(Dag->getArgName(0));
1017 // Verify that this is something that makes sense for an operator.
1018 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
1019 !Operator->isSubClassOf("Instruction") &&
1020 !Operator->isSubClassOf("SDNodeXForm") &&
1021 !Operator->isSubClassOf("Intrinsic") &&
1022 Operator->getName() != "set" &&
1023 Operator->getName() != "implicit" &&
1024 Operator->getName() != "parallel")
1025 error("Unrecognized node '" + Operator->getName() + "'!");
1027 // Check to see if this is something that is illegal in an input pattern.
1028 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1029 Operator->isSubClassOf("SDNodeXForm")))
1030 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1032 std::vector<TreePatternNode*> Children;
1034 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1035 Init *Arg = Dag->getArg(i);
1036 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1037 Children.push_back(ParseTreePattern(DI));
1038 if (Children.back()->getName().empty())
1039 Children.back()->setName(Dag->getArgName(i));
1040 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1041 Record *R = DefI->getDef();
1042 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1043 // TreePatternNode if its own.
1044 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1045 Dag->setArg(i, new DagInit(DefI,
1046 std::vector<std::pair<Init*, std::string> >()));
1047 --i; // Revisit this node...
1049 TreePatternNode *Node = new TreePatternNode(DefI);
1050 Node->setName(Dag->getArgName(i));
1051 Children.push_back(Node);
1054 if (R->getName() == "node") {
1055 if (Dag->getArgName(i).empty())
1056 error("'node' argument requires a name to match with operand list");
1057 Args.push_back(Dag->getArgName(i));
1060 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1061 TreePatternNode *Node = new TreePatternNode(II);
1062 if (!Dag->getArgName(i).empty())
1063 error("Constant int argument should not have a name!");
1064 Children.push_back(Node);
1065 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1066 // Turn this into an IntInit.
1067 Init *II = BI->convertInitializerTo(new IntRecTy());
1068 if (II == 0 || !dynamic_cast<IntInit*>(II))
1069 error("Bits value must be constants!");
1071 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1072 if (!Dag->getArgName(i).empty())
1073 error("Constant int argument should not have a name!");
1074 Children.push_back(Node);
1079 error("Unknown leaf value for tree pattern!");
1083 // If the operator is an intrinsic, then this is just syntactic sugar for for
1084 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1085 // convert the intrinsic name to a number.
1086 if (Operator->isSubClassOf("Intrinsic")) {
1087 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1088 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1090 // If this intrinsic returns void, it must have side-effects and thus a
1092 if (Int.ArgVTs[0] == MVT::isVoid) {
1093 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1094 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1095 // Has side-effects, requires chain.
1096 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1098 // Otherwise, no chain.
1099 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1102 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1103 Children.insert(Children.begin(), IIDNode);
1106 return new TreePatternNode(Operator, Children);
1109 /// InferAllTypes - Infer/propagate as many types throughout the expression
1110 /// patterns as possible. Return true if all types are infered, false
1111 /// otherwise. Throw an exception if a type contradiction is found.
1112 bool TreePattern::InferAllTypes() {
1113 bool MadeChange = true;
1114 while (MadeChange) {
1116 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1117 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1120 bool HasUnresolvedTypes = false;
1121 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1122 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1123 return !HasUnresolvedTypes;
1126 void TreePattern::print(std::ostream &OS) const {
1127 OS << getRecord()->getName();
1128 if (!Args.empty()) {
1129 OS << "(" << Args[0];
1130 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1131 OS << ", " << Args[i];
1136 if (Trees.size() > 1)
1138 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1140 Trees[i]->print(OS);
1144 if (Trees.size() > 1)
1148 void TreePattern::dump() const { print(*cerr.stream()); }
1150 //===----------------------------------------------------------------------===//
1151 // CodeGenDAGPatterns implementation
1154 // FIXME: REMOVE OSTREAM ARGUMENT
1155 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1156 Intrinsics = LoadIntrinsics(Records);
1158 ParseNodeTransforms();
1159 ParseComplexPatterns();
1160 ParsePatternFragments();
1161 ParseDefaultOperands();
1162 ParseInstructions();
1165 // Generate variants. For example, commutative patterns can match
1166 // multiple ways. Add them to PatternsToMatch as well.
1170 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1171 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1172 E = PatternFragments.end(); I != E; ++I)
1177 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1178 Record *N = Records.getDef(Name);
1179 if (!N || !N->isSubClassOf("SDNode")) {
1180 cerr << "Error getting SDNode '" << Name << "'!\n";
1186 // Parse all of the SDNode definitions for the target, populating SDNodes.
1187 void CodeGenDAGPatterns::ParseNodeInfo() {
1188 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1189 while (!Nodes.empty()) {
1190 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1194 // Get the buildin intrinsic nodes.
1195 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1196 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1197 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1200 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1201 /// map, and emit them to the file as functions.
1202 void CodeGenDAGPatterns::ParseNodeTransforms() {
1203 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1204 while (!Xforms.empty()) {
1205 Record *XFormNode = Xforms.back();
1206 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1207 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1208 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1214 void CodeGenDAGPatterns::ParseComplexPatterns() {
1215 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1216 while (!AMs.empty()) {
1217 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1223 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1224 /// file, building up the PatternFragments map. After we've collected them all,
1225 /// inline fragments together as necessary, so that there are no references left
1226 /// inside a pattern fragment to a pattern fragment.
1228 void CodeGenDAGPatterns::ParsePatternFragments() {
1229 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1231 // First step, parse all of the fragments.
1232 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1233 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1234 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1235 PatternFragments[Fragments[i]] = P;
1237 // Validate the argument list, converting it to set, to discard duplicates.
1238 std::vector<std::string> &Args = P->getArgList();
1239 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1241 if (OperandsSet.count(""))
1242 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1244 // Parse the operands list.
1245 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1246 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1247 // Special cases: ops == outs == ins. Different names are used to
1248 // improve readibility.
1250 (OpsOp->getDef()->getName() != "ops" &&
1251 OpsOp->getDef()->getName() != "outs" &&
1252 OpsOp->getDef()->getName() != "ins"))
1253 P->error("Operands list should start with '(ops ... '!");
1255 // Copy over the arguments.
1257 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1258 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1259 static_cast<DefInit*>(OpsList->getArg(j))->
1260 getDef()->getName() != "node")
1261 P->error("Operands list should all be 'node' values.");
1262 if (OpsList->getArgName(j).empty())
1263 P->error("Operands list should have names for each operand!");
1264 if (!OperandsSet.count(OpsList->getArgName(j)))
1265 P->error("'" + OpsList->getArgName(j) +
1266 "' does not occur in pattern or was multiply specified!");
1267 OperandsSet.erase(OpsList->getArgName(j));
1268 Args.push_back(OpsList->getArgName(j));
1271 if (!OperandsSet.empty())
1272 P->error("Operands list does not contain an entry for operand '" +
1273 *OperandsSet.begin() + "'!");
1275 // If there is a code init for this fragment, keep track of the fact that
1276 // this fragment uses it.
1277 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1279 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1281 // If there is a node transformation corresponding to this, keep track of
1283 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1284 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1285 P->getOnlyTree()->setTransformFn(Transform);
1288 // Now that we've parsed all of the tree fragments, do a closure on them so
1289 // that there are not references to PatFrags left inside of them.
1290 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1291 E = PatternFragments.end(); I != E; ++I) {
1292 TreePattern *ThePat = I->second;
1293 ThePat->InlinePatternFragments();
1295 // Infer as many types as possible. Don't worry about it if we don't infer
1296 // all of them, some may depend on the inputs of the pattern.
1298 ThePat->InferAllTypes();
1300 // If this pattern fragment is not supported by this target (no types can
1301 // satisfy its constraints), just ignore it. If the bogus pattern is
1302 // actually used by instructions, the type consistency error will be
1306 // If debugging, print out the pattern fragment result.
1307 DEBUG(ThePat->dump());
1311 void CodeGenDAGPatterns::ParseDefaultOperands() {
1312 std::vector<Record*> DefaultOps[2];
1313 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1314 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1316 // Find some SDNode.
1317 assert(!SDNodes.empty() && "No SDNodes parsed?");
1318 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1320 for (unsigned iter = 0; iter != 2; ++iter) {
1321 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1322 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1324 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1325 // SomeSDnode so that we can parse this.
1326 std::vector<std::pair<Init*, std::string> > Ops;
1327 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1328 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1329 DefaultInfo->getArgName(op)));
1330 DagInit *DI = new DagInit(SomeSDNode, Ops);
1332 // Create a TreePattern to parse this.
1333 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1334 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1336 // Copy the operands over into a DAGDefaultOperand.
1337 DAGDefaultOperand DefaultOpInfo;
1339 TreePatternNode *T = P.getTree(0);
1340 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1341 TreePatternNode *TPN = T->getChild(op);
1342 while (TPN->ApplyTypeConstraints(P, false))
1343 /* Resolve all types */;
1345 if (TPN->ContainsUnresolvedType()) {
1347 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1348 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1350 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1351 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1353 DefaultOpInfo.DefaultOps.push_back(TPN);
1356 // Insert it into the DefaultOperands map so we can find it later.
1357 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1362 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1363 /// instruction input. Return true if this is a real use.
1364 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1365 std::map<std::string, TreePatternNode*> &InstInputs,
1366 std::vector<Record*> &InstImpInputs) {
1367 // No name -> not interesting.
1368 if (Pat->getName().empty()) {
1369 if (Pat->isLeaf()) {
1370 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1371 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1372 I->error("Input " + DI->getDef()->getName() + " must be named!");
1373 else if (DI && DI->getDef()->isSubClassOf("Register"))
1374 InstImpInputs.push_back(DI->getDef());
1381 if (Pat->isLeaf()) {
1382 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1383 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1386 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1387 Rec = Pat->getOperator();
1390 // SRCVALUE nodes are ignored.
1391 if (Rec->getName() == "srcvalue")
1394 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1399 if (Slot->isLeaf()) {
1400 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1402 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1403 SlotRec = Slot->getOperator();
1406 // Ensure that the inputs agree if we've already seen this input.
1408 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1409 if (Slot->getExtTypes() != Pat->getExtTypes())
1410 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1415 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1416 /// part of "I", the instruction), computing the set of inputs and outputs of
1417 /// the pattern. Report errors if we see anything naughty.
1418 void CodeGenDAGPatterns::
1419 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1420 std::map<std::string, TreePatternNode*> &InstInputs,
1421 std::map<std::string, TreePatternNode*>&InstResults,
1422 std::vector<Record*> &InstImpInputs,
1423 std::vector<Record*> &InstImpResults) {
1424 if (Pat->isLeaf()) {
1425 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1426 if (!isUse && Pat->getTransformFn())
1427 I->error("Cannot specify a transform function for a non-input value!");
1429 } else if (Pat->getOperator()->getName() == "implicit") {
1430 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1431 TreePatternNode *Dest = Pat->getChild(i);
1432 if (!Dest->isLeaf())
1433 I->error("implicitly defined value should be a register!");
1435 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1436 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1437 I->error("implicitly defined value should be a register!");
1438 InstImpResults.push_back(Val->getDef());
1441 } else if (Pat->getOperator()->getName() != "set") {
1442 // If this is not a set, verify that the children nodes are not void typed,
1444 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1445 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1446 I->error("Cannot have void nodes inside of patterns!");
1447 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1448 InstImpInputs, InstImpResults);
1451 // If this is a non-leaf node with no children, treat it basically as if
1452 // it were a leaf. This handles nodes like (imm).
1454 if (Pat->getNumChildren() == 0)
1455 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1457 if (!isUse && Pat->getTransformFn())
1458 I->error("Cannot specify a transform function for a non-input value!");
1462 // Otherwise, this is a set, validate and collect instruction results.
1463 if (Pat->getNumChildren() == 0)
1464 I->error("set requires operands!");
1466 if (Pat->getTransformFn())
1467 I->error("Cannot specify a transform function on a set node!");
1469 // Check the set destinations.
1470 unsigned NumDests = Pat->getNumChildren()-1;
1471 for (unsigned i = 0; i != NumDests; ++i) {
1472 TreePatternNode *Dest = Pat->getChild(i);
1473 if (!Dest->isLeaf())
1474 I->error("set destination should be a register!");
1476 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1478 I->error("set destination should be a register!");
1480 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1481 Val->getDef()->getName() == "ptr_rc") {
1482 if (Dest->getName().empty())
1483 I->error("set destination must have a name!");
1484 if (InstResults.count(Dest->getName()))
1485 I->error("cannot set '" + Dest->getName() +"' multiple times");
1486 InstResults[Dest->getName()] = Dest;
1487 } else if (Val->getDef()->isSubClassOf("Register")) {
1488 InstImpResults.push_back(Val->getDef());
1490 I->error("set destination should be a register!");
1494 // Verify and collect info from the computation.
1495 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1496 InstInputs, InstResults,
1497 InstImpInputs, InstImpResults);
1500 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1501 /// any fragments involved. This populates the Instructions list with fully
1502 /// resolved instructions.
1503 void CodeGenDAGPatterns::ParseInstructions() {
1504 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1506 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1509 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1510 LI = Instrs[i]->getValueAsListInit("Pattern");
1512 // If there is no pattern, only collect minimal information about the
1513 // instruction for its operand list. We have to assume that there is one
1514 // result, as we have no detailed info.
1515 if (!LI || LI->getSize() == 0) {
1516 std::vector<Record*> Results;
1517 std::vector<Record*> Operands;
1519 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1521 if (InstInfo.OperandList.size() != 0) {
1522 if (InstInfo.NumDefs == 0) {
1523 // These produce no results
1524 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1525 Operands.push_back(InstInfo.OperandList[j].Rec);
1527 // Assume the first operand is the result.
1528 Results.push_back(InstInfo.OperandList[0].Rec);
1530 // The rest are inputs.
1531 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1532 Operands.push_back(InstInfo.OperandList[j].Rec);
1536 // Create and insert the instruction.
1537 std::vector<Record*> ImpResults;
1538 std::vector<Record*> ImpOperands;
1539 Instructions.insert(std::make_pair(Instrs[i],
1540 DAGInstruction(0, Results, Operands, ImpResults,
1542 continue; // no pattern.
1545 // Parse the instruction.
1546 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1547 // Inline pattern fragments into it.
1548 I->InlinePatternFragments();
1550 // Infer as many types as possible. If we cannot infer all of them, we can
1551 // never do anything with this instruction pattern: report it to the user.
1552 if (!I->InferAllTypes())
1553 I->error("Could not infer all types in pattern!");
1555 // InstInputs - Keep track of all of the inputs of the instruction, along
1556 // with the record they are declared as.
1557 std::map<std::string, TreePatternNode*> InstInputs;
1559 // InstResults - Keep track of all the virtual registers that are 'set'
1560 // in the instruction, including what reg class they are.
1561 std::map<std::string, TreePatternNode*> InstResults;
1563 std::vector<Record*> InstImpInputs;
1564 std::vector<Record*> InstImpResults;
1566 // Verify that the top-level forms in the instruction are of void type, and
1567 // fill in the InstResults map.
1568 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1569 TreePatternNode *Pat = I->getTree(j);
1570 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1571 I->error("Top-level forms in instruction pattern should have"
1574 // Find inputs and outputs, and verify the structure of the uses/defs.
1575 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1576 InstImpInputs, InstImpResults);
1579 // Now that we have inputs and outputs of the pattern, inspect the operands
1580 // list for the instruction. This determines the order that operands are
1581 // added to the machine instruction the node corresponds to.
1582 unsigned NumResults = InstResults.size();
1584 // Parse the operands list from the (ops) list, validating it.
1585 assert(I->getArgList().empty() && "Args list should still be empty here!");
1586 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1588 // Check that all of the results occur first in the list.
1589 std::vector<Record*> Results;
1590 TreePatternNode *Res0Node = NULL;
1591 for (unsigned i = 0; i != NumResults; ++i) {
1592 if (i == CGI.OperandList.size())
1593 I->error("'" + InstResults.begin()->first +
1594 "' set but does not appear in operand list!");
1595 const std::string &OpName = CGI.OperandList[i].Name;
1597 // Check that it exists in InstResults.
1598 TreePatternNode *RNode = InstResults[OpName];
1600 I->error("Operand $" + OpName + " does not exist in operand list!");
1604 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1606 I->error("Operand $" + OpName + " should be a set destination: all "
1607 "outputs must occur before inputs in operand list!");
1609 if (CGI.OperandList[i].Rec != R)
1610 I->error("Operand $" + OpName + " class mismatch!");
1612 // Remember the return type.
1613 Results.push_back(CGI.OperandList[i].Rec);
1615 // Okay, this one checks out.
1616 InstResults.erase(OpName);
1619 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1620 // the copy while we're checking the inputs.
1621 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1623 std::vector<TreePatternNode*> ResultNodeOperands;
1624 std::vector<Record*> Operands;
1625 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1626 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1627 const std::string &OpName = Op.Name;
1629 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1631 if (!InstInputsCheck.count(OpName)) {
1632 // If this is an predicate operand or optional def operand with an
1633 // DefaultOps set filled in, we can ignore this. When we codegen it,
1634 // we will do so as always executed.
1635 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1636 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1637 // Does it have a non-empty DefaultOps field? If so, ignore this
1639 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1642 I->error("Operand $" + OpName +
1643 " does not appear in the instruction pattern");
1645 TreePatternNode *InVal = InstInputsCheck[OpName];
1646 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1648 if (InVal->isLeaf() &&
1649 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1650 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1651 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1652 I->error("Operand $" + OpName + "'s register class disagrees"
1653 " between the operand and pattern");
1655 Operands.push_back(Op.Rec);
1657 // Construct the result for the dest-pattern operand list.
1658 TreePatternNode *OpNode = InVal->clone();
1660 // No predicate is useful on the result.
1661 OpNode->setPredicateFn("");
1663 // Promote the xform function to be an explicit node if set.
1664 if (Record *Xform = OpNode->getTransformFn()) {
1665 OpNode->setTransformFn(0);
1666 std::vector<TreePatternNode*> Children;
1667 Children.push_back(OpNode);
1668 OpNode = new TreePatternNode(Xform, Children);
1671 ResultNodeOperands.push_back(OpNode);
1674 if (!InstInputsCheck.empty())
1675 I->error("Input operand $" + InstInputsCheck.begin()->first +
1676 " occurs in pattern but not in operands list!");
1678 TreePatternNode *ResultPattern =
1679 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1680 // Copy fully inferred output node type to instruction result pattern.
1682 ResultPattern->setTypes(Res0Node->getExtTypes());
1684 // Create and insert the instruction.
1685 // FIXME: InstImpResults and InstImpInputs should not be part of
1687 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1688 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1690 // Use a temporary tree pattern to infer all types and make sure that the
1691 // constructed result is correct. This depends on the instruction already
1692 // being inserted into the Instructions map.
1693 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1694 Temp.InferAllTypes();
1696 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1697 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1702 // If we can, convert the instructions to be patterns that are matched!
1703 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1704 E = Instructions.end(); II != E; ++II) {
1705 DAGInstruction &TheInst = II->second;
1706 const TreePattern *I = TheInst.getPattern();
1707 if (I == 0) continue; // No pattern.
1709 // FIXME: Assume only the first tree is the pattern. The others are clobber
1711 TreePatternNode *Pattern = I->getTree(0);
1712 TreePatternNode *SrcPattern;
1713 if (Pattern->getOperator()->getName() == "set") {
1714 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1716 // Not a set (store or something?)
1717 SrcPattern = Pattern;
1721 if (!SrcPattern->canPatternMatch(Reason, *this))
1722 I->error("Instruction can never match: " + Reason);
1724 Record *Instr = II->first;
1725 TreePatternNode *DstPattern = TheInst.getResultPattern();
1727 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1728 SrcPattern, DstPattern, TheInst.getImpResults(),
1729 Instr->getValueAsInt("AddedComplexity")));
1733 void CodeGenDAGPatterns::ParsePatterns() {
1734 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1736 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1737 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1738 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
1739 Record *Operator = OpDef->getDef();
1740 TreePattern *Pattern;
1741 if (Operator->getName() != "parallel")
1742 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1744 std::vector<Init*> Values;
1745 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
1746 Values.push_back(Tree->getArg(j));
1747 ListInit *LI = new ListInit(Values);
1748 Pattern = new TreePattern(Patterns[i], LI, true, *this);
1751 // Inline pattern fragments into it.
1752 Pattern->InlinePatternFragments();
1754 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1755 if (LI->getSize() == 0) continue; // no pattern.
1757 // Parse the instruction.
1758 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1760 // Inline pattern fragments into it.
1761 Result->InlinePatternFragments();
1763 if (Result->getNumTrees() != 1)
1764 Result->error("Cannot handle instructions producing instructions "
1765 "with temporaries yet!");
1767 bool IterateInference;
1768 bool InferredAllPatternTypes, InferredAllResultTypes;
1770 // Infer as many types as possible. If we cannot infer all of them, we
1771 // can never do anything with this pattern: report it to the user.
1772 InferredAllPatternTypes = Pattern->InferAllTypes();
1774 // Infer as many types as possible. If we cannot infer all of them, we
1775 // can never do anything with this pattern: report it to the user.
1776 InferredAllResultTypes = Result->InferAllTypes();
1778 // Apply the type of the result to the source pattern. This helps us
1779 // resolve cases where the input type is known to be a pointer type (which
1780 // is considered resolved), but the result knows it needs to be 32- or
1781 // 64-bits. Infer the other way for good measure.
1782 IterateInference = Pattern->getTree(0)->
1783 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
1784 IterateInference |= Result->getTree(0)->
1785 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
1786 } while (IterateInference);
1788 // Verify that we inferred enough types that we can do something with the
1789 // pattern and result. If these fire the user has to add type casts.
1790 if (!InferredAllPatternTypes)
1791 Pattern->error("Could not infer all types in pattern!");
1792 if (!InferredAllResultTypes)
1793 Result->error("Could not infer all types in pattern result!");
1795 // Validate that the input pattern is correct.
1796 std::map<std::string, TreePatternNode*> InstInputs;
1797 std::map<std::string, TreePatternNode*> InstResults;
1798 std::vector<Record*> InstImpInputs;
1799 std::vector<Record*> InstImpResults;
1800 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
1801 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
1802 InstInputs, InstResults,
1803 InstImpInputs, InstImpResults);
1805 // Promote the xform function to be an explicit node if set.
1806 TreePatternNode *DstPattern = Result->getOnlyTree();
1807 std::vector<TreePatternNode*> ResultNodeOperands;
1808 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1809 TreePatternNode *OpNode = DstPattern->getChild(ii);
1810 if (Record *Xform = OpNode->getTransformFn()) {
1811 OpNode->setTransformFn(0);
1812 std::vector<TreePatternNode*> Children;
1813 Children.push_back(OpNode);
1814 OpNode = new TreePatternNode(Xform, Children);
1816 ResultNodeOperands.push_back(OpNode);
1818 DstPattern = Result->getOnlyTree();
1819 if (!DstPattern->isLeaf())
1820 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1821 ResultNodeOperands);
1822 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1823 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1824 Temp.InferAllTypes();
1827 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
1828 Pattern->error("Pattern can never match: " + Reason);
1831 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1832 Pattern->getTree(0),
1833 Temp.getOnlyTree(), InstImpResults,
1834 Patterns[i]->getValueAsInt("AddedComplexity")));
1838 /// CombineChildVariants - Given a bunch of permutations of each child of the
1839 /// 'operator' node, put them together in all possible ways.
1840 static void CombineChildVariants(TreePatternNode *Orig,
1841 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1842 std::vector<TreePatternNode*> &OutVariants,
1843 CodeGenDAGPatterns &CDP) {
1844 // Make sure that each operand has at least one variant to choose from.
1845 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1846 if (ChildVariants[i].empty())
1849 // The end result is an all-pairs construction of the resultant pattern.
1850 std::vector<unsigned> Idxs;
1851 Idxs.resize(ChildVariants.size());
1852 bool NotDone = true;
1854 // Create the variant and add it to the output list.
1855 std::vector<TreePatternNode*> NewChildren;
1856 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1857 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1858 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1860 // Copy over properties.
1861 R->setName(Orig->getName());
1862 R->setPredicateFn(Orig->getPredicateFn());
1863 R->setTransformFn(Orig->getTransformFn());
1864 R->setTypes(Orig->getExtTypes());
1866 // If this pattern cannot every match, do not include it as a variant.
1867 std::string ErrString;
1868 if (!R->canPatternMatch(ErrString, CDP)) {
1871 bool AlreadyExists = false;
1873 // Scan to see if this pattern has already been emitted. We can get
1874 // duplication due to things like commuting:
1875 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1876 // which are the same pattern. Ignore the dups.
1877 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1878 if (R->isIsomorphicTo(OutVariants[i])) {
1879 AlreadyExists = true;
1886 OutVariants.push_back(R);
1889 // Increment indices to the next permutation.
1891 // Look for something we can increment without causing a wrap-around.
1892 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1893 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1894 NotDone = true; // Found something to increment.
1902 /// CombineChildVariants - A helper function for binary operators.
1904 static void CombineChildVariants(TreePatternNode *Orig,
1905 const std::vector<TreePatternNode*> &LHS,
1906 const std::vector<TreePatternNode*> &RHS,
1907 std::vector<TreePatternNode*> &OutVariants,
1908 CodeGenDAGPatterns &CDP) {
1909 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1910 ChildVariants.push_back(LHS);
1911 ChildVariants.push_back(RHS);
1912 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP);
1916 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1917 std::vector<TreePatternNode *> &Children) {
1918 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1919 Record *Operator = N->getOperator();
1921 // Only permit raw nodes.
1922 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1923 N->getTransformFn()) {
1924 Children.push_back(N);
1928 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1929 Children.push_back(N->getChild(0));
1931 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1933 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1934 Children.push_back(N->getChild(1));
1936 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1939 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1940 /// the (potentially recursive) pattern by using algebraic laws.
1942 static void GenerateVariantsOf(TreePatternNode *N,
1943 std::vector<TreePatternNode*> &OutVariants,
1944 CodeGenDAGPatterns &CDP) {
1945 // We cannot permute leaves.
1947 OutVariants.push_back(N);
1951 // Look up interesting info about the node.
1952 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
1954 // If this node is associative, reassociate.
1955 if (NodeInfo.hasProperty(SDNPAssociative)) {
1956 // Reassociate by pulling together all of the linked operators
1957 std::vector<TreePatternNode*> MaximalChildren;
1958 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1960 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1962 if (MaximalChildren.size() == 3) {
1963 // Find the variants of all of our maximal children.
1964 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1965 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP);
1966 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP);
1967 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP);
1969 // There are only two ways we can permute the tree:
1970 // (A op B) op C and A op (B op C)
1971 // Within these forms, we can also permute A/B/C.
1973 // Generate legal pair permutations of A/B/C.
1974 std::vector<TreePatternNode*> ABVariants;
1975 std::vector<TreePatternNode*> BAVariants;
1976 std::vector<TreePatternNode*> ACVariants;
1977 std::vector<TreePatternNode*> CAVariants;
1978 std::vector<TreePatternNode*> BCVariants;
1979 std::vector<TreePatternNode*> CBVariants;
1980 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP);
1981 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP);
1982 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP);
1983 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP);
1984 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP);
1985 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP);
1987 // Combine those into the result: (x op x) op x
1988 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP);
1989 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP);
1990 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP);
1991 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP);
1992 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP);
1993 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP);
1995 // Combine those into the result: x op (x op x)
1996 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP);
1997 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP);
1998 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP);
1999 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP);
2000 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP);
2001 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP);
2006 // Compute permutations of all children.
2007 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2008 ChildVariants.resize(N->getNumChildren());
2009 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2010 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP);
2012 // Build all permutations based on how the children were formed.
2013 CombineChildVariants(N, ChildVariants, OutVariants, CDP);
2015 // If this node is commutative, consider the commuted order.
2016 if (NodeInfo.hasProperty(SDNPCommutative)) {
2017 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
2018 // Don't count children which are actually register references.
2020 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2021 TreePatternNode *Child = N->getChild(i);
2022 if (Child->isLeaf())
2023 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2024 Record *RR = DI->getDef();
2025 if (RR->isSubClassOf("Register"))
2030 // Consider the commuted order.
2032 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2038 // GenerateVariants - Generate variants. For example, commutative patterns can
2039 // match multiple ways. Add them to PatternsToMatch as well.
2040 void CodeGenDAGPatterns::GenerateVariants() {
2041 DOUT << "Generating instruction variants.\n";
2043 // Loop over all of the patterns we've collected, checking to see if we can
2044 // generate variants of the instruction, through the exploitation of
2045 // identities. This permits the target to provide agressive matching without
2046 // the .td file having to contain tons of variants of instructions.
2048 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2049 // intentionally do not reconsider these. Any variants of added patterns have
2050 // already been added.
2052 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2053 std::vector<TreePatternNode*> Variants;
2054 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
2056 assert(!Variants.empty() && "Must create at least original variant!");
2057 Variants.erase(Variants.begin()); // Remove the original pattern.
2059 if (Variants.empty()) // No variants for this pattern.
2062 DOUT << "FOUND VARIANTS OF: ";
2063 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2066 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2067 TreePatternNode *Variant = Variants[v];
2069 DOUT << " VAR#" << v << ": ";
2070 DEBUG(Variant->dump());
2073 // Scan to see if an instruction or explicit pattern already matches this.
2074 bool AlreadyExists = false;
2075 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2076 // Check to see if this variant already exists.
2077 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
2078 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2079 AlreadyExists = true;
2083 // If we already have it, ignore the variant.
2084 if (AlreadyExists) continue;
2086 // Otherwise, add it to the list of patterns we have.
2088 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2089 Variant, PatternsToMatch[i].getDstPattern(),
2090 PatternsToMatch[i].getDstRegs(),
2091 PatternsToMatch[i].getAddedComplexity()));