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))) {
300 TP.error("Type inference contradiction found in node!");
302 TP.error("Type inference contradiction found in node " +
303 getOperator()->getName() + "!");
305 return true; // unreachable
309 void TreePatternNode::print(std::ostream &OS) const {
311 OS << *getLeafValue();
313 OS << "(" << getOperator()->getName();
316 switch (getExtType()) {
317 case MVT::Other: OS << ":Other"; break;
318 case MVT::isInt: OS << ":isInt"; break;
319 case MVT::isFP : OS << ":isFP"; break;
320 case MVT::isUnknown: ; /*OS << ":?";*/ break;
321 default: OS << ":" << getType(); break;
325 if (getNumChildren() != 0) {
327 getChild(0)->print(OS);
328 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
330 getChild(i)->print(OS);
336 if (!PredicateFn.empty())
337 OS << "<<P:" << PredicateFn << ">>";
339 OS << "<<X:" << TransformFn->getName() << ">>";
340 if (!getName().empty())
341 OS << ":$" << getName();
344 void TreePatternNode::dump() const {
348 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
349 /// the specified node. For this comparison, all of the state of the node
350 /// is considered, except for the assigned name. Nodes with differing names
351 /// that are otherwise identical are considered isomorphic.
352 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
353 if (N == this) return true;
354 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
355 getPredicateFn() != N->getPredicateFn() ||
356 getTransformFn() != N->getTransformFn())
360 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
361 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
362 return DI->getDef() == NDI->getDef();
363 return getLeafValue() == N->getLeafValue();
366 if (N->getOperator() != getOperator() ||
367 N->getNumChildren() != getNumChildren()) return false;
368 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
369 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
374 /// clone - Make a copy of this tree and all of its children.
376 TreePatternNode *TreePatternNode::clone() const {
377 TreePatternNode *New;
379 New = new TreePatternNode(getLeafValue());
381 std::vector<TreePatternNode*> CChildren;
382 CChildren.reserve(Children.size());
383 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
384 CChildren.push_back(getChild(i)->clone());
385 New = new TreePatternNode(getOperator(), CChildren);
387 New->setName(getName());
388 New->setType(getExtType());
389 New->setPredicateFn(getPredicateFn());
390 New->setTransformFn(getTransformFn());
394 /// SubstituteFormalArguments - Replace the formal arguments in this tree
395 /// with actual values specified by ArgMap.
396 void TreePatternNode::
397 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
398 if (isLeaf()) return;
400 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
401 TreePatternNode *Child = getChild(i);
402 if (Child->isLeaf()) {
403 Init *Val = Child->getLeafValue();
404 if (dynamic_cast<DefInit*>(Val) &&
405 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
406 // We found a use of a formal argument, replace it with its value.
407 Child = ArgMap[Child->getName()];
408 assert(Child && "Couldn't find formal argument!");
412 getChild(i)->SubstituteFormalArguments(ArgMap);
418 /// InlinePatternFragments - If this pattern refers to any pattern
419 /// fragments, inline them into place, giving us a pattern without any
420 /// PatFrag references.
421 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
422 if (isLeaf()) return this; // nothing to do.
423 Record *Op = getOperator();
425 if (!Op->isSubClassOf("PatFrag")) {
426 // Just recursively inline children nodes.
427 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
428 setChild(i, getChild(i)->InlinePatternFragments(TP));
432 // Otherwise, we found a reference to a fragment. First, look up its
433 // TreePattern record.
434 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
436 // Verify that we are passing the right number of operands.
437 if (Frag->getNumArgs() != Children.size())
438 TP.error("'" + Op->getName() + "' fragment requires " +
439 utostr(Frag->getNumArgs()) + " operands!");
441 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
443 // Resolve formal arguments to their actual value.
444 if (Frag->getNumArgs()) {
445 // Compute the map of formal to actual arguments.
446 std::map<std::string, TreePatternNode*> ArgMap;
447 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
448 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
450 FragTree->SubstituteFormalArguments(ArgMap);
453 FragTree->setName(getName());
454 FragTree->UpdateNodeType(getExtType(), TP);
456 // Get a new copy of this fragment to stitch into here.
457 //delete this; // FIXME: implement refcounting!
461 /// getIntrinsicType - Check to see if the specified record has an intrinsic
462 /// type which should be applied to it. This infer the type of register
463 /// references from the register file information, for example.
465 static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
467 // Check to see if this is a register or a register class...
468 if (R->isSubClassOf("RegisterClass")) {
469 if (NotRegisters) return MVT::isUnknown;
470 const CodeGenRegisterClass &RC =
471 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
472 return RC.getValueTypeNum(0);
473 } else if (R->isSubClassOf("PatFrag")) {
474 // Pattern fragment types will be resolved when they are inlined.
475 return MVT::isUnknown;
476 } else if (R->isSubClassOf("Register")) {
477 // If the register appears in exactly one regclass, and the regclass has one
478 // value type, use it as the known type.
479 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
480 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
481 if (RC->getNumValueTypes() == 1)
482 return RC->getValueTypeNum(0);
483 return MVT::isUnknown;
484 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
485 // Using a VTSDNode or CondCodeSDNode.
487 } else if (R->isSubClassOf("ComplexPattern")) {
488 return TP.getDAGISelEmitter().getComplexPattern(R).getValueType();
489 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
491 return MVT::isUnknown;
494 TP.error("Unknown node flavor used in pattern: " + R->getName());
498 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
499 /// this node and its children in the tree. This returns true if it makes a
500 /// change, false otherwise. If a type contradiction is found, throw an
502 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
504 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
505 // If it's a regclass or something else known, include the type.
506 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
508 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
509 // Int inits are always integers. :)
510 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
513 unsigned Size = MVT::getSizeInBits(getType());
514 // Make sure that the value is representable for this type.
516 int Val = (II->getValue() << (32-Size)) >> (32-Size);
517 if (Val != II->getValue())
518 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
519 "' is out of range for type 'MVT::" +
520 getEnumName(getType()) + "'!");
529 // special handling for set, which isn't really an SDNode.
530 if (getOperator()->getName() == "set") {
531 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
532 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
533 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
535 // Types of operands must match.
536 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
537 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
538 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
540 } else if (getOperator()->isSubClassOf("SDNode")) {
541 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
543 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
544 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
545 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
546 // Branch, etc. do not produce results and top-level forms in instr pattern
547 // must have void types.
548 if (NI.getNumResults() == 0)
549 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
551 } else if (getOperator()->isSubClassOf("Instruction")) {
552 const DAGInstruction &Inst =
553 TP.getDAGISelEmitter().getInstruction(getOperator());
554 bool MadeChange = false;
555 unsigned NumResults = Inst.getNumResults();
557 assert(NumResults <= 1 &&
558 "Only supports zero or one result instrs!");
559 // Apply the result type to the node
560 if (NumResults == 0) {
561 MadeChange = UpdateNodeType(MVT::isVoid, TP);
563 Record *ResultNode = Inst.getResult(0);
564 assert(ResultNode->isSubClassOf("RegisterClass") &&
565 "Operands should be register classes!");
567 const CodeGenRegisterClass &RC =
568 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
570 // Get the first ValueType in the RegClass, it's as good as any.
571 MadeChange = UpdateNodeType(RC.getValueTypeNum(0), TP);
574 if (getNumChildren() != Inst.getNumOperands())
575 TP.error("Instruction '" + getOperator()->getName() + " expects " +
576 utostr(Inst.getNumOperands()) + " operands, not " +
577 utostr(getNumChildren()) + " operands!");
578 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
579 Record *OperandNode = Inst.getOperand(i);
581 if (OperandNode->isSubClassOf("RegisterClass")) {
582 const CodeGenRegisterClass &RC =
583 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
584 VT = RC.getValueTypeNum(0);
585 } else if (OperandNode->isSubClassOf("Operand")) {
586 VT = getValueType(OperandNode->getValueAsDef("Type"));
588 assert(0 && "Unknown operand type!");
592 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
593 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
597 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
599 // Node transforms always take one operand, and take and return the same
601 if (getNumChildren() != 1)
602 TP.error("Node transform '" + getOperator()->getName() +
603 "' requires one operand!");
604 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
605 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
610 /// canPatternMatch - If it is impossible for this pattern to match on this
611 /// target, fill in Reason and return false. Otherwise, return true. This is
612 /// used as a santity check for .td files (to prevent people from writing stuff
613 /// that can never possibly work), and to prevent the pattern permuter from
614 /// generating stuff that is useless.
615 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
616 if (isLeaf()) return true;
618 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
619 if (!getChild(i)->canPatternMatch(Reason, ISE))
622 // If this node is a commutative operator, check that the LHS isn't an
624 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
625 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
626 // Scan all of the operands of the node and make sure that only the last one
627 // is a constant node.
628 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
629 if (!getChild(i)->isLeaf() &&
630 getChild(i)->getOperator()->getName() == "imm") {
631 Reason = "Immediate value must be on the RHS of commutative operators!";
639 //===----------------------------------------------------------------------===//
640 // TreePattern implementation
643 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
644 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
645 isInputPattern = isInput;
646 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
647 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
650 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
651 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
652 isInputPattern = isInput;
653 Trees.push_back(ParseTreePattern(Pat));
656 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
657 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
658 isInputPattern = isInput;
659 Trees.push_back(Pat);
664 void TreePattern::error(const std::string &Msg) const {
666 throw "In " + TheRecord->getName() + ": " + Msg;
669 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
670 Record *Operator = Dag->getNodeType();
672 if (Operator->isSubClassOf("ValueType")) {
673 // If the operator is a ValueType, then this must be "type cast" of a leaf
675 if (Dag->getNumArgs() != 1)
676 error("Type cast only takes one operand!");
678 Init *Arg = Dag->getArg(0);
679 TreePatternNode *New;
680 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
681 Record *R = DI->getDef();
682 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
683 Dag->setArg(0, new DagInit(R,
684 std::vector<std::pair<Init*, std::string> >()));
685 return ParseTreePattern(Dag);
687 New = new TreePatternNode(DI);
688 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
689 New = ParseTreePattern(DI);
690 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
691 New = new TreePatternNode(II);
692 if (!Dag->getArgName(0).empty())
693 error("Constant int argument should not have a name!");
696 error("Unknown leaf value for tree pattern!");
700 // Apply the type cast.
701 New->UpdateNodeType(getValueType(Operator), *this);
702 New->setName(Dag->getArgName(0));
706 // Verify that this is something that makes sense for an operator.
707 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
708 !Operator->isSubClassOf("Instruction") &&
709 !Operator->isSubClassOf("SDNodeXForm") &&
710 Operator->getName() != "set")
711 error("Unrecognized node '" + Operator->getName() + "'!");
713 // Check to see if this is something that is illegal in an input pattern.
714 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
715 Operator->isSubClassOf("SDNodeXForm")))
716 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
718 std::vector<TreePatternNode*> Children;
720 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
721 Init *Arg = Dag->getArg(i);
722 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
723 Children.push_back(ParseTreePattern(DI));
724 if (Children.back()->getName().empty())
725 Children.back()->setName(Dag->getArgName(i));
726 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
727 Record *R = DefI->getDef();
728 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
729 // TreePatternNode if its own.
730 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
731 Dag->setArg(i, new DagInit(R,
732 std::vector<std::pair<Init*, std::string> >()));
733 --i; // Revisit this node...
735 TreePatternNode *Node = new TreePatternNode(DefI);
736 Node->setName(Dag->getArgName(i));
737 Children.push_back(Node);
740 if (R->getName() == "node") {
741 if (Dag->getArgName(i).empty())
742 error("'node' argument requires a name to match with operand list");
743 Args.push_back(Dag->getArgName(i));
746 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
747 TreePatternNode *Node = new TreePatternNode(II);
748 if (!Dag->getArgName(i).empty())
749 error("Constant int argument should not have a name!");
750 Children.push_back(Node);
755 error("Unknown leaf value for tree pattern!");
759 return new TreePatternNode(Operator, Children);
762 /// InferAllTypes - Infer/propagate as many types throughout the expression
763 /// patterns as possible. Return true if all types are infered, false
764 /// otherwise. Throw an exception if a type contradiction is found.
765 bool TreePattern::InferAllTypes() {
766 bool MadeChange = true;
769 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
770 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
773 bool HasUnresolvedTypes = false;
774 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
775 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
776 return !HasUnresolvedTypes;
779 void TreePattern::print(std::ostream &OS) const {
780 OS << getRecord()->getName();
782 OS << "(" << Args[0];
783 for (unsigned i = 1, e = Args.size(); i != e; ++i)
784 OS << ", " << Args[i];
789 if (Trees.size() > 1)
791 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
797 if (Trees.size() > 1)
801 void TreePattern::dump() const { print(std::cerr); }
805 //===----------------------------------------------------------------------===//
806 // DAGISelEmitter implementation
809 // Parse all of the SDNode definitions for the target, populating SDNodes.
810 void DAGISelEmitter::ParseNodeInfo() {
811 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
812 while (!Nodes.empty()) {
813 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
818 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
819 /// map, and emit them to the file as functions.
820 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
821 OS << "\n// Node transformations.\n";
822 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
823 while (!Xforms.empty()) {
824 Record *XFormNode = Xforms.back();
825 Record *SDNode = XFormNode->getValueAsDef("Opcode");
826 std::string Code = XFormNode->getValueAsCode("XFormFunction");
827 SDNodeXForms.insert(std::make_pair(XFormNode,
828 std::make_pair(SDNode, Code)));
831 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
832 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
834 OS << "inline SDOperand Transform_" << XFormNode->getName()
835 << "(SDNode *" << C2 << ") {\n";
836 if (ClassName != "SDNode")
837 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
838 OS << Code << "\n}\n";
845 void DAGISelEmitter::ParseComplexPatterns() {
846 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
847 while (!AMs.empty()) {
848 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
854 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
855 /// file, building up the PatternFragments map. After we've collected them all,
856 /// inline fragments together as necessary, so that there are no references left
857 /// inside a pattern fragment to a pattern fragment.
859 /// This also emits all of the predicate functions to the output file.
861 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
862 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
864 // First step, parse all of the fragments and emit predicate functions.
865 OS << "\n// Predicate functions.\n";
866 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
867 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
868 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
869 PatternFragments[Fragments[i]] = P;
871 // Validate the argument list, converting it to map, to discard duplicates.
872 std::vector<std::string> &Args = P->getArgList();
873 std::set<std::string> OperandsMap(Args.begin(), Args.end());
875 if (OperandsMap.count(""))
876 P->error("Cannot have unnamed 'node' values in pattern fragment!");
878 // Parse the operands list.
879 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
880 if (OpsList->getNodeType()->getName() != "ops")
881 P->error("Operands list should start with '(ops ... '!");
883 // Copy over the arguments.
885 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
886 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
887 static_cast<DefInit*>(OpsList->getArg(j))->
888 getDef()->getName() != "node")
889 P->error("Operands list should all be 'node' values.");
890 if (OpsList->getArgName(j).empty())
891 P->error("Operands list should have names for each operand!");
892 if (!OperandsMap.count(OpsList->getArgName(j)))
893 P->error("'" + OpsList->getArgName(j) +
894 "' does not occur in pattern or was multiply specified!");
895 OperandsMap.erase(OpsList->getArgName(j));
896 Args.push_back(OpsList->getArgName(j));
899 if (!OperandsMap.empty())
900 P->error("Operands list does not contain an entry for operand '" +
901 *OperandsMap.begin() + "'!");
903 // If there is a code init for this fragment, emit the predicate code and
904 // keep track of the fact that this fragment uses it.
905 std::string Code = Fragments[i]->getValueAsCode("Predicate");
907 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
908 std::string ClassName =
909 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
910 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
912 OS << "inline bool Predicate_" << Fragments[i]->getName()
913 << "(SDNode *" << C2 << ") {\n";
914 if (ClassName != "SDNode")
915 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
916 OS << Code << "\n}\n";
917 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
920 // If there is a node transformation corresponding to this, keep track of
922 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
923 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
924 P->getOnlyTree()->setTransformFn(Transform);
929 // Now that we've parsed all of the tree fragments, do a closure on them so
930 // that there are not references to PatFrags left inside of them.
931 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
932 E = PatternFragments.end(); I != E; ++I) {
933 TreePattern *ThePat = I->second;
934 ThePat->InlinePatternFragments();
936 // Infer as many types as possible. Don't worry about it if we don't infer
937 // all of them, some may depend on the inputs of the pattern.
939 ThePat->InferAllTypes();
941 // If this pattern fragment is not supported by this target (no types can
942 // satisfy its constraints), just ignore it. If the bogus pattern is
943 // actually used by instructions, the type consistency error will be
947 // If debugging, print out the pattern fragment result.
948 DEBUG(ThePat->dump());
952 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
953 /// instruction input. Return true if this is a real use.
954 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
955 std::map<std::string, TreePatternNode*> &InstInputs,
956 std::vector<Record*> &InstImpInputs) {
957 // No name -> not interesting.
958 if (Pat->getName().empty()) {
960 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
961 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
962 I->error("Input " + DI->getDef()->getName() + " must be named!");
963 else if (DI && DI->getDef()->isSubClassOf("Register")) {
964 InstImpInputs.push_back(DI->getDef());
972 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
973 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
976 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
977 Rec = Pat->getOperator();
980 // SRCVALUE nodes are ignored.
981 if (Rec->getName() == "srcvalue")
984 TreePatternNode *&Slot = InstInputs[Pat->getName()];
989 if (Slot->isLeaf()) {
990 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
992 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
993 SlotRec = Slot->getOperator();
996 // Ensure that the inputs agree if we've already seen this input.
998 I->error("All $" + Pat->getName() + " inputs must agree with each other");
999 if (Slot->getExtType() != Pat->getExtType())
1000 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1005 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1006 /// part of "I", the instruction), computing the set of inputs and outputs of
1007 /// the pattern. Report errors if we see anything naughty.
1008 void DAGISelEmitter::
1009 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1010 std::map<std::string, TreePatternNode*> &InstInputs,
1011 std::map<std::string, Record*> &InstResults,
1012 std::vector<Record*> &InstImpInputs,
1013 std::vector<Record*> &InstImpResults) {
1014 if (Pat->isLeaf()) {
1015 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1016 if (!isUse && Pat->getTransformFn())
1017 I->error("Cannot specify a transform function for a non-input value!");
1019 } else if (Pat->getOperator()->getName() != "set") {
1020 // If this is not a set, verify that the children nodes are not void typed,
1022 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1023 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
1024 I->error("Cannot have void nodes inside of patterns!");
1025 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1026 InstImpInputs, InstImpResults);
1029 // If this is a non-leaf node with no children, treat it basically as if
1030 // it were a leaf. This handles nodes like (imm).
1032 if (Pat->getNumChildren() == 0)
1033 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1035 if (!isUse && Pat->getTransformFn())
1036 I->error("Cannot specify a transform function for a non-input value!");
1040 // Otherwise, this is a set, validate and collect instruction results.
1041 if (Pat->getNumChildren() == 0)
1042 I->error("set requires operands!");
1043 else if (Pat->getNumChildren() & 1)
1044 I->error("set requires an even number of operands");
1046 if (Pat->getTransformFn())
1047 I->error("Cannot specify a transform function on a set node!");
1049 // Check the set destinations.
1050 unsigned NumValues = Pat->getNumChildren()/2;
1051 for (unsigned i = 0; i != NumValues; ++i) {
1052 TreePatternNode *Dest = Pat->getChild(i);
1053 if (!Dest->isLeaf())
1054 I->error("set destination should be a register!");
1056 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1058 I->error("set destination should be a register!");
1060 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1061 if (Dest->getName().empty())
1062 I->error("set destination must have a name!");
1063 if (InstResults.count(Dest->getName()))
1064 I->error("cannot set '" + Dest->getName() +"' multiple times");
1065 InstResults[Dest->getName()] = Val->getDef();
1066 } else if (Val->getDef()->isSubClassOf("Register")) {
1067 InstImpResults.push_back(Val->getDef());
1069 I->error("set destination should be a register!");
1072 // Verify and collect info from the computation.
1073 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1074 InstInputs, InstResults, InstImpInputs, InstImpResults);
1078 /// NodeHasChain - return true if TreePatternNode has the property
1079 /// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1081 static bool NodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1083 if (N->isLeaf()) return false;
1084 Record *Operator = N->getOperator();
1085 if (!Operator->isSubClassOf("SDNode")) return false;
1087 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1088 return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1091 static bool PatternHasCtrlDep(TreePatternNode *N, DAGISelEmitter &ISE)
1093 if (NodeHasChain(N, ISE))
1096 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1097 TreePatternNode *Child = N->getChild(i);
1098 if (PatternHasCtrlDep(Child, ISE))
1107 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1108 /// any fragments involved. This populates the Instructions list with fully
1109 /// resolved instructions.
1110 void DAGISelEmitter::ParseInstructions() {
1111 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1113 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1116 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1117 LI = Instrs[i]->getValueAsListInit("Pattern");
1119 // If there is no pattern, only collect minimal information about the
1120 // instruction for its operand list. We have to assume that there is one
1121 // result, as we have no detailed info.
1122 if (!LI || LI->getSize() == 0) {
1123 std::vector<Record*> Results;
1124 std::vector<Record*> Operands;
1126 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1128 // Doesn't even define a result?
1129 if (InstInfo.OperandList.size() == 0)
1132 // FIXME: temporary hack...
1133 if (InstInfo.isReturn || InstInfo.isBranch || InstInfo.isCall ||
1135 // These produce no results
1136 for (unsigned j = 0, e = InstInfo.OperandList.size(); j != e; ++j)
1137 Operands.push_back(InstInfo.OperandList[j].Rec);
1139 // Assume the first operand is the result.
1140 Results.push_back(InstInfo.OperandList[0].Rec);
1142 // The rest are inputs.
1143 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1144 Operands.push_back(InstInfo.OperandList[j].Rec);
1147 // Create and insert the instruction.
1148 std::vector<Record*> ImpResults;
1149 std::vector<Record*> ImpOperands;
1150 Instructions.insert(std::make_pair(Instrs[i],
1151 DAGInstruction(0, Results, Operands,
1152 ImpResults, ImpOperands)));
1153 continue; // no pattern.
1156 // Parse the instruction.
1157 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1158 // Inline pattern fragments into it.
1159 I->InlinePatternFragments();
1161 // Infer as many types as possible. If we cannot infer all of them, we can
1162 // never do anything with this instruction pattern: report it to the user.
1163 if (!I->InferAllTypes())
1164 I->error("Could not infer all types in pattern!");
1166 // InstInputs - Keep track of all of the inputs of the instruction, along
1167 // with the record they are declared as.
1168 std::map<std::string, TreePatternNode*> InstInputs;
1170 // InstResults - Keep track of all the virtual registers that are 'set'
1171 // in the instruction, including what reg class they are.
1172 std::map<std::string, Record*> InstResults;
1174 std::vector<Record*> InstImpInputs;
1175 std::vector<Record*> InstImpResults;
1177 // Verify that the top-level forms in the instruction are of void type, and
1178 // fill in the InstResults map.
1179 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1180 TreePatternNode *Pat = I->getTree(j);
1181 if (Pat->getExtType() != MVT::isVoid)
1182 I->error("Top-level forms in instruction pattern should have"
1185 // Find inputs and outputs, and verify the structure of the uses/defs.
1186 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1187 InstImpInputs, InstImpResults);
1190 // Now that we have inputs and outputs of the pattern, inspect the operands
1191 // list for the instruction. This determines the order that operands are
1192 // added to the machine instruction the node corresponds to.
1193 unsigned NumResults = InstResults.size();
1195 // Parse the operands list from the (ops) list, validating it.
1196 std::vector<std::string> &Args = I->getArgList();
1197 assert(Args.empty() && "Args list should still be empty here!");
1198 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1200 // Check that all of the results occur first in the list.
1201 std::vector<Record*> Results;
1202 for (unsigned i = 0; i != NumResults; ++i) {
1203 if (i == CGI.OperandList.size())
1204 I->error("'" + InstResults.begin()->first +
1205 "' set but does not appear in operand list!");
1206 const std::string &OpName = CGI.OperandList[i].Name;
1208 // Check that it exists in InstResults.
1209 Record *R = InstResults[OpName];
1211 I->error("Operand $" + OpName + " should be a set destination: all "
1212 "outputs must occur before inputs in operand list!");
1214 if (CGI.OperandList[i].Rec != R)
1215 I->error("Operand $" + OpName + " class mismatch!");
1217 // Remember the return type.
1218 Results.push_back(CGI.OperandList[i].Rec);
1220 // Okay, this one checks out.
1221 InstResults.erase(OpName);
1224 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1225 // the copy while we're checking the inputs.
1226 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1228 std::vector<TreePatternNode*> ResultNodeOperands;
1229 std::vector<Record*> Operands;
1230 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1231 const std::string &OpName = CGI.OperandList[i].Name;
1233 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1235 if (!InstInputsCheck.count(OpName))
1236 I->error("Operand $" + OpName +
1237 " does not appear in the instruction pattern");
1238 TreePatternNode *InVal = InstInputsCheck[OpName];
1239 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1241 if (InVal->isLeaf() &&
1242 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1243 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1244 if (CGI.OperandList[i].Rec != InRec &&
1245 !InRec->isSubClassOf("ComplexPattern"))
1246 I->error("Operand $" + OpName +
1247 "'s register class disagrees between the operand and pattern");
1249 Operands.push_back(CGI.OperandList[i].Rec);
1251 // Construct the result for the dest-pattern operand list.
1252 TreePatternNode *OpNode = InVal->clone();
1254 // No predicate is useful on the result.
1255 OpNode->setPredicateFn("");
1257 // Promote the xform function to be an explicit node if set.
1258 if (Record *Xform = OpNode->getTransformFn()) {
1259 OpNode->setTransformFn(0);
1260 std::vector<TreePatternNode*> Children;
1261 Children.push_back(OpNode);
1262 OpNode = new TreePatternNode(Xform, Children);
1265 ResultNodeOperands.push_back(OpNode);
1268 if (!InstInputsCheck.empty())
1269 I->error("Input operand $" + InstInputsCheck.begin()->first +
1270 " occurs in pattern but not in operands list!");
1272 TreePatternNode *ResultPattern =
1273 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1275 // Create and insert the instruction.
1276 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1277 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1279 // Use a temporary tree pattern to infer all types and make sure that the
1280 // constructed result is correct. This depends on the instruction already
1281 // being inserted into the Instructions map.
1282 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1283 Temp.InferAllTypes();
1285 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1286 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1291 // If we can, convert the instructions to be patterns that are matched!
1292 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1293 E = Instructions.end(); II != E; ++II) {
1294 DAGInstruction &TheInst = II->second;
1295 TreePattern *I = TheInst.getPattern();
1296 if (I == 0) continue; // No pattern.
1298 if (I->getNumTrees() != 1) {
1299 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1302 TreePatternNode *Pattern = I->getTree(0);
1303 TreePatternNode *SrcPattern;
1304 if (Pattern->getOperator()->getName() == "set") {
1305 if (Pattern->getNumChildren() != 2)
1306 continue; // Not a set of a single value (not handled so far)
1308 SrcPattern = Pattern->getChild(1)->clone();
1310 // Not a set (store or something?)
1311 SrcPattern = Pattern;
1315 if (!SrcPattern->canPatternMatch(Reason, *this))
1316 I->error("Instruction can never match: " + Reason);
1318 Record *Instr = II->first;
1319 TreePatternNode *DstPattern = TheInst.getResultPattern();
1321 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1322 SrcPattern, DstPattern));
1324 if (PatternHasCtrlDep(Pattern, *this)) {
1325 CodeGenInstruction &InstInfo = Target.getInstruction(Instr->getName());
1326 InstInfo.hasCtrlDep = true;
1331 void DAGISelEmitter::ParsePatterns() {
1332 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1334 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1335 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1336 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1338 // Inline pattern fragments into it.
1339 Pattern->InlinePatternFragments();
1341 // Infer as many types as possible. If we cannot infer all of them, we can
1342 // never do anything with this pattern: report it to the user.
1343 if (!Pattern->InferAllTypes())
1344 Pattern->error("Could not infer all types in pattern!");
1346 // Validate that the input pattern is correct.
1348 std::map<std::string, TreePatternNode*> InstInputs;
1349 std::map<std::string, Record*> InstResults;
1350 std::vector<Record*> InstImpInputs;
1351 std::vector<Record*> InstImpResults;
1352 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1353 InstInputs, InstResults,
1354 InstImpInputs, InstImpResults);
1357 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1358 if (LI->getSize() == 0) continue; // no pattern.
1360 // Parse the instruction.
1361 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1363 // Inline pattern fragments into it.
1364 Result->InlinePatternFragments();
1366 // Infer as many types as possible. If we cannot infer all of them, we can
1367 // never do anything with this pattern: report it to the user.
1368 if (!Result->InferAllTypes())
1369 Result->error("Could not infer all types in pattern result!");
1371 if (Result->getNumTrees() != 1)
1372 Result->error("Cannot handle instructions producing instructions "
1373 "with temporaries yet!");
1376 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1377 Pattern->error("Pattern can never match: " + Reason);
1380 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1381 Pattern->getOnlyTree(),
1382 Result->getOnlyTree()));
1386 /// CombineChildVariants - Given a bunch of permutations of each child of the
1387 /// 'operator' node, put them together in all possible ways.
1388 static void CombineChildVariants(TreePatternNode *Orig,
1389 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1390 std::vector<TreePatternNode*> &OutVariants,
1391 DAGISelEmitter &ISE) {
1392 // Make sure that each operand has at least one variant to choose from.
1393 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1394 if (ChildVariants[i].empty())
1397 // The end result is an all-pairs construction of the resultant pattern.
1398 std::vector<unsigned> Idxs;
1399 Idxs.resize(ChildVariants.size());
1400 bool NotDone = true;
1402 // Create the variant and add it to the output list.
1403 std::vector<TreePatternNode*> NewChildren;
1404 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1405 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1406 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1408 // Copy over properties.
1409 R->setName(Orig->getName());
1410 R->setPredicateFn(Orig->getPredicateFn());
1411 R->setTransformFn(Orig->getTransformFn());
1412 R->setType(Orig->getExtType());
1414 // If this pattern cannot every match, do not include it as a variant.
1415 std::string ErrString;
1416 if (!R->canPatternMatch(ErrString, ISE)) {
1419 bool AlreadyExists = false;
1421 // Scan to see if this pattern has already been emitted. We can get
1422 // duplication due to things like commuting:
1423 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1424 // which are the same pattern. Ignore the dups.
1425 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1426 if (R->isIsomorphicTo(OutVariants[i])) {
1427 AlreadyExists = true;
1434 OutVariants.push_back(R);
1437 // Increment indices to the next permutation.
1439 // Look for something we can increment without causing a wrap-around.
1440 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1441 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1442 NotDone = true; // Found something to increment.
1450 /// CombineChildVariants - A helper function for binary operators.
1452 static void CombineChildVariants(TreePatternNode *Orig,
1453 const std::vector<TreePatternNode*> &LHS,
1454 const std::vector<TreePatternNode*> &RHS,
1455 std::vector<TreePatternNode*> &OutVariants,
1456 DAGISelEmitter &ISE) {
1457 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1458 ChildVariants.push_back(LHS);
1459 ChildVariants.push_back(RHS);
1460 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1464 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1465 std::vector<TreePatternNode *> &Children) {
1466 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1467 Record *Operator = N->getOperator();
1469 // Only permit raw nodes.
1470 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1471 N->getTransformFn()) {
1472 Children.push_back(N);
1476 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1477 Children.push_back(N->getChild(0));
1479 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1481 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1482 Children.push_back(N->getChild(1));
1484 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1487 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1488 /// the (potentially recursive) pattern by using algebraic laws.
1490 static void GenerateVariantsOf(TreePatternNode *N,
1491 std::vector<TreePatternNode*> &OutVariants,
1492 DAGISelEmitter &ISE) {
1493 // We cannot permute leaves.
1495 OutVariants.push_back(N);
1499 // Look up interesting info about the node.
1500 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1502 // If this node is associative, reassociate.
1503 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1504 // Reassociate by pulling together all of the linked operators
1505 std::vector<TreePatternNode*> MaximalChildren;
1506 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1508 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1510 if (MaximalChildren.size() == 3) {
1511 // Find the variants of all of our maximal children.
1512 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1513 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1514 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1515 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1517 // There are only two ways we can permute the tree:
1518 // (A op B) op C and A op (B op C)
1519 // Within these forms, we can also permute A/B/C.
1521 // Generate legal pair permutations of A/B/C.
1522 std::vector<TreePatternNode*> ABVariants;
1523 std::vector<TreePatternNode*> BAVariants;
1524 std::vector<TreePatternNode*> ACVariants;
1525 std::vector<TreePatternNode*> CAVariants;
1526 std::vector<TreePatternNode*> BCVariants;
1527 std::vector<TreePatternNode*> CBVariants;
1528 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1529 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1530 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1531 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1532 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1533 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1535 // Combine those into the result: (x op x) op x
1536 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1537 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1538 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1539 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1540 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1541 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1543 // Combine those into the result: x op (x op x)
1544 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1545 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1546 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1547 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1548 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1549 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1554 // Compute permutations of all children.
1555 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1556 ChildVariants.resize(N->getNumChildren());
1557 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1558 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1560 // Build all permutations based on how the children were formed.
1561 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1563 // If this node is commutative, consider the commuted order.
1564 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1565 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1566 // Consider the commuted order.
1567 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1573 // GenerateVariants - Generate variants. For example, commutative patterns can
1574 // match multiple ways. Add them to PatternsToMatch as well.
1575 void DAGISelEmitter::GenerateVariants() {
1577 DEBUG(std::cerr << "Generating instruction variants.\n");
1579 // Loop over all of the patterns we've collected, checking to see if we can
1580 // generate variants of the instruction, through the exploitation of
1581 // identities. This permits the target to provide agressive matching without
1582 // the .td file having to contain tons of variants of instructions.
1584 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1585 // intentionally do not reconsider these. Any variants of added patterns have
1586 // already been added.
1588 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1589 std::vector<TreePatternNode*> Variants;
1590 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1592 assert(!Variants.empty() && "Must create at least original variant!");
1593 Variants.erase(Variants.begin()); // Remove the original pattern.
1595 if (Variants.empty()) // No variants for this pattern.
1598 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1599 PatternsToMatch[i].getSrcPattern()->dump();
1602 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1603 TreePatternNode *Variant = Variants[v];
1605 DEBUG(std::cerr << " VAR#" << v << ": ";
1609 // Scan to see if an instruction or explicit pattern already matches this.
1610 bool AlreadyExists = false;
1611 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1612 // Check to see if this variant already exists.
1613 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1614 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1615 AlreadyExists = true;
1619 // If we already have it, ignore the variant.
1620 if (AlreadyExists) continue;
1622 // Otherwise, add it to the list of patterns we have.
1624 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1625 Variant, PatternsToMatch[i].getDstPattern()));
1628 DEBUG(std::cerr << "\n");
1633 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1635 static bool NodeIsComplexPattern(TreePatternNode *N)
1637 return (N->isLeaf() &&
1638 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1639 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1640 isSubClassOf("ComplexPattern"));
1643 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1644 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1645 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1646 DAGISelEmitter &ISE)
1649 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1650 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1651 isSubClassOf("ComplexPattern")) {
1652 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1658 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1659 /// patterns before small ones. This is used to determine the size of a
1661 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1662 assert(isExtIntegerVT(P->getExtType()) ||
1663 isExtFloatingPointVT(P->getExtType()) ||
1664 P->getExtType() == MVT::isVoid ||
1665 P->getExtType() == MVT::Flag && "Not a valid pattern node to size!");
1666 unsigned Size = 1; // The node itself.
1668 // FIXME: This is a hack to statically increase the priority of patterns
1669 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1670 // Later we can allow complexity / cost for each pattern to be (optionally)
1671 // specified. To get best possible pattern match we'll need to dynamically
1672 // calculate the complexity of all patterns a dag can potentially map to.
1673 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1675 Size += AM->getNumOperands();
1677 // Count children in the count if they are also nodes.
1678 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1679 TreePatternNode *Child = P->getChild(i);
1680 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
1681 Size += getPatternSize(Child, ISE);
1682 else if (Child->isLeaf()) {
1683 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1684 ++Size; // Matches a ConstantSDNode.
1685 else if (NodeIsComplexPattern(Child))
1686 Size += getPatternSize(Child, ISE);
1693 /// getResultPatternCost - Compute the number of instructions for this pattern.
1694 /// This is a temporary hack. We should really include the instruction
1695 /// latencies in this calculation.
1696 static unsigned getResultPatternCost(TreePatternNode *P) {
1697 if (P->isLeaf()) return 0;
1699 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1700 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1701 Cost += getResultPatternCost(P->getChild(i));
1705 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1706 // In particular, we want to match maximal patterns first and lowest cost within
1707 // a particular complexity first.
1708 struct PatternSortingPredicate {
1709 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1710 DAGISelEmitter &ISE;
1712 bool operator()(PatternToMatch *LHS,
1713 PatternToMatch *RHS) {
1714 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1715 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1716 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1717 if (LHSSize < RHSSize) return false;
1719 // If the patterns have equal complexity, compare generated instruction cost
1720 return getResultPatternCost(LHS->getDstPattern()) <
1721 getResultPatternCost(RHS->getDstPattern());
1725 /// getRegisterValueType - Look up and return the first ValueType of specified
1726 /// RegisterClass record
1727 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1728 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1729 return RC->getValueTypeNum(0);
1734 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1735 /// type information from it.
1736 static void RemoveAllTypes(TreePatternNode *N) {
1737 N->setType(MVT::isUnknown);
1739 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1740 RemoveAllTypes(N->getChild(i));
1743 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1744 Record *N = Records.getDef(Name);
1745 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1749 class PatternCodeEmitter {
1751 DAGISelEmitter &ISE;
1754 ListInit *Predicates;
1755 // Instruction selector pattern.
1756 TreePatternNode *Pattern;
1757 // Matched instruction.
1758 TreePatternNode *Instruction;
1761 // Node to name mapping
1762 std::map<std::string,std::string> VariableMap;
1763 // Names of all the folded nodes which produce chains.
1764 std::vector<std::string> FoldedChains;
1770 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1771 TreePatternNode *pattern, TreePatternNode *instr,
1772 unsigned PatNum, std::ostream &os) :
1773 ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
1774 PatternNo(PatNum), OS(os), FoundChain(false), InFlag(false), TmpNo(0) {};
1776 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1777 /// if the match fails. At this point, we already know that the opcode for N
1778 /// matches, and the SDNode for the result has the RootName specified name.
1779 void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
1780 bool isRoot = false) {
1782 // Emit instruction predicates. Each predicate is just a string for now.
1784 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1785 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1786 Record *Def = Pred->getDef();
1787 if (Def->isSubClassOf("Predicate")) {
1792 OS << "(" << Def->getValueAsString("CondString") << ")";
1794 OS << ") goto P" << PatternNo << "Fail;\n";
1797 assert(0 && "Unknown predicate type!");
1804 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1805 OS << " if (cast<ConstantSDNode>(" << RootName
1806 << ")->getSignExtended() != " << II->getValue() << ")\n"
1807 << " goto P" << PatternNo << "Fail;\n";
1809 } else if (!NodeIsComplexPattern(N)) {
1810 assert(0 && "Cannot match this as a leaf value!");
1815 // If this node has a name associated with it, capture it in VariableMap. If
1816 // we already saw this in the pattern, emit code to verify dagness.
1817 if (!N->getName().empty()) {
1818 std::string &VarMapEntry = VariableMap[N->getName()];
1819 if (VarMapEntry.empty()) {
1820 VarMapEntry = RootName;
1822 // If we get here, this is a second reference to a specific name. Since
1823 // we already have checked that the first reference is valid, we don't
1824 // have to recursively match it, just check that it's the same as the
1825 // previously named thing.
1826 OS << " if (" << VarMapEntry << " != " << RootName
1827 << ") goto P" << PatternNo << "Fail;\n";
1833 // Emit code to load the child nodes and match their contents recursively.
1835 bool HasChain = NodeHasChain(N, ISE);
1839 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
1840 OS << " if (!" << RootName << ".hasOneUse()) goto P"
1841 << PatternNo << "Fail; // Multiple uses of actual result?\n";
1842 OS << " if (CodeGenMap.count(" << RootName
1843 << ".getValue(" << CInfo.getNumResults() << "))) goto P"
1844 << PatternNo << "Fail; // Already selected for a chain use?\n";
1848 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1849 OS << " SDOperand " << RootName << OpNo <<" = " << RootName
1850 << ".getOperand(" << OpNo << ");\n";
1851 TreePatternNode *Child = N->getChild(i);
1853 if (!Child->isLeaf()) {
1854 // If it's not a leaf, recursively match.
1855 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1856 OS << " if (" << RootName << OpNo << ".getOpcode() != "
1857 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1858 EmitMatchCode(Child, RootName + utostr(OpNo));
1859 if (NodeHasChain(Child, ISE))
1860 FoldedChains.push_back(RootName + utostr(OpNo));
1862 // If this child has a name associated with it, capture it in VarMap. If
1863 // we already saw this in the pattern, emit code to verify dagness.
1864 if (!Child->getName().empty()) {
1865 std::string &VarMapEntry = VariableMap[Child->getName()];
1866 if (VarMapEntry.empty()) {
1867 VarMapEntry = RootName + utostr(OpNo);
1869 // If we get here, this is a second reference to a specific name. Since
1870 // we already have checked that the first reference is valid, we don't
1871 // have to recursively match it, just check that it's the same as the
1872 // previously named thing.
1873 OS << " if (" << VarMapEntry << " != " << RootName << OpNo
1874 << ") goto P" << PatternNo << "Fail;\n";
1879 // Handle leaves of various types.
1880 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1881 Record *LeafRec = DI->getDef();
1882 if (LeafRec->isSubClassOf("RegisterClass")) {
1883 // Handle register references. Nothing to do here.
1884 } else if (LeafRec->isSubClassOf("Register")) {
1886 OS << " SDOperand InFlag = SDOperand(0,0);\n";
1889 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1890 // Handle complex pattern. Nothing to do here.
1891 } else if (LeafRec->getName() == "srcvalue") {
1892 // Place holder for SRCVALUE nodes. Nothing to do here.
1893 } else if (LeafRec->isSubClassOf("ValueType")) {
1894 // Make sure this is the specified value type.
1895 OS << " if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
1896 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1898 } else if (LeafRec->isSubClassOf("CondCode")) {
1899 // Make sure this is the specified cond code.
1900 OS << " if (cast<CondCodeSDNode>(" << RootName << OpNo
1901 << ")->get() != " << "ISD::" << LeafRec->getName()
1902 << ") goto P" << PatternNo << "Fail;\n";
1905 assert(0 && "Unknown leaf type!");
1907 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1908 OS << " if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1909 << " cast<ConstantSDNode>(" << RootName << OpNo
1910 << ")->getSignExtended() != " << II->getValue() << ")\n"
1911 << " goto P" << PatternNo << "Fail;\n";
1914 assert(0 && "Unknown leaf type!");
1921 OS << " SDOperand Chain = " << RootName << ".getOperand(0);\n";
1926 // If there is a node predicate for this, emit the call.
1927 if (!N->getPredicateFn().empty())
1928 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1929 << ".Val)) goto P" << PatternNo << "Fail;\n";
1932 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
1933 /// we actually have to build a DAG!
1934 std::pair<unsigned, unsigned>
1935 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
1936 // This is something selected from the pattern we matched.
1937 if (!N->getName().empty()) {
1938 assert(!isRoot && "Root of pattern cannot be a leaf!");
1939 std::string &Val = VariableMap[N->getName()];
1940 assert(!Val.empty() &&
1941 "Variable referenced but not defined and not caught earlier!");
1942 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1943 // Already selected this operand, just return the tmpval.
1944 return std::make_pair(1, atoi(Val.c_str()+3));
1947 const ComplexPattern *CP;
1948 unsigned ResNo = TmpNo++;
1949 unsigned NumRes = 1;
1950 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1951 switch (N->getType()) {
1952 default: assert(0 && "Unknown type for constant node!");
1953 case MVT::i1: OS << " bool Tmp"; break;
1954 case MVT::i8: OS << " unsigned char Tmp"; break;
1955 case MVT::i16: OS << " unsigned short Tmp"; break;
1956 case MVT::i32: OS << " unsigned Tmp"; break;
1957 case MVT::i64: OS << " uint64_t Tmp"; break;
1959 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1960 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1961 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1962 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1963 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
1964 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
1965 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
1966 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
1967 std::string Fn = CP->getSelectFunc();
1968 NumRes = CP->getNumOperands();
1969 OS << " SDOperand ";
1970 for (unsigned i = 0; i < NumRes; i++) {
1971 if (i != 0) OS << ", ";
1972 OS << "Tmp" << i + ResNo;
1975 OS << " if (!" << Fn << "(" << Val;
1976 for (unsigned i = 0; i < NumRes; i++)
1977 OS << ", Tmp" << i + ResNo;
1978 OS << ")) goto P" << PatternNo << "Fail;\n";
1979 TmpNo = ResNo + NumRes;
1981 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1983 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1984 // value if used multiple times by this pattern result.
1985 Val = "Tmp"+utostr(ResNo);
1986 return std::make_pair(NumRes, ResNo);
1990 // If this is an explicit register reference, handle it.
1991 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1992 unsigned ResNo = TmpNo++;
1993 if (DI->getDef()->isSubClassOf("Register")) {
1994 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1995 << ISE.getQualifiedName(DI->getDef()) << ", MVT::"
1996 << getEnumName(N->getType())
1998 return std::make_pair(1, ResNo);
2000 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2001 unsigned ResNo = TmpNo++;
2002 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
2003 << II->getValue() << ", MVT::"
2004 << getEnumName(N->getType())
2006 return std::make_pair(1, ResNo);
2010 assert(0 && "Unknown leaf type!");
2011 return std::make_pair(1, ~0U);
2014 Record *Op = N->getOperator();
2015 if (Op->isSubClassOf("Instruction")) {
2016 // Determine operand emission order. Complex pattern first.
2017 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2018 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2019 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2020 TreePatternNode *Child = N->getChild(i);
2022 EmitOrder.push_back(std::make_pair(i, Child));
2023 OI = EmitOrder.begin();
2024 } else if (NodeIsComplexPattern(Child)) {
2025 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2027 EmitOrder.push_back(std::make_pair(i, Child));
2031 // Emit all of the operands.
2032 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2033 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2034 unsigned OpOrder = EmitOrder[i].first;
2035 TreePatternNode *Child = EmitOrder[i].second;
2036 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2037 NumTemps[OpOrder] = NumTemp;
2040 // List all the operands in the right order.
2041 std::vector<unsigned> Ops;
2042 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2043 for (unsigned j = 0; j < NumTemps[i].first; j++)
2044 Ops.push_back(NumTemps[i].second + j);
2047 const CodeGenTarget &CGT = ISE.getTargetInfo();
2048 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2050 // Emit all the chain and CopyToReg stuff.
2052 OS << " Chain = Select(Chain);\n";
2053 EmitCopyToRegs(Pattern, "N", II.hasCtrlDep);
2055 const DAGInstruction &Inst = ISE.getInstruction(Op);
2056 unsigned NumImpResults = Inst.getNumImpResults();
2057 unsigned NumResults = Inst.getNumResults();
2058 unsigned ResNo = TmpNo++;
2060 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
2061 << II.Namespace << "::" << II.TheDef->getName();
2062 if (N->getType() != MVT::isVoid)
2063 OS << ", MVT::" << getEnumName(N->getType());
2064 for (unsigned i = 0; i < NumImpResults; i++) {
2065 Record *ImpResult = Inst.getImpResult(i);
2066 MVT::ValueType RVT = getRegisterValueType(ImpResult, CGT);
2067 OS << ", MVT::" << getEnumName(RVT);
2070 unsigned LastOp = 0;
2071 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2073 OS << ", Tmp" << LastOp;
2076 if (II.hasCtrlDep) {
2077 // Must have at least one result
2078 OS << " Chain = Tmp" << LastOp << ".getValue("
2079 << NumResults << ");\n";
2081 } else if (II.hasCtrlDep) {
2082 OS << " SDOperand Result = ";
2083 OS << "CurDAG->getTargetNode("
2084 << II.Namespace << "::" << II.TheDef->getName();
2085 if (NumResults > 0) {
2086 // TODO: multiple results?
2087 if (N->getType() != MVT::isVoid)
2088 OS << ", MVT::" << getEnumName(N->getType());
2090 OS << ", MVT::Other";
2091 for (unsigned i = 0; i < NumImpResults; i++) {
2092 Record *ImpResult = Inst.getImpResult(i);
2093 MVT::ValueType RVT = getRegisterValueType(ImpResult, CGT);
2094 OS << ", MVT::" << getEnumName(RVT);
2096 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2097 OS << ", Tmp" << Ops[i];
2102 if (NumResults != 0) {
2103 OS << " CodeGenMap[N.getValue(0)] = Result;\n";
2106 if (NodeHasChain(Pattern, ISE))
2107 OS << "= CodeGenMap[N.getValue(" << NumResults << ")] ";
2108 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2109 OS << "= CodeGenMap[" << FoldedChains[j] << ".getValue("
2110 << NumResults << ")] ";
2111 OS << "= Result.getValue(" << NumResults << ");\n";
2112 if (NumResults == 0 && NumImpResults == 0)
2113 OS << " return Chain;\n";
2115 OS << " return (N.ResNo) ? Chain : Result.getValue(0);\n";
2117 // If this instruction is the root, and if there is only one use of it,
2118 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2119 OS << " if (N.Val->hasOneUse()) {\n";
2120 OS << " return CurDAG->SelectNodeTo(N.Val, "
2121 << II.Namespace << "::" << II.TheDef->getName();
2122 if (N->getType() != MVT::isVoid)
2123 OS << ", MVT::" << getEnumName(N->getType());
2124 for (unsigned i = 0; i < NumImpResults; i++) {
2125 Record *ImpResult = Inst.getImpResult(i);
2126 MVT::ValueType RVT = getRegisterValueType(ImpResult, CGT);
2127 OS << ", MVT::" << getEnumName(RVT);
2129 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2130 OS << ", Tmp" << Ops[i];
2134 OS << " } else {\n";
2135 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
2136 << II.Namespace << "::" << II.TheDef->getName();
2137 if (N->getType() != MVT::isVoid)
2138 OS << ", MVT::" << getEnumName(N->getType());
2139 for (unsigned i = 0; i < NumImpResults; i++) {
2140 Record *ImpResult = Inst.getImpResult(i);
2141 MVT::ValueType RVT = getRegisterValueType(ImpResult, CGT);
2142 OS << ", MVT::" << getEnumName(RVT);
2144 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2145 OS << ", Tmp" << Ops[i];
2151 return std::make_pair(1, ResNo);
2152 } else if (Op->isSubClassOf("SDNodeXForm")) {
2153 assert(N->getNumChildren() == 1 && "node xform should have one child!");
2154 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
2155 unsigned ResNo = TmpNo++;
2156 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
2157 << "(Tmp" << OpVal << ".Val);\n";
2159 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
2160 OS << " return Tmp" << ResNo << ";\n";
2162 return std::make_pair(1, ResNo);
2165 assert(0 && "Unknown node in result pattern!");
2166 return std::make_pair(1, ~0U);
2170 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2171 /// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2172 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2173 /// for, this returns true otherwise false if Pat has all types.
2174 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2175 const std::string &Prefix) {
2177 if (!Pat->hasTypeSet()) {
2178 // Move a type over from 'other' to 'pat'.
2179 Pat->setType(Other->getType());
2180 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
2181 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
2185 unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
2186 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2187 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2188 Prefix + utostr(OpNo)))
2194 /// EmitCopyToRegs - Emit the flag operands for the DAG that is
2196 void EmitCopyToRegs(TreePatternNode *N, const std::string &RootName,
2198 const CodeGenTarget &T = ISE.getTargetInfo();
2199 unsigned OpNo = (unsigned) NodeHasChain(N, ISE);
2200 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2201 TreePatternNode *Child = N->getChild(i);
2202 if (!Child->isLeaf()) {
2203 EmitCopyToRegs(Child, RootName + utostr(OpNo), HasCtrlDep);
2205 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2206 Record *RR = DI->getDef();
2207 if (RR->isSubClassOf("Register")) {
2208 MVT::ValueType RVT = getRegisterValueType(RR, T);
2209 if (RVT == MVT::Flag) {
2210 OS << " InFlag = Select(" << RootName << OpNo << ");\n";
2211 } else if (HasCtrlDep) {
2212 OS << " SDOperand " << RootName << "CR" << i << ";\n";
2213 OS << " " << RootName << "CR" << i
2214 << " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
2215 << ISE.getQualifiedName(RR) << ", MVT::"
2216 << getEnumName(RVT) << ")"
2217 << ", Select(" << RootName << OpNo << "), InFlag);\n";
2218 OS << " Chain = " << RootName << "CR" << i
2219 << ".getValue(0);\n";
2220 OS << " InFlag = " << RootName << "CR" << i
2221 << ".getValue(1);\n";
2223 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
2224 << ", CurDAG->getRegister(" << ISE.getQualifiedName(RR)
2225 << ", MVT::" << getEnumName(RVT) << ")"
2226 << ", Select(" << RootName << OpNo
2227 << "), InFlag).getValue(1);\n";
2236 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2237 /// stream to match the pattern, and generate the code for the match if it
2239 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2241 static unsigned PatternCount = 0;
2242 unsigned PatternNo = PatternCount++;
2243 OS << " { // Pattern #" << PatternNo << ": ";
2244 Pattern.getSrcPattern()->print(OS);
2245 OS << "\n // Emits: ";
2246 Pattern.getDstPattern()->print(OS);
2248 OS << " // Pattern complexity = "
2249 << getPatternSize(Pattern.getSrcPattern(), *this)
2251 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
2253 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2254 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2257 // Emit the matcher, capturing named arguments in VariableMap.
2258 Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", true /*the root*/);
2260 // TP - Get *SOME* tree pattern, we don't care which.
2261 TreePattern &TP = *PatternFragments.begin()->second;
2263 // At this point, we know that we structurally match the pattern, but the
2264 // types of the nodes may not match. Figure out the fewest number of type
2265 // comparisons we need to emit. For example, if there is only one integer
2266 // type supported by a target, there should be no type comparisons at all for
2267 // integer patterns!
2269 // To figure out the fewest number of type checks needed, clone the pattern,
2270 // remove the types, then perform type inference on the pattern as a whole.
2271 // If there are unresolved types, emit an explicit check for those types,
2272 // apply the type to the tree, then rerun type inference. Iterate until all
2273 // types are resolved.
2275 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2276 RemoveAllTypes(Pat);
2279 // Resolve/propagate as many types as possible.
2281 bool MadeChange = true;
2283 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2285 assert(0 && "Error: could not find consistent types for something we"
2286 " already decided was ok!");
2290 // Insert a check for an unresolved type and add it to the tree. If we find
2291 // an unresolved type to add a check for, this returns true and we iterate,
2292 // otherwise we are done.
2293 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2295 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
2299 OS << " }\n P" << PatternNo << "Fail:\n";
2304 /// CompareByRecordName - An ordering predicate that implements less-than by
2305 /// comparing the names records.
2306 struct CompareByRecordName {
2307 bool operator()(const Record *LHS, const Record *RHS) const {
2308 // Sort by name first.
2309 if (LHS->getName() < RHS->getName()) return true;
2310 // If both names are equal, sort by pointer.
2311 return LHS->getName() == RHS->getName() && LHS < RHS;
2316 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
2317 std::string InstNS = Target.inst_begin()->second.Namespace;
2318 if (!InstNS.empty()) InstNS += "::";
2320 // Emit boilerplate.
2321 OS << "// The main instruction selector code.\n"
2322 << "SDOperand SelectCode(SDOperand N) {\n"
2323 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
2324 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2325 << "INSTRUCTION_LIST_END))\n"
2326 << " return N; // Already selected.\n\n"
2327 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
2328 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
2329 << " switch (N.getOpcode()) {\n"
2330 << " default: break;\n"
2331 << " case ISD::EntryToken: // These leaves remain the same.\n"
2333 << " case ISD::AssertSext:\n"
2334 << " case ISD::AssertZext: {\n"
2335 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2336 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2337 << " return Tmp0;\n"
2339 << " case ISD::TokenFactor:\n"
2340 << " if (N.getNumOperands() == 2) {\n"
2341 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2342 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2343 << " return CodeGenMap[N] =\n"
2344 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2346 << " std::vector<SDOperand> Ops;\n"
2347 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2348 << " Ops.push_back(Select(N.getOperand(i)));\n"
2349 << " return CodeGenMap[N] = \n"
2350 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2352 << " case ISD::CopyFromReg: {\n"
2353 << " SDOperand Chain = Select(N.getOperand(0));\n"
2354 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2355 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
2356 << " if (N.Val->getNumValues() == 2) {\n"
2357 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2358 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
2359 << " CodeGenMap[N.getValue(0)] = New;\n"
2360 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2361 << " return New.getValue(N.ResNo);\n"
2363 << " SDOperand Flag;\n"
2364 << " if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
2365 << " if (Chain == N.getOperand(0) &&\n"
2366 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
2367 << " return N; // No change\n"
2368 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
2369 << " CodeGenMap[N.getValue(0)] = New;\n"
2370 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2371 << " CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
2372 << " return New.getValue(N.ResNo);\n"
2375 << " case ISD::CopyToReg: {\n"
2376 << " SDOperand Chain = Select(N.getOperand(0));\n"
2377 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2378 << " SDOperand Val = Select(N.getOperand(2));\n"
2379 << " SDOperand Result = N;\n"
2380 << " if (N.Val->getNumValues() == 1) {\n"
2381 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
2382 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
2383 << " return CodeGenMap[N] = Result;\n"
2385 << " SDOperand Flag;\n"
2386 << " if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
2387 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
2388 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
2389 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
2390 << " CodeGenMap[N.getValue(0)] = Result;\n"
2391 << " CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
2392 << " return Result.getValue(N.ResNo);\n"
2396 // Group the patterns by their top-level opcodes.
2397 std::map<Record*, std::vector<PatternToMatch*>,
2398 CompareByRecordName> PatternsByOpcode;
2399 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2400 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2401 if (!Node->isLeaf()) {
2402 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2404 const ComplexPattern *CP;
2406 dynamic_cast<IntInit*>(Node->getLeafValue())) {
2407 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2408 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2409 std::vector<Record*> OpNodes = CP->getRootNodes();
2410 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2411 PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2412 &PatternsToMatch[i]);
2415 std::cerr << "Unrecognized opcode '";
2417 std::cerr << "' on tree pattern '";
2418 std::cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
2419 std::cerr << "'!\n";
2425 // Loop over all of the case statements.
2426 for (std::map<Record*, std::vector<PatternToMatch*>,
2427 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2428 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2429 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2430 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2432 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
2434 // We want to emit all of the matching code now. However, we want to emit
2435 // the matches in order of minimal cost. Sort the patterns so the least
2436 // cost one is at the start.
2437 std::stable_sort(Patterns.begin(), Patterns.end(),
2438 PatternSortingPredicate(*this));
2440 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2441 EmitCodeForPattern(*Patterns[i], OS);
2442 OS << " break;\n\n";
2446 OS << " } // end of big switch.\n\n"
2447 << " std::cerr << \"Cannot yet select: \";\n"
2448 << " N.Val->dump();\n"
2449 << " std::cerr << '\\n';\n"
2454 void DAGISelEmitter::run(std::ostream &OS) {
2455 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2458 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2459 << "// *** instruction selector class. These functions are really "
2462 OS << "// Instance var to keep track of multiply used nodes that have \n"
2463 << "// already been selected.\n"
2464 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2467 ParseNodeTransforms(OS);
2468 ParseComplexPatterns();
2469 ParsePatternFragments(OS);
2470 ParseInstructions();
2473 // Generate variants. For example, commutative patterns can match
2474 // multiple ways. Add them to PatternsToMatch as well.
2478 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2479 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2480 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
2481 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
2485 // At this point, we have full information about the 'Patterns' we need to
2486 // parse, both implicitly from instructions as well as from explicit pattern
2487 // definitions. Emit the resultant instruction selector.
2488 EmitInstructionSelector(OS);
2490 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2491 E = PatternFragments.end(); I != E; ++I)
2493 PatternFragments.clear();
2495 Instructions.clear();