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]);
37 /// isExtIntegerVT - Return true if the specified extended value type is
38 /// integer, or isInt.
39 static bool isExtIntegerVT(unsigned char VT) {
40 return VT == MVT::isInt ||
41 (VT < MVT::LAST_VALUETYPE && MVT::isInteger((MVT::ValueType)VT));
44 /// isExtFloatingPointVT - Return true if the specified extended value type is
45 /// floating point, or isFP.
46 static bool isExtFloatingPointVT(unsigned char VT) {
47 return VT == MVT::isFP ||
48 (VT < MVT::LAST_VALUETYPE && MVT::isFloatingPoint((MVT::ValueType)VT));
51 //===----------------------------------------------------------------------===//
52 // SDTypeConstraint implementation
55 SDTypeConstraint::SDTypeConstraint(Record *R) {
56 OperandNo = R->getValueAsInt("OperandNum");
58 if (R->isSubClassOf("SDTCisVT")) {
59 ConstraintType = SDTCisVT;
60 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
61 } else if (R->isSubClassOf("SDTCisPtrTy")) {
62 ConstraintType = SDTCisPtrTy;
63 } else if (R->isSubClassOf("SDTCisInt")) {
64 ConstraintType = SDTCisInt;
65 } else if (R->isSubClassOf("SDTCisFP")) {
66 ConstraintType = SDTCisFP;
67 } else if (R->isSubClassOf("SDTCisSameAs")) {
68 ConstraintType = SDTCisSameAs;
69 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
70 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
71 ConstraintType = SDTCisVTSmallerThanOp;
72 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
73 R->getValueAsInt("OtherOperandNum");
74 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
75 ConstraintType = SDTCisOpSmallerThanOp;
76 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
77 R->getValueAsInt("BigOperandNum");
79 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
84 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
85 /// N, which has NumResults results.
86 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
88 unsigned NumResults) const {
89 assert(NumResults <= 1 &&
90 "We only work with nodes with zero or one result so far!");
92 if (OpNo < NumResults)
93 return N; // FIXME: need value #
95 return N->getChild(OpNo-NumResults);
98 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
99 /// constraint to the nodes operands. This returns true if it makes a
100 /// change, false otherwise. If a type contradiction is found, throw an
102 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
103 const SDNodeInfo &NodeInfo,
104 TreePattern &TP) const {
105 unsigned NumResults = NodeInfo.getNumResults();
106 assert(NumResults <= 1 &&
107 "We only work with nodes with zero or one result so far!");
109 // Check that the number of operands is sane.
110 if (NodeInfo.getNumOperands() >= 0) {
111 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
112 TP.error(N->getOperator()->getName() + " node requires exactly " +
113 itostr(NodeInfo.getNumOperands()) + " operands!");
116 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
118 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
120 switch (ConstraintType) {
121 default: assert(0 && "Unknown constraint type!");
123 // Operand must be a particular type.
124 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
126 // Operand must be same as target pointer type.
127 return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
130 // If there is only one integer type supported, this must be it.
131 std::vector<MVT::ValueType> IntVTs =
132 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
134 // If we found exactly one supported integer type, apply it.
135 if (IntVTs.size() == 1)
136 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
137 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
140 // If there is only one FP type supported, this must be it.
141 std::vector<MVT::ValueType> FPVTs =
142 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
144 // If we found exactly one supported FP type, apply it.
145 if (FPVTs.size() == 1)
146 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
147 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
150 TreePatternNode *OtherNode =
151 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
152 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
153 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
155 case SDTCisVTSmallerThanOp: {
156 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
157 // have an integer type that is smaller than the VT.
158 if (!NodeToApply->isLeaf() ||
159 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
160 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
161 ->isSubClassOf("ValueType"))
162 TP.error(N->getOperator()->getName() + " expects a VT operand!");
164 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
165 if (!MVT::isInteger(VT))
166 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
168 TreePatternNode *OtherNode =
169 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
171 // It must be integer.
172 bool MadeChange = false;
173 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
175 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
176 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
179 case SDTCisOpSmallerThanOp: {
180 TreePatternNode *BigOperand =
181 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
183 // Both operands must be integer or FP, but we don't care which.
184 bool MadeChange = false;
186 if (isExtIntegerVT(NodeToApply->getExtType()))
187 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
188 else if (isExtFloatingPointVT(NodeToApply->getExtType()))
189 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
190 if (isExtIntegerVT(BigOperand->getExtType()))
191 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
192 else if (isExtFloatingPointVT(BigOperand->getExtType()))
193 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
195 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
197 if (isExtIntegerVT(NodeToApply->getExtType())) {
198 VTs = FilterVTs(VTs, MVT::isInteger);
199 } else if (isExtFloatingPointVT(NodeToApply->getExtType())) {
200 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
205 switch (VTs.size()) {
206 default: // Too many VT's to pick from.
207 case 0: break; // No info yet.
209 // Only one VT of this flavor. Cannot ever satisify the constraints.
210 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
212 // If we have exactly two possible types, the little operand must be the
213 // small one, the big operand should be the big one. Common with
214 // float/double for example.
215 assert(VTs[0] < VTs[1] && "Should be sorted!");
216 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
217 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
227 //===----------------------------------------------------------------------===//
228 // SDNodeInfo implementation
230 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
231 EnumName = R->getValueAsString("Opcode");
232 SDClassName = R->getValueAsString("SDClass");
233 Record *TypeProfile = R->getValueAsDef("TypeProfile");
234 NumResults = TypeProfile->getValueAsInt("NumResults");
235 NumOperands = TypeProfile->getValueAsInt("NumOperands");
237 // Parse the properties.
239 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
240 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
241 if (PropList[i]->getName() == "SDNPCommutative") {
242 Properties |= 1 << SDNPCommutative;
243 } else if (PropList[i]->getName() == "SDNPAssociative") {
244 Properties |= 1 << SDNPAssociative;
245 } else if (PropList[i]->getName() == "SDNPHasChain") {
246 Properties |= 1 << SDNPHasChain;
248 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
249 << "' on node '" << R->getName() << "'!\n";
255 // Parse the type constraints.
256 std::vector<Record*> ConstraintList =
257 TypeProfile->getValueAsListOfDefs("Constraints");
258 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
261 //===----------------------------------------------------------------------===//
262 // TreePatternNode implementation
265 TreePatternNode::~TreePatternNode() {
266 #if 0 // FIXME: implement refcounted tree nodes!
267 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
272 /// UpdateNodeType - Set the node type of N to VT if VT contains
273 /// information. If N already contains a conflicting type, then throw an
274 /// exception. This returns true if any information was updated.
276 bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
277 if (VT == MVT::isUnknown || getExtType() == VT) return false;
278 if (getExtType() == MVT::isUnknown) {
283 // If we are told this is to be an int or FP type, and it already is, ignore
285 if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
286 (VT == MVT::isFP && isExtFloatingPointVT(getExtType())))
289 // If we know this is an int or fp type, and we are told it is a specific one,
291 if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
292 (getExtType() == MVT::isFP && isExtFloatingPointVT(VT))) {
299 TP.error("Type inference contradiction found in node!");
301 TP.error("Type inference contradiction found in node " +
302 getOperator()->getName() + "!");
304 return true; // unreachable
308 void TreePatternNode::print(std::ostream &OS) const {
310 OS << *getLeafValue();
312 OS << "(" << getOperator()->getName();
315 switch (getExtType()) {
316 case MVT::Other: OS << ":Other"; break;
317 case MVT::isInt: OS << ":isInt"; break;
318 case MVT::isFP : OS << ":isFP"; break;
319 case MVT::isUnknown: ; /*OS << ":?";*/ break;
320 default: OS << ":" << getType(); break;
324 if (getNumChildren() != 0) {
326 getChild(0)->print(OS);
327 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
329 getChild(i)->print(OS);
335 if (!PredicateFn.empty())
336 OS << "<<P:" << PredicateFn << ">>";
338 OS << "<<X:" << TransformFn->getName() << ">>";
339 if (!getName().empty())
340 OS << ":$" << getName();
343 void TreePatternNode::dump() const {
347 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
348 /// the specified node. For this comparison, all of the state of the node
349 /// is considered, except for the assigned name. Nodes with differing names
350 /// that are otherwise identical are considered isomorphic.
351 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
352 if (N == this) return true;
353 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
354 getPredicateFn() != N->getPredicateFn() ||
355 getTransformFn() != N->getTransformFn())
359 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
360 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
361 return DI->getDef() == NDI->getDef();
362 return getLeafValue() == N->getLeafValue();
365 if (N->getOperator() != getOperator() ||
366 N->getNumChildren() != getNumChildren()) return false;
367 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
368 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
373 /// clone - Make a copy of this tree and all of its children.
375 TreePatternNode *TreePatternNode::clone() const {
376 TreePatternNode *New;
378 New = new TreePatternNode(getLeafValue());
380 std::vector<TreePatternNode*> CChildren;
381 CChildren.reserve(Children.size());
382 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
383 CChildren.push_back(getChild(i)->clone());
384 New = new TreePatternNode(getOperator(), CChildren);
386 New->setName(getName());
387 New->setType(getExtType());
388 New->setPredicateFn(getPredicateFn());
389 New->setTransformFn(getTransformFn());
393 /// SubstituteFormalArguments - Replace the formal arguments in this tree
394 /// with actual values specified by ArgMap.
395 void TreePatternNode::
396 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
397 if (isLeaf()) return;
399 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
400 TreePatternNode *Child = getChild(i);
401 if (Child->isLeaf()) {
402 Init *Val = Child->getLeafValue();
403 if (dynamic_cast<DefInit*>(Val) &&
404 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
405 // We found a use of a formal argument, replace it with its value.
406 Child = ArgMap[Child->getName()];
407 assert(Child && "Couldn't find formal argument!");
411 getChild(i)->SubstituteFormalArguments(ArgMap);
417 /// InlinePatternFragments - If this pattern refers to any pattern
418 /// fragments, inline them into place, giving us a pattern without any
419 /// PatFrag references.
420 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
421 if (isLeaf()) return this; // nothing to do.
422 Record *Op = getOperator();
424 if (!Op->isSubClassOf("PatFrag")) {
425 // Just recursively inline children nodes.
426 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
427 setChild(i, getChild(i)->InlinePatternFragments(TP));
431 // Otherwise, we found a reference to a fragment. First, look up its
432 // TreePattern record.
433 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
435 // Verify that we are passing the right number of operands.
436 if (Frag->getNumArgs() != Children.size())
437 TP.error("'" + Op->getName() + "' fragment requires " +
438 utostr(Frag->getNumArgs()) + " operands!");
440 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
442 // Resolve formal arguments to their actual value.
443 if (Frag->getNumArgs()) {
444 // Compute the map of formal to actual arguments.
445 std::map<std::string, TreePatternNode*> ArgMap;
446 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
447 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
449 FragTree->SubstituteFormalArguments(ArgMap);
452 FragTree->setName(getName());
453 FragTree->UpdateNodeType(getExtType(), TP);
455 // Get a new copy of this fragment to stitch into here.
456 //delete this; // FIXME: implement refcounting!
460 /// getIntrinsicType - Check to see if the specified record has an intrinsic
461 /// type which should be applied to it. This infer the type of register
462 /// references from the register file information, for example.
464 static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
466 // Check to see if this is a register or a register class...
467 if (R->isSubClassOf("RegisterClass")) {
468 if (NotRegisters) return MVT::isUnknown;
469 const CodeGenRegisterClass &RC =
470 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
471 return RC.getValueTypeNum(0);
472 } else if (R->isSubClassOf("PatFrag")) {
473 // Pattern fragment types will be resolved when they are inlined.
474 return MVT::isUnknown;
475 } else if (R->isSubClassOf("Register")) {
476 // If the register appears in exactly one regclass, and the regclass has one
477 // value type, use it as the known type.
478 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
479 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
480 if (RC->getNumValueTypes() == 1)
481 return RC->getValueTypeNum(0);
482 return MVT::isUnknown;
483 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
484 // Using a VTSDNode or CondCodeSDNode.
486 } else if (R->isSubClassOf("ComplexPattern")) {
487 return TP.getDAGISelEmitter().getComplexPattern(R).getValueType();
488 } else if (R->getName() == "node") {
490 return MVT::isUnknown;
493 TP.error("Unknown node flavor used in pattern: " + R->getName());
497 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
498 /// this node and its children in the tree. This returns true if it makes a
499 /// change, false otherwise. If a type contradiction is found, throw an
501 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
503 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
504 // If it's a regclass or something else known, include the type.
505 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
507 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
508 // Int inits are always integers. :)
509 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
512 unsigned Size = MVT::getSizeInBits(getType());
513 // Make sure that the value is representable for this type.
515 int Val = (II->getValue() << (32-Size)) >> (32-Size);
516 if (Val != II->getValue())
517 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
518 "' is out of range for type 'MVT::" +
519 getEnumName(getType()) + "'!");
528 // special handling for set, which isn't really an SDNode.
529 if (getOperator()->getName() == "set") {
530 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
531 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
532 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
534 // Types of operands must match.
535 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
536 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
537 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
539 } else if (getOperator()->isSubClassOf("SDNode")) {
540 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
542 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
543 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
544 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
545 // Branch, etc. do not produce results and top-level forms in instr pattern
546 // must have void types.
547 if (NI.getNumResults() == 0)
548 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
550 } else if (getOperator()->isSubClassOf("Instruction")) {
551 const DAGInstruction &Inst =
552 TP.getDAGISelEmitter().getInstruction(getOperator());
553 bool MadeChange = false;
554 unsigned NumResults = Inst.getNumResults();
556 assert(NumResults <= 1 &&
557 "Only supports zero or one result instrs!");
558 // Apply the result type to the node
559 if (NumResults == 0) {
560 MadeChange = UpdateNodeType(MVT::isVoid, TP);
562 Record *ResultNode = Inst.getResult(0);
563 assert(ResultNode->isSubClassOf("RegisterClass") &&
564 "Operands should be register classes!");
566 const CodeGenRegisterClass &RC =
567 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
569 // Get the first ValueType in the RegClass, it's as good as any.
570 MadeChange = UpdateNodeType(RC.getValueTypeNum(0), TP);
573 if (getNumChildren() != Inst.getNumOperands())
574 TP.error("Instruction '" + getOperator()->getName() + " expects " +
575 utostr(Inst.getNumOperands()) + " operands, not " +
576 utostr(getNumChildren()) + " operands!");
577 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
578 Record *OperandNode = Inst.getOperand(i);
580 if (OperandNode->isSubClassOf("RegisterClass")) {
581 const CodeGenRegisterClass &RC =
582 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
583 VT = RC.getValueTypeNum(0);
584 } else if (OperandNode->isSubClassOf("Operand")) {
585 VT = getValueType(OperandNode->getValueAsDef("Type"));
587 assert(0 && "Unknown operand type!");
591 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
592 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
596 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
598 // Node transforms always take one operand, and take and return the same
600 if (getNumChildren() != 1)
601 TP.error("Node transform '" + getOperator()->getName() +
602 "' requires one operand!");
603 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
604 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
609 /// canPatternMatch - If it is impossible for this pattern to match on this
610 /// target, fill in Reason and return false. Otherwise, return true. This is
611 /// used as a santity check for .td files (to prevent people from writing stuff
612 /// that can never possibly work), and to prevent the pattern permuter from
613 /// generating stuff that is useless.
614 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
615 if (isLeaf()) return true;
617 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
618 if (!getChild(i)->canPatternMatch(Reason, ISE))
621 // If this node is a commutative operator, check that the LHS isn't an
623 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
624 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
625 // Scan all of the operands of the node and make sure that only the last one
626 // is a constant node.
627 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
628 if (!getChild(i)->isLeaf() &&
629 getChild(i)->getOperator()->getName() == "imm") {
630 Reason = "Immediate value must be on the RHS of commutative operators!";
638 //===----------------------------------------------------------------------===//
639 // TreePattern implementation
642 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
643 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
644 isInputPattern = isInput;
645 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
646 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
649 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
650 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
651 isInputPattern = isInput;
652 Trees.push_back(ParseTreePattern(Pat));
655 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
656 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
657 isInputPattern = isInput;
658 Trees.push_back(Pat);
663 void TreePattern::error(const std::string &Msg) const {
665 throw "In " + TheRecord->getName() + ": " + Msg;
668 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
669 Record *Operator = Dag->getNodeType();
671 if (Operator->isSubClassOf("ValueType")) {
672 // If the operator is a ValueType, then this must be "type cast" of a leaf
674 if (Dag->getNumArgs() != 1)
675 error("Type cast only takes one operand!");
677 Init *Arg = Dag->getArg(0);
678 TreePatternNode *New;
679 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
680 Record *R = DI->getDef();
681 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
682 Dag->setArg(0, new DagInit(R,
683 std::vector<std::pair<Init*, std::string> >()));
684 return ParseTreePattern(Dag);
686 New = new TreePatternNode(DI);
687 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
688 New = ParseTreePattern(DI);
689 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
690 New = new TreePatternNode(II);
691 if (!Dag->getArgName(0).empty())
692 error("Constant int argument should not have a name!");
695 error("Unknown leaf value for tree pattern!");
699 // Apply the type cast.
700 New->UpdateNodeType(getValueType(Operator), *this);
701 New->setName(Dag->getArgName(0));
705 // Verify that this is something that makes sense for an operator.
706 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
707 !Operator->isSubClassOf("Instruction") &&
708 !Operator->isSubClassOf("SDNodeXForm") &&
709 Operator->getName() != "set")
710 error("Unrecognized node '" + Operator->getName() + "'!");
712 // Check to see if this is something that is illegal in an input pattern.
713 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
714 Operator->isSubClassOf("SDNodeXForm")))
715 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
717 std::vector<TreePatternNode*> Children;
719 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
720 Init *Arg = Dag->getArg(i);
721 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
722 Children.push_back(ParseTreePattern(DI));
723 if (Children.back()->getName().empty())
724 Children.back()->setName(Dag->getArgName(i));
725 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
726 Record *R = DefI->getDef();
727 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
728 // TreePatternNode if its own.
729 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
730 Dag->setArg(i, new DagInit(R,
731 std::vector<std::pair<Init*, std::string> >()));
732 --i; // Revisit this node...
734 TreePatternNode *Node = new TreePatternNode(DefI);
735 Node->setName(Dag->getArgName(i));
736 Children.push_back(Node);
739 if (R->getName() == "node") {
740 if (Dag->getArgName(i).empty())
741 error("'node' argument requires a name to match with operand list");
742 Args.push_back(Dag->getArgName(i));
745 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
746 TreePatternNode *Node = new TreePatternNode(II);
747 if (!Dag->getArgName(i).empty())
748 error("Constant int argument should not have a name!");
749 Children.push_back(Node);
754 error("Unknown leaf value for tree pattern!");
758 return new TreePatternNode(Operator, Children);
761 /// InferAllTypes - Infer/propagate as many types throughout the expression
762 /// patterns as possible. Return true if all types are infered, false
763 /// otherwise. Throw an exception if a type contradiction is found.
764 bool TreePattern::InferAllTypes() {
765 bool MadeChange = true;
768 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
769 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
772 bool HasUnresolvedTypes = false;
773 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
774 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
775 return !HasUnresolvedTypes;
778 void TreePattern::print(std::ostream &OS) const {
779 OS << getRecord()->getName();
781 OS << "(" << Args[0];
782 for (unsigned i = 1, e = Args.size(); i != e; ++i)
783 OS << ", " << Args[i];
788 if (Trees.size() > 1)
790 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
796 if (Trees.size() > 1)
800 void TreePattern::dump() const { print(std::cerr); }
804 //===----------------------------------------------------------------------===//
805 // DAGISelEmitter implementation
808 // Parse all of the SDNode definitions for the target, populating SDNodes.
809 void DAGISelEmitter::ParseNodeInfo() {
810 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
811 while (!Nodes.empty()) {
812 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
817 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
818 /// map, and emit them to the file as functions.
819 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
820 OS << "\n// Node transformations.\n";
821 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
822 while (!Xforms.empty()) {
823 Record *XFormNode = Xforms.back();
824 Record *SDNode = XFormNode->getValueAsDef("Opcode");
825 std::string Code = XFormNode->getValueAsCode("XFormFunction");
826 SDNodeXForms.insert(std::make_pair(XFormNode,
827 std::make_pair(SDNode, Code)));
830 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
831 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
833 OS << "inline SDOperand Transform_" << XFormNode->getName()
834 << "(SDNode *" << C2 << ") {\n";
835 if (ClassName != "SDNode")
836 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
837 OS << Code << "\n}\n";
844 void DAGISelEmitter::ParseComplexPatterns() {
845 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
846 while (!AMs.empty()) {
847 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
853 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
854 /// file, building up the PatternFragments map. After we've collected them all,
855 /// inline fragments together as necessary, so that there are no references left
856 /// inside a pattern fragment to a pattern fragment.
858 /// This also emits all of the predicate functions to the output file.
860 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
861 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
863 // First step, parse all of the fragments and emit predicate functions.
864 OS << "\n// Predicate functions.\n";
865 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
866 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
867 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
868 PatternFragments[Fragments[i]] = P;
870 // Validate the argument list, converting it to map, to discard duplicates.
871 std::vector<std::string> &Args = P->getArgList();
872 std::set<std::string> OperandsMap(Args.begin(), Args.end());
874 if (OperandsMap.count(""))
875 P->error("Cannot have unnamed 'node' values in pattern fragment!");
877 // Parse the operands list.
878 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
879 if (OpsList->getNodeType()->getName() != "ops")
880 P->error("Operands list should start with '(ops ... '!");
882 // Copy over the arguments.
884 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
885 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
886 static_cast<DefInit*>(OpsList->getArg(j))->
887 getDef()->getName() != "node")
888 P->error("Operands list should all be 'node' values.");
889 if (OpsList->getArgName(j).empty())
890 P->error("Operands list should have names for each operand!");
891 if (!OperandsMap.count(OpsList->getArgName(j)))
892 P->error("'" + OpsList->getArgName(j) +
893 "' does not occur in pattern or was multiply specified!");
894 OperandsMap.erase(OpsList->getArgName(j));
895 Args.push_back(OpsList->getArgName(j));
898 if (!OperandsMap.empty())
899 P->error("Operands list does not contain an entry for operand '" +
900 *OperandsMap.begin() + "'!");
902 // If there is a code init for this fragment, emit the predicate code and
903 // keep track of the fact that this fragment uses it.
904 std::string Code = Fragments[i]->getValueAsCode("Predicate");
906 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
907 std::string ClassName =
908 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
909 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
911 OS << "inline bool Predicate_" << Fragments[i]->getName()
912 << "(SDNode *" << C2 << ") {\n";
913 if (ClassName != "SDNode")
914 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
915 OS << Code << "\n}\n";
916 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
919 // If there is a node transformation corresponding to this, keep track of
921 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
922 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
923 P->getOnlyTree()->setTransformFn(Transform);
928 // Now that we've parsed all of the tree fragments, do a closure on them so
929 // that there are not references to PatFrags left inside of them.
930 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
931 E = PatternFragments.end(); I != E; ++I) {
932 TreePattern *ThePat = I->second;
933 ThePat->InlinePatternFragments();
935 // Infer as many types as possible. Don't worry about it if we don't infer
936 // all of them, some may depend on the inputs of the pattern.
938 ThePat->InferAllTypes();
940 // If this pattern fragment is not supported by this target (no types can
941 // satisfy its constraints), just ignore it. If the bogus pattern is
942 // actually used by instructions, the type consistency error will be
946 // If debugging, print out the pattern fragment result.
947 DEBUG(ThePat->dump());
951 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
952 /// instruction input. Return true if this is a real use.
953 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
954 std::map<std::string, TreePatternNode*> &InstInputs) {
955 // No name -> not interesting.
956 if (Pat->getName().empty()) {
958 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
959 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
960 I->error("Input " + DI->getDef()->getName() + " must be named!");
968 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
969 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
972 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
973 Rec = Pat->getOperator();
976 TreePatternNode *&Slot = InstInputs[Pat->getName()];
981 if (Slot->isLeaf()) {
982 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
984 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
985 SlotRec = Slot->getOperator();
988 // Ensure that the inputs agree if we've already seen this input.
990 I->error("All $" + Pat->getName() + " inputs must agree with each other");
991 if (Slot->getExtType() != Pat->getExtType())
992 I->error("All $" + Pat->getName() + " inputs must agree with each other");
997 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
998 /// part of "I", the instruction), computing the set of inputs and outputs of
999 /// the pattern. Report errors if we see anything naughty.
1000 void DAGISelEmitter::
1001 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1002 std::map<std::string, TreePatternNode*> &InstInputs,
1003 std::map<std::string, Record*> &InstResults) {
1004 if (Pat->isLeaf()) {
1005 bool isUse = HandleUse(I, Pat, InstInputs);
1006 if (!isUse && Pat->getTransformFn())
1007 I->error("Cannot specify a transform function for a non-input value!");
1009 } else if (Pat->getOperator()->getName() != "set") {
1010 // If this is not a set, verify that the children nodes are not void typed,
1012 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1013 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
1014 I->error("Cannot have void nodes inside of patterns!");
1015 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
1018 // If this is a non-leaf node with no children, treat it basically as if
1019 // it were a leaf. This handles nodes like (imm).
1021 if (Pat->getNumChildren() == 0)
1022 isUse = HandleUse(I, Pat, InstInputs);
1024 if (!isUse && Pat->getTransformFn())
1025 I->error("Cannot specify a transform function for a non-input value!");
1029 // Otherwise, this is a set, validate and collect instruction results.
1030 if (Pat->getNumChildren() == 0)
1031 I->error("set requires operands!");
1032 else if (Pat->getNumChildren() & 1)
1033 I->error("set requires an even number of operands");
1035 if (Pat->getTransformFn())
1036 I->error("Cannot specify a transform function on a set node!");
1038 // Check the set destinations.
1039 unsigned NumValues = Pat->getNumChildren()/2;
1040 for (unsigned i = 0; i != NumValues; ++i) {
1041 TreePatternNode *Dest = Pat->getChild(i);
1042 if (!Dest->isLeaf())
1043 I->error("set destination should be a register!");
1045 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1047 I->error("set destination should be a register!");
1049 if (!Val->getDef()->isSubClassOf("RegisterClass") &&
1050 !Val->getDef()->isSubClassOf("Register"))
1051 I->error("set destination should be a register!");
1052 if (Dest->getName().empty())
1053 I->error("set destination must have a name!");
1054 if (InstResults.count(Dest->getName()))
1055 I->error("cannot set '" + Dest->getName() +"' multiple times");
1056 InstResults[Dest->getName()] = Val->getDef();
1058 // Verify and collect info from the computation.
1059 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1060 InstInputs, InstResults);
1064 /// NodeHasChain - return true if TreePatternNode has the property
1065 /// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1067 static bool NodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1069 if (N->isLeaf()) return false;
1070 Record *Operator = N->getOperator();
1071 if (!Operator->isSubClassOf("SDNode")) return false;
1073 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1074 return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1077 static bool PatternHasCtrlDep(TreePatternNode *N, DAGISelEmitter &ISE)
1079 if (NodeHasChain(N, ISE))
1082 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1083 TreePatternNode *Child = N->getChild(i);
1084 if (PatternHasCtrlDep(Child, ISE))
1093 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1094 /// any fragments involved. This populates the Instructions list with fully
1095 /// resolved instructions.
1096 void DAGISelEmitter::ParseInstructions() {
1097 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1099 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1102 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1103 LI = Instrs[i]->getValueAsListInit("Pattern");
1105 // If there is no pattern, only collect minimal information about the
1106 // instruction for its operand list. We have to assume that there is one
1107 // result, as we have no detailed info.
1108 if (!LI || LI->getSize() == 0) {
1109 std::vector<Record*> Results;
1110 std::vector<Record*> Operands;
1112 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1114 // Doesn't even define a result?
1115 if (InstInfo.OperandList.size() == 0)
1118 // FIXME: temporary hack...
1119 if (InstInfo.isReturn || InstInfo.isBranch || InstInfo.isCall ||
1121 // These produce no results
1122 for (unsigned j = 0, e = InstInfo.OperandList.size(); j != e; ++j)
1123 Operands.push_back(InstInfo.OperandList[j].Rec);
1125 // Assume the first operand is the result.
1126 Results.push_back(InstInfo.OperandList[0].Rec);
1128 // The rest are inputs.
1129 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1130 Operands.push_back(InstInfo.OperandList[j].Rec);
1133 // Create and insert the instruction.
1134 Instructions.insert(std::make_pair(Instrs[i],
1135 DAGInstruction(0, Results, Operands)));
1136 continue; // no pattern.
1139 // Parse the instruction.
1140 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1141 // Inline pattern fragments into it.
1142 I->InlinePatternFragments();
1144 // Infer as many types as possible. If we cannot infer all of them, we can
1145 // never do anything with this instruction pattern: report it to the user.
1146 if (!I->InferAllTypes())
1147 I->error("Could not infer all types in pattern!");
1149 // InstInputs - Keep track of all of the inputs of the instruction, along
1150 // with the record they are declared as.
1151 std::map<std::string, TreePatternNode*> InstInputs;
1153 // InstResults - Keep track of all the virtual registers that are 'set'
1154 // in the instruction, including what reg class they are.
1155 std::map<std::string, Record*> InstResults;
1157 // Verify that the top-level forms in the instruction are of void type, and
1158 // fill in the InstResults map.
1159 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1160 TreePatternNode *Pat = I->getTree(j);
1161 if (Pat->getExtType() != MVT::isVoid)
1162 I->error("Top-level forms in instruction pattern should have"
1165 // Find inputs and outputs, and verify the structure of the uses/defs.
1166 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
1169 // Now that we have inputs and outputs of the pattern, inspect the operands
1170 // list for the instruction. This determines the order that operands are
1171 // added to the machine instruction the node corresponds to.
1172 unsigned NumResults = InstResults.size();
1174 // Parse the operands list from the (ops) list, validating it.
1175 std::vector<std::string> &Args = I->getArgList();
1176 assert(Args.empty() && "Args list should still be empty here!");
1177 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1179 // Check that all of the results occur first in the list.
1180 std::vector<Record*> Results;
1181 for (unsigned i = 0; i != NumResults; ++i) {
1182 if (i == CGI.OperandList.size())
1183 I->error("'" + InstResults.begin()->first +
1184 "' set but does not appear in operand list!");
1185 const std::string &OpName = CGI.OperandList[i].Name;
1187 // Check that it exists in InstResults.
1188 Record *R = InstResults[OpName];
1190 I->error("Operand $" + OpName + " should be a set destination: all "
1191 "outputs must occur before inputs in operand list!");
1193 if (CGI.OperandList[i].Rec != R)
1194 I->error("Operand $" + OpName + " class mismatch!");
1196 // Remember the return type.
1197 Results.push_back(CGI.OperandList[i].Rec);
1199 // Okay, this one checks out.
1200 InstResults.erase(OpName);
1203 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1204 // the copy while we're checking the inputs.
1205 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1207 std::vector<TreePatternNode*> ResultNodeOperands;
1208 std::vector<Record*> Operands;
1209 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1210 const std::string &OpName = CGI.OperandList[i].Name;
1212 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1214 if (!InstInputsCheck.count(OpName))
1215 I->error("Operand $" + OpName +
1216 " does not appear in the instruction pattern");
1217 TreePatternNode *InVal = InstInputsCheck[OpName];
1218 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1220 if (InVal->isLeaf() &&
1221 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1222 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1223 if (CGI.OperandList[i].Rec != InRec &&
1224 !InRec->isSubClassOf("ComplexPattern"))
1225 I->error("Operand $" + OpName +
1226 "'s register class disagrees between the operand and pattern");
1228 Operands.push_back(CGI.OperandList[i].Rec);
1230 // Construct the result for the dest-pattern operand list.
1231 TreePatternNode *OpNode = InVal->clone();
1233 // No predicate is useful on the result.
1234 OpNode->setPredicateFn("");
1236 // Promote the xform function to be an explicit node if set.
1237 if (Record *Xform = OpNode->getTransformFn()) {
1238 OpNode->setTransformFn(0);
1239 std::vector<TreePatternNode*> Children;
1240 Children.push_back(OpNode);
1241 OpNode = new TreePatternNode(Xform, Children);
1244 ResultNodeOperands.push_back(OpNode);
1247 if (!InstInputsCheck.empty())
1248 I->error("Input operand $" + InstInputsCheck.begin()->first +
1249 " occurs in pattern but not in operands list!");
1251 TreePatternNode *ResultPattern =
1252 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1254 // Create and insert the instruction.
1255 DAGInstruction TheInst(I, Results, Operands);
1256 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1258 // Use a temporary tree pattern to infer all types and make sure that the
1259 // constructed result is correct. This depends on the instruction already
1260 // being inserted into the Instructions map.
1261 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1262 Temp.InferAllTypes();
1264 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1265 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1270 // If we can, convert the instructions to be patterns that are matched!
1271 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1272 E = Instructions.end(); II != E; ++II) {
1273 DAGInstruction &TheInst = II->second;
1274 TreePattern *I = TheInst.getPattern();
1275 if (I == 0) continue; // No pattern.
1277 if (I->getNumTrees() != 1) {
1278 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1281 TreePatternNode *Pattern = I->getTree(0);
1282 TreePatternNode *SrcPattern;
1283 if (TheInst.getNumResults() == 0) {
1284 SrcPattern = Pattern;
1286 if (Pattern->getOperator()->getName() != "set")
1287 continue; // Not a set (store or something?)
1289 if (Pattern->getNumChildren() != 2)
1290 continue; // Not a set of a single value (not handled so far)
1292 SrcPattern = Pattern->getChild(1)->clone();
1296 if (!SrcPattern->canPatternMatch(Reason, *this))
1297 I->error("Instruction can never match: " + Reason);
1299 TreePatternNode *DstPattern = TheInst.getResultPattern();
1300 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
1302 if (PatternHasCtrlDep(Pattern, *this)) {
1303 Record *Instr = II->first;
1304 CodeGenInstruction &InstInfo = Target.getInstruction(Instr->getName());
1305 InstInfo.hasCtrlDep = true;
1310 void DAGISelEmitter::ParsePatterns() {
1311 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1313 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1314 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1315 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1317 // Inline pattern fragments into it.
1318 Pattern->InlinePatternFragments();
1320 // Infer as many types as possible. If we cannot infer all of them, we can
1321 // never do anything with this pattern: report it to the user.
1322 if (!Pattern->InferAllTypes())
1323 Pattern->error("Could not infer all types in pattern!");
1325 // Validate that the input pattern is correct.
1327 std::map<std::string, TreePatternNode*> InstInputs;
1328 std::map<std::string, Record*> InstResults;
1329 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1330 InstInputs, InstResults);
1333 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1334 if (LI->getSize() == 0) continue; // no pattern.
1336 // Parse the instruction.
1337 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1339 // Inline pattern fragments into it.
1340 Result->InlinePatternFragments();
1342 // Infer as many types as possible. If we cannot infer all of them, we can
1343 // never do anything with this pattern: report it to the user.
1344 if (!Result->InferAllTypes())
1345 Result->error("Could not infer all types in pattern result!");
1347 if (Result->getNumTrees() != 1)
1348 Result->error("Cannot handle instructions producing instructions "
1349 "with temporaries yet!");
1352 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1353 Pattern->error("Pattern can never match: " + Reason);
1355 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1356 Result->getOnlyTree()));
1360 /// CombineChildVariants - Given a bunch of permutations of each child of the
1361 /// 'operator' node, put them together in all possible ways.
1362 static void CombineChildVariants(TreePatternNode *Orig,
1363 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1364 std::vector<TreePatternNode*> &OutVariants,
1365 DAGISelEmitter &ISE) {
1366 // Make sure that each operand has at least one variant to choose from.
1367 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1368 if (ChildVariants[i].empty())
1371 // The end result is an all-pairs construction of the resultant pattern.
1372 std::vector<unsigned> Idxs;
1373 Idxs.resize(ChildVariants.size());
1374 bool NotDone = true;
1376 // Create the variant and add it to the output list.
1377 std::vector<TreePatternNode*> NewChildren;
1378 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1379 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1380 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1382 // Copy over properties.
1383 R->setName(Orig->getName());
1384 R->setPredicateFn(Orig->getPredicateFn());
1385 R->setTransformFn(Orig->getTransformFn());
1386 R->setType(Orig->getExtType());
1388 // If this pattern cannot every match, do not include it as a variant.
1389 std::string ErrString;
1390 if (!R->canPatternMatch(ErrString, ISE)) {
1393 bool AlreadyExists = false;
1395 // Scan to see if this pattern has already been emitted. We can get
1396 // duplication due to things like commuting:
1397 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1398 // which are the same pattern. Ignore the dups.
1399 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1400 if (R->isIsomorphicTo(OutVariants[i])) {
1401 AlreadyExists = true;
1408 OutVariants.push_back(R);
1411 // Increment indices to the next permutation.
1413 // Look for something we can increment without causing a wrap-around.
1414 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1415 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1416 NotDone = true; // Found something to increment.
1424 /// CombineChildVariants - A helper function for binary operators.
1426 static void CombineChildVariants(TreePatternNode *Orig,
1427 const std::vector<TreePatternNode*> &LHS,
1428 const std::vector<TreePatternNode*> &RHS,
1429 std::vector<TreePatternNode*> &OutVariants,
1430 DAGISelEmitter &ISE) {
1431 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1432 ChildVariants.push_back(LHS);
1433 ChildVariants.push_back(RHS);
1434 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1438 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1439 std::vector<TreePatternNode *> &Children) {
1440 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1441 Record *Operator = N->getOperator();
1443 // Only permit raw nodes.
1444 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1445 N->getTransformFn()) {
1446 Children.push_back(N);
1450 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1451 Children.push_back(N->getChild(0));
1453 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1455 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1456 Children.push_back(N->getChild(1));
1458 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1461 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1462 /// the (potentially recursive) pattern by using algebraic laws.
1464 static void GenerateVariantsOf(TreePatternNode *N,
1465 std::vector<TreePatternNode*> &OutVariants,
1466 DAGISelEmitter &ISE) {
1467 // We cannot permute leaves.
1469 OutVariants.push_back(N);
1473 // Look up interesting info about the node.
1474 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1476 // If this node is associative, reassociate.
1477 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1478 // Reassociate by pulling together all of the linked operators
1479 std::vector<TreePatternNode*> MaximalChildren;
1480 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1482 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1484 if (MaximalChildren.size() == 3) {
1485 // Find the variants of all of our maximal children.
1486 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1487 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1488 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1489 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1491 // There are only two ways we can permute the tree:
1492 // (A op B) op C and A op (B op C)
1493 // Within these forms, we can also permute A/B/C.
1495 // Generate legal pair permutations of A/B/C.
1496 std::vector<TreePatternNode*> ABVariants;
1497 std::vector<TreePatternNode*> BAVariants;
1498 std::vector<TreePatternNode*> ACVariants;
1499 std::vector<TreePatternNode*> CAVariants;
1500 std::vector<TreePatternNode*> BCVariants;
1501 std::vector<TreePatternNode*> CBVariants;
1502 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1503 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1504 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1505 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1506 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1507 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1509 // Combine those into the result: (x op x) op x
1510 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1511 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1512 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1513 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1514 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1515 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1517 // Combine those into the result: x op (x op x)
1518 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1519 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1520 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1521 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1522 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1523 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1528 // Compute permutations of all children.
1529 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1530 ChildVariants.resize(N->getNumChildren());
1531 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1532 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1534 // Build all permutations based on how the children were formed.
1535 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1537 // If this node is commutative, consider the commuted order.
1538 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1539 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1540 // Consider the commuted order.
1541 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1547 // GenerateVariants - Generate variants. For example, commutative patterns can
1548 // match multiple ways. Add them to PatternsToMatch as well.
1549 void DAGISelEmitter::GenerateVariants() {
1551 DEBUG(std::cerr << "Generating instruction variants.\n");
1553 // Loop over all of the patterns we've collected, checking to see if we can
1554 // generate variants of the instruction, through the exploitation of
1555 // identities. This permits the target to provide agressive matching without
1556 // the .td file having to contain tons of variants of instructions.
1558 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1559 // intentionally do not reconsider these. Any variants of added patterns have
1560 // already been added.
1562 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1563 std::vector<TreePatternNode*> Variants;
1564 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1566 assert(!Variants.empty() && "Must create at least original variant!");
1567 Variants.erase(Variants.begin()); // Remove the original pattern.
1569 if (Variants.empty()) // No variants for this pattern.
1572 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1573 PatternsToMatch[i].first->dump();
1576 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1577 TreePatternNode *Variant = Variants[v];
1579 DEBUG(std::cerr << " VAR#" << v << ": ";
1583 // Scan to see if an instruction or explicit pattern already matches this.
1584 bool AlreadyExists = false;
1585 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1586 // Check to see if this variant already exists.
1587 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1588 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1589 AlreadyExists = true;
1593 // If we already have it, ignore the variant.
1594 if (AlreadyExists) continue;
1596 // Otherwise, add it to the list of patterns we have.
1597 PatternsToMatch.push_back(std::make_pair(Variant,
1598 PatternsToMatch[i].second));
1601 DEBUG(std::cerr << "\n");
1606 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1608 static bool NodeIsComplexPattern(TreePatternNode *N)
1610 return (N->isLeaf() &&
1611 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1612 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1613 isSubClassOf("ComplexPattern"));
1616 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1617 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1618 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1619 DAGISelEmitter &ISE)
1622 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1623 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1624 isSubClassOf("ComplexPattern")) {
1625 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1631 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1632 /// patterns before small ones. This is used to determine the size of a
1634 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1635 assert(isExtIntegerVT(P->getExtType()) ||
1636 isExtFloatingPointVT(P->getExtType()) ||
1637 P->getExtType() == MVT::isVoid && "Not a valid pattern node to size!");
1638 unsigned Size = 1; // The node itself.
1640 // FIXME: This is a hack to statically increase the priority of patterns
1641 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1642 // Later we can allow complexity / cost for each pattern to be (optionally)
1643 // specified. To get best possible pattern match we'll need to dynamically
1644 // calculate the complexity of all patterns a dag can potentially map to.
1645 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1647 Size += AM->getNumOperands();
1649 // Count children in the count if they are also nodes.
1650 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1651 TreePatternNode *Child = P->getChild(i);
1652 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
1653 Size += getPatternSize(Child, ISE);
1654 else if (Child->isLeaf()) {
1655 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1656 ++Size; // Matches a ConstantSDNode.
1657 else if (NodeIsComplexPattern(Child))
1658 Size += getPatternSize(Child, ISE);
1665 /// getResultPatternCost - Compute the number of instructions for this pattern.
1666 /// This is a temporary hack. We should really include the instruction
1667 /// latencies in this calculation.
1668 static unsigned getResultPatternCost(TreePatternNode *P) {
1669 if (P->isLeaf()) return 0;
1671 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1672 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1673 Cost += getResultPatternCost(P->getChild(i));
1677 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1678 // In particular, we want to match maximal patterns first and lowest cost within
1679 // a particular complexity first.
1680 struct PatternSortingPredicate {
1681 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1682 DAGISelEmitter &ISE;
1684 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1685 DAGISelEmitter::PatternToMatch *RHS) {
1686 unsigned LHSSize = getPatternSize(LHS->first, ISE);
1687 unsigned RHSSize = getPatternSize(RHS->first, ISE);
1688 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1689 if (LHSSize < RHSSize) return false;
1691 // If the patterns have equal complexity, compare generated instruction cost
1692 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1696 /// getRegisterValueType - Look up and return the first ValueType of specified
1697 /// RegisterClass record
1698 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1699 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1700 return RC->getValueTypeNum(0);
1705 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1706 /// type information from it.
1707 static void RemoveAllTypes(TreePatternNode *N) {
1708 N->setType(MVT::isUnknown);
1710 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1711 RemoveAllTypes(N->getChild(i));
1714 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1715 Record *N = Records.getDef(Name);
1716 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1720 class PatternCodeEmitter {
1722 DAGISelEmitter &ISE;
1724 // LHS of the pattern being matched
1725 TreePatternNode *LHS;
1728 // Node to name mapping
1729 std::map<std::string,std::string> VariableMap;
1730 // Names of all the folded nodes which produce chains.
1731 std::vector<std::string> FoldedChains;
1737 PatternCodeEmitter(DAGISelEmitter &ise, TreePatternNode *lhs,
1738 unsigned PatNum, std::ostream &os) :
1739 ISE(ise), LHS(lhs), PatternNo(PatNum), OS(os),
1740 FoundChain(false), InFlag(false), TmpNo(0) {};
1742 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1743 /// if the match fails. At this point, we already know that the opcode for N
1744 /// matches, and the SDNode for the result has the RootName specified name.
1745 void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
1746 bool isRoot = false) {
1748 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1749 OS << " if (cast<ConstantSDNode>(" << RootName
1750 << ")->getSignExtended() != " << II->getValue() << ")\n"
1751 << " goto P" << PatternNo << "Fail;\n";
1753 } else if (!NodeIsComplexPattern(N)) {
1754 assert(0 && "Cannot match this as a leaf value!");
1759 // If this node has a name associated with it, capture it in VariableMap. If
1760 // we already saw this in the pattern, emit code to verify dagness.
1761 if (!N->getName().empty()) {
1762 std::string &VarMapEntry = VariableMap[N->getName()];
1763 if (VarMapEntry.empty()) {
1764 VarMapEntry = RootName;
1766 // If we get here, this is a second reference to a specific name. Since
1767 // we already have checked that the first reference is valid, we don't
1768 // have to recursively match it, just check that it's the same as the
1769 // previously named thing.
1770 OS << " if (" << VarMapEntry << " != " << RootName
1771 << ") goto P" << PatternNo << "Fail;\n";
1777 // Emit code to load the child nodes and match their contents recursively.
1779 bool HasChain = NodeHasChain(N, ISE);
1783 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
1784 OS << " if (!" << RootName << ".hasOneUse()) goto P"
1785 << PatternNo << "Fail; // Multiple uses of actual result?\n";
1786 OS << " if (CodeGenMap.count(" << RootName
1787 << ".getValue(" << CInfo.getNumResults() << "))) goto P"
1788 << PatternNo << "Fail; // Already selected for a chain use?\n";
1792 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1793 OS << " SDOperand " << RootName << OpNo <<" = " << RootName
1794 << ".getOperand(" << OpNo << ");\n";
1795 TreePatternNode *Child = N->getChild(i);
1797 if (!Child->isLeaf()) {
1798 // If it's not a leaf, recursively match.
1799 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1800 OS << " if (" << RootName << OpNo << ".getOpcode() != "
1801 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1802 EmitMatchCode(Child, RootName + utostr(OpNo));
1803 if (NodeHasChain(Child, ISE))
1804 FoldedChains.push_back(RootName + utostr(OpNo));
1806 // If this child has a name associated with it, capture it in VarMap. If
1807 // we already saw this in the pattern, emit code to verify dagness.
1808 if (!Child->getName().empty()) {
1809 std::string &VarMapEntry = VariableMap[Child->getName()];
1810 if (VarMapEntry.empty()) {
1811 VarMapEntry = RootName + utostr(OpNo);
1813 // If we get here, this is a second reference to a specific name. Since
1814 // we already have checked that the first reference is valid, we don't
1815 // have to recursively match it, just check that it's the same as the
1816 // previously named thing.
1817 OS << " if (" << VarMapEntry << " != " << RootName << OpNo
1818 << ") goto P" << PatternNo << "Fail;\n";
1823 // Handle leaves of various types.
1824 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1825 Record *LeafRec = DI->getDef();
1826 if (LeafRec->isSubClassOf("RegisterClass")) {
1827 // Handle register references. Nothing to do here.
1828 } else if (LeafRec->isSubClassOf("Register")) {
1830 OS << " SDOperand InFlag = SDOperand(0,0);\n";
1833 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1834 // Handle complex pattern. Nothing to do here.
1835 } else if (LeafRec->isSubClassOf("ValueType")) {
1836 // Make sure this is the specified value type.
1837 OS << " if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
1838 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1840 } else if (LeafRec->isSubClassOf("CondCode")) {
1841 // Make sure this is the specified cond code.
1842 OS << " if (cast<CondCodeSDNode>(" << RootName << OpNo
1843 << ")->get() != " << "ISD::" << LeafRec->getName()
1844 << ") goto P" << PatternNo << "Fail;\n";
1847 assert(0 && "Unknown leaf type!");
1849 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1850 OS << " if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1851 << " cast<ConstantSDNode>(" << RootName << OpNo
1852 << ")->getSignExtended() != " << II->getValue() << ")\n"
1853 << " goto P" << PatternNo << "Fail;\n";
1856 assert(0 && "Unknown leaf type!");
1863 OS << " SDOperand Chain = " << RootName << ".getOperand(0);\n";
1868 // If there is a node predicate for this, emit the call.
1869 if (!N->getPredicateFn().empty())
1870 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1871 << ".Val)) goto P" << PatternNo << "Fail;\n";
1874 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
1875 /// we actually have to build a DAG!
1876 std::pair<unsigned, unsigned>
1877 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
1878 // This is something selected from the pattern we matched.
1879 if (!N->getName().empty()) {
1880 assert(!isRoot && "Root of pattern cannot be a leaf!");
1881 std::string &Val = VariableMap[N->getName()];
1882 assert(!Val.empty() &&
1883 "Variable referenced but not defined and not caught earlier!");
1884 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1885 // Already selected this operand, just return the tmpval.
1886 return std::make_pair(1, atoi(Val.c_str()+3));
1889 const ComplexPattern *CP;
1890 unsigned ResNo = TmpNo++;
1891 unsigned NumRes = 1;
1892 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1893 switch (N->getType()) {
1894 default: assert(0 && "Unknown type for constant node!");
1895 case MVT::i1: OS << " bool Tmp"; break;
1896 case MVT::i8: OS << " unsigned char Tmp"; break;
1897 case MVT::i16: OS << " unsigned short Tmp"; break;
1898 case MVT::i32: OS << " unsigned Tmp"; break;
1899 case MVT::i64: OS << " uint64_t Tmp"; break;
1901 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1902 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1903 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1904 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1905 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
1906 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
1907 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
1908 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
1909 std::string Fn = CP->getSelectFunc();
1910 NumRes = CP->getNumOperands();
1911 OS << " SDOperand ";
1912 for (unsigned i = 0; i < NumRes; i++) {
1913 if (i != 0) OS << ", ";
1914 OS << "Tmp" << i + ResNo;
1917 OS << " if (!" << Fn << "(" << Val;
1918 for (unsigned i = 0; i < NumRes; i++)
1919 OS << " , Tmp" << i + ResNo;
1920 OS << ")) goto P" << PatternNo << "Fail;\n";
1921 TmpNo = ResNo + NumRes;
1923 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1925 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1926 // value if used multiple times by this pattern result.
1927 Val = "Tmp"+utostr(ResNo);
1928 return std::make_pair(NumRes, ResNo);
1932 // If this is an explicit register reference, handle it.
1933 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1934 unsigned ResNo = TmpNo++;
1935 if (DI->getDef()->isSubClassOf("Register")) {
1936 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1937 << ISE.getQualifiedName(DI->getDef()) << ", MVT::"
1938 << getEnumName(N->getType())
1940 return std::make_pair(1, ResNo);
1942 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1943 unsigned ResNo = TmpNo++;
1944 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1945 << II->getValue() << ", MVT::"
1946 << getEnumName(N->getType())
1948 return std::make_pair(1, ResNo);
1952 assert(0 && "Unknown leaf type!");
1953 return std::make_pair(1, ~0U);
1956 Record *Op = N->getOperator();
1957 if (Op->isSubClassOf("Instruction")) {
1958 // Determine operand emission order. Complex pattern first.
1959 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
1960 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
1961 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1962 TreePatternNode *Child = N->getChild(i);
1964 EmitOrder.push_back(std::make_pair(i, Child));
1965 OI = EmitOrder.begin();
1966 } else if (NodeIsComplexPattern(Child)) {
1967 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
1969 EmitOrder.push_back(std::make_pair(i, Child));
1973 // Emit all of the operands.
1974 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
1975 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
1976 unsigned OpOrder = EmitOrder[i].first;
1977 TreePatternNode *Child = EmitOrder[i].second;
1978 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
1979 NumTemps[OpOrder] = NumTemp;
1982 // List all the operands in the right order.
1983 std::vector<unsigned> Ops;
1984 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
1985 for (unsigned j = 0; j < NumTemps[i].first; j++)
1986 Ops.push_back(NumTemps[i].second + j);
1989 CodeGenInstruction &II =
1990 ISE.getTargetInfo().getInstruction(Op->getName());
1992 // Emit all the chain and CopyToReg stuff.
1994 OS << " Chain = Select(Chain);\n";
1995 EmitCopyToRegs(LHS, "N", II.hasCtrlDep);
1997 const DAGInstruction &Inst = ISE.getInstruction(Op);
1998 unsigned NumResults = Inst.getNumResults();
1999 unsigned ResNo = TmpNo++;
2001 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
2002 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
2003 << getEnumName(N->getType());
2004 unsigned LastOp = 0;
2005 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2007 OS << ", Tmp" << LastOp;
2010 if (II.hasCtrlDep) {
2011 // Must have at least one result
2012 OS << " Chain = Tmp" << LastOp << ".getValue("
2013 << NumResults << ");\n";
2015 } else if (II.hasCtrlDep) {
2016 OS << " SDOperand Result = ";
2017 OS << "CurDAG->getTargetNode("
2018 << II.Namespace << "::" << II.TheDef->getName();
2020 OS << ", MVT::" << getEnumName(N->getType()); // TODO: multiple results?
2021 OS << ", MVT::Other";
2022 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2023 OS << ", Tmp" << Ops[i];
2028 if (NumResults != 0) {
2029 OS << " CodeGenMap[N] = Result;\n";
2032 if (NodeHasChain(LHS, ISE))
2033 OS << "= CodeGenMap[N.getValue(" << NumResults << ")] ";
2034 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2035 OS << "= CodeGenMap[" << FoldedChains[j] << ".getValue("
2036 << NumResults << ")] ";
2037 OS << "= Result.getValue(" << NumResults << ");\n";
2038 if (NumResults == 0)
2039 OS << " return Chain;\n";
2041 OS << " return (N.ResNo) ? Chain : Result.getValue(0);\n";
2043 // If this instruction is the root, and if there is only one use of it,
2044 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2045 OS << " if (N.Val->hasOneUse()) {\n";
2046 OS << " return CurDAG->SelectNodeTo(N.Val, "
2047 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
2048 << getEnumName(N->getType());
2049 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2050 OS << ", Tmp" << Ops[i];
2054 OS << " } else {\n";
2055 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
2056 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
2057 << getEnumName(N->getType());
2058 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2059 OS << ", Tmp" << Ops[i];
2065 return std::make_pair(1, ResNo);
2066 } else if (Op->isSubClassOf("SDNodeXForm")) {
2067 assert(N->getNumChildren() == 1 && "node xform should have one child!");
2068 unsigned OpVal = EmitResultCode(N->getChild(0))
2071 unsigned ResNo = TmpNo++;
2072 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
2073 << "(Tmp" << OpVal << ".Val);\n";
2075 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
2076 OS << " return Tmp" << ResNo << ";\n";
2078 return std::make_pair(1, ResNo);
2081 assert(0 && "Unknown node in result pattern!");
2082 return std::make_pair(1, ~0U);
2086 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2087 /// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2088 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2089 /// for, this returns true otherwise false if Pat has all types.
2090 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2091 const std::string &Prefix) {
2093 if (!Pat->hasTypeSet()) {
2094 // Move a type over from 'other' to 'pat'.
2095 Pat->setType(Other->getType());
2096 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
2097 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
2101 unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
2102 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2103 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2104 Prefix + utostr(OpNo)))
2110 /// EmitCopyToRegs - Emit the flag operands for the DAG that is
2112 void EmitCopyToRegs(TreePatternNode *N, const std::string &RootName,
2114 const CodeGenTarget &T = ISE.getTargetInfo();
2115 unsigned OpNo = (unsigned) NodeHasChain(N, ISE);
2116 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2117 TreePatternNode *Child = N->getChild(i);
2118 if (!Child->isLeaf()) {
2119 EmitCopyToRegs(Child, RootName + utostr(OpNo), HasCtrlDep);
2121 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2122 Record *RR = DI->getDef();
2123 if (RR->isSubClassOf("Register")) {
2124 MVT::ValueType RVT = getRegisterValueType(RR, T);
2126 OS << " SDOperand " << RootName << "CR" << i << ";\n";
2127 OS << " " << RootName << "CR" << i
2128 << " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
2129 << ISE.getQualifiedName(RR) << ", MVT::"
2130 << getEnumName(RVT) << ")"
2131 << ", Select(" << RootName << OpNo << "), InFlag);\n";
2132 OS << " Chain = " << RootName << "CR" << i
2133 << ".getValue(0);\n";
2134 OS << " InFlag = " << RootName << "CR" << i
2135 << ".getValue(1);\n";
2137 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
2138 << ", CurDAG->getRegister(" << ISE.getQualifiedName(RR)
2139 << ", MVT::" << getEnumName(RVT) << ")"
2140 << ", Select(" << RootName << OpNo
2141 << "), InFlag).getValue(1);\n";
2150 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2151 /// stream to match the pattern, and generate the code for the match if it
2153 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2155 static unsigned PatternCount = 0;
2156 unsigned PatternNo = PatternCount++;
2157 OS << " { // Pattern #" << PatternNo << ": ";
2158 Pattern.first->print(OS);
2159 OS << "\n // Emits: ";
2160 Pattern.second->print(OS);
2162 OS << " // Pattern complexity = " << getPatternSize(Pattern.first, *this)
2163 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
2165 PatternCodeEmitter Emitter(*this, Pattern.first, PatternNo, OS);
2167 // Emit the matcher, capturing named arguments in VariableMap.
2168 Emitter.EmitMatchCode(Pattern.first, "N", true /*the root*/);
2170 // TP - Get *SOME* tree pattern, we don't care which.
2171 TreePattern &TP = *PatternFragments.begin()->second;
2173 // At this point, we know that we structurally match the pattern, but the
2174 // types of the nodes may not match. Figure out the fewest number of type
2175 // comparisons we need to emit. For example, if there is only one integer
2176 // type supported by a target, there should be no type comparisons at all for
2177 // integer patterns!
2179 // To figure out the fewest number of type checks needed, clone the pattern,
2180 // remove the types, then perform type inference on the pattern as a whole.
2181 // If there are unresolved types, emit an explicit check for those types,
2182 // apply the type to the tree, then rerun type inference. Iterate until all
2183 // types are resolved.
2185 TreePatternNode *Pat = Pattern.first->clone();
2186 RemoveAllTypes(Pat);
2189 // Resolve/propagate as many types as possible.
2191 bool MadeChange = true;
2193 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2195 assert(0 && "Error: could not find consistent types for something we"
2196 " already decided was ok!");
2200 // Insert a check for an unresolved type and add it to the tree. If we find
2201 // an unresolved type to add a check for, this returns true and we iterate,
2202 // otherwise we are done.
2203 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.first, "N"));
2205 Emitter.EmitResultCode(Pattern.second, true /*the root*/);
2209 OS << " }\n P" << PatternNo << "Fail:\n";
2214 /// CompareByRecordName - An ordering predicate that implements less-than by
2215 /// comparing the names records.
2216 struct CompareByRecordName {
2217 bool operator()(const Record *LHS, const Record *RHS) const {
2218 // Sort by name first.
2219 if (LHS->getName() < RHS->getName()) return true;
2220 // If both names are equal, sort by pointer.
2221 return LHS->getName() == RHS->getName() && LHS < RHS;
2226 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
2227 std::string InstNS = Target.inst_begin()->second.Namespace;
2228 if (!InstNS.empty()) InstNS += "::";
2230 // Emit boilerplate.
2231 OS << "// The main instruction selector code.\n"
2232 << "SDOperand SelectCode(SDOperand N) {\n"
2233 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
2234 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2235 << "INSTRUCTION_LIST_END))\n"
2236 << " return N; // Already selected.\n\n"
2237 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
2238 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
2239 << " switch (N.getOpcode()) {\n"
2240 << " default: break;\n"
2241 << " case ISD::EntryToken: // These leaves remain the same.\n"
2243 << " case ISD::AssertSext:\n"
2244 << " case ISD::AssertZext: {\n"
2245 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2246 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2247 << " return Tmp0;\n"
2249 << " case ISD::TokenFactor:\n"
2250 << " if (N.getNumOperands() == 2) {\n"
2251 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2252 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2253 << " return CodeGenMap[N] =\n"
2254 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2256 << " std::vector<SDOperand> Ops;\n"
2257 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2258 << " Ops.push_back(Select(N.getOperand(i)));\n"
2259 << " return CodeGenMap[N] = \n"
2260 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2262 << " case ISD::CopyFromReg: {\n"
2263 << " SDOperand Chain = Select(N.getOperand(0));\n"
2264 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2265 << " SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
2266 << " cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
2267 << " N.Val->getValueType(0));\n"
2268 << " return New.getValue(N.ResNo);\n"
2270 << " case ISD::CopyToReg: {\n"
2271 << " SDOperand Chain = Select(N.getOperand(0));\n"
2272 << " SDOperand Reg = N.getOperand(1);\n"
2273 << " SDOperand Val = Select(N.getOperand(2));\n"
2274 << " return CodeGenMap[N] = \n"
2275 << " CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
2276 << " Chain, Reg, Val);\n"
2279 // Group the patterns by their top-level opcodes.
2280 std::map<Record*, std::vector<PatternToMatch*>,
2281 CompareByRecordName> PatternsByOpcode;
2282 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2283 TreePatternNode *Node = PatternsToMatch[i].first;
2284 if (!Node->isLeaf()) {
2285 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2287 const ComplexPattern *CP;
2289 dynamic_cast<IntInit*>(Node->getLeafValue())) {
2290 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2291 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2292 std::vector<Record*> OpNodes = CP->getRootNodes();
2293 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2294 PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2295 &PatternsToMatch[i]);
2298 std::cerr << "Unrecognized opcode '";
2300 std::cerr << "' on tree pattern '";
2301 std::cerr << PatternsToMatch[i].second->getOperator()->getName();
2302 std::cerr << "'!\n";
2308 // Loop over all of the case statements.
2309 for (std::map<Record*, std::vector<PatternToMatch*>,
2310 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2311 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2312 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2313 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2315 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
2317 // We want to emit all of the matching code now. However, we want to emit
2318 // the matches in order of minimal cost. Sort the patterns so the least
2319 // cost one is at the start.
2320 std::stable_sort(Patterns.begin(), Patterns.end(),
2321 PatternSortingPredicate(*this));
2323 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2324 EmitCodeForPattern(*Patterns[i], OS);
2325 OS << " break;\n\n";
2329 OS << " } // end of big switch.\n\n"
2330 << " std::cerr << \"Cannot yet select: \";\n"
2331 << " N.Val->dump();\n"
2332 << " std::cerr << '\\n';\n"
2337 void DAGISelEmitter::run(std::ostream &OS) {
2338 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2341 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2342 << "// *** instruction selector class. These functions are really "
2345 OS << "// Instance var to keep track of multiply used nodes that have \n"
2346 << "// already been selected.\n"
2347 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2350 ParseNodeTransforms(OS);
2351 ParseComplexPatterns();
2352 ParsePatternFragments(OS);
2353 ParseInstructions();
2356 // Generate variants. For example, commutative patterns can match
2357 // multiple ways. Add them to PatternsToMatch as well.
2361 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2362 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2363 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
2364 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
2368 // At this point, we have full information about the 'Patterns' we need to
2369 // parse, both implicitly from instructions as well as from explicit pattern
2370 // definitions. Emit the resultant instruction selector.
2371 EmitInstructionSelector(OS);
2373 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2374 E = PatternFragments.end(); I != E; ++I)
2376 PatternFragments.clear();
2378 Instructions.clear();