blob: 0faaa7284ac7c77d80c983e15a6c445718224575 [file] [log] [blame]
Chris Lattnerfe718932008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner6cefb772008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfe718932008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner6cefb772008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner93c7e412008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000016#include "Record.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/Support/Debug.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include "llvm/Support/Streams.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000020#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000021#include <algorithm>
Chris Lattner6cefb772008-01-05 22:25:12 +000022using namespace llvm;
23
24//===----------------------------------------------------------------------===//
25// Helpers for working with extended types.
26
27/// FilterVTs - Filter a list of VT's according to a predicate.
28///
29template<typename T>
30static std::vector<MVT::ValueType>
31FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
32 std::vector<MVT::ValueType> Result;
33 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
34 if (Filter(InVTs[i]))
35 Result.push_back(InVTs[i]);
36 return Result;
37}
38
39template<typename T>
40static std::vector<unsigned char>
41FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42 std::vector<unsigned char> Result;
43 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
44 if (Filter((MVT::ValueType)InVTs[i]))
45 Result.push_back(InVTs[i]);
46 return Result;
47}
48
49static std::vector<unsigned char>
50ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
51 std::vector<unsigned char> Result;
52 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53 Result.push_back(InVTs[i]);
54 return Result;
55}
56
57static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
58 const std::vector<unsigned char> &RHS) {
59 if (LHS.size() > RHS.size()) return false;
60 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
61 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
62 return false;
63 return true;
64}
65
66/// isExtIntegerVT - Return true if the specified extended value type vector
67/// contains isInt or an integer value type.
68namespace llvm {
69namespace MVT {
70bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
71 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
72 return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty());
73}
74
75/// isExtFloatingPointVT - Return true if the specified extended value type
76/// vector contains isFP or a FP value type.
77bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
78 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
79 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
80}
81} // end namespace MVT.
82} // end namespace llvm.
83
84//===----------------------------------------------------------------------===//
85// SDTypeConstraint implementation
86//
87
88SDTypeConstraint::SDTypeConstraint(Record *R) {
89 OperandNo = R->getValueAsInt("OperandNum");
90
91 if (R->isSubClassOf("SDTCisVT")) {
92 ConstraintType = SDTCisVT;
93 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
94 } else if (R->isSubClassOf("SDTCisPtrTy")) {
95 ConstraintType = SDTCisPtrTy;
96 } else if (R->isSubClassOf("SDTCisInt")) {
97 ConstraintType = SDTCisInt;
98 } else if (R->isSubClassOf("SDTCisFP")) {
99 ConstraintType = SDTCisFP;
100 } else if (R->isSubClassOf("SDTCisSameAs")) {
101 ConstraintType = SDTCisSameAs;
102 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
103 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
104 ConstraintType = SDTCisVTSmallerThanOp;
105 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
106 R->getValueAsInt("OtherOperandNum");
107 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
108 ConstraintType = SDTCisOpSmallerThanOp;
109 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
110 R->getValueAsInt("BigOperandNum");
111 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
112 ConstraintType = SDTCisIntVectorOfSameSize;
113 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
114 R->getValueAsInt("OtherOpNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000115 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
116 ConstraintType = SDTCisEltOfVec;
117 x.SDTCisEltOfVec_Info.OtherOperandNum =
118 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000119 } else {
120 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
121 exit(1);
122 }
123}
124
125/// getOperandNum - Return the node corresponding to operand #OpNo in tree
126/// N, which has NumResults results.
127TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
128 TreePatternNode *N,
129 unsigned NumResults) const {
130 assert(NumResults <= 1 &&
131 "We only work with nodes with zero or one result so far!");
132
133 if (OpNo >= (NumResults + N->getNumChildren())) {
134 cerr << "Invalid operand number " << OpNo << " ";
135 N->dump();
136 cerr << '\n';
137 exit(1);
138 }
139
140 if (OpNo < NumResults)
141 return N; // FIXME: need value #
142 else
143 return N->getChild(OpNo-NumResults);
144}
145
146/// ApplyTypeConstraint - Given a node in a pattern, apply this type
147/// constraint to the nodes operands. This returns true if it makes a
148/// change, false otherwise. If a type contradiction is found, throw an
149/// exception.
150bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
151 const SDNodeInfo &NodeInfo,
152 TreePattern &TP) const {
153 unsigned NumResults = NodeInfo.getNumResults();
154 assert(NumResults <= 1 &&
155 "We only work with nodes with zero or one result so far!");
156
157 // Check that the number of operands is sane. Negative operands -> varargs.
158 if (NodeInfo.getNumOperands() >= 0) {
159 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
160 TP.error(N->getOperator()->getName() + " node requires exactly " +
161 itostr(NodeInfo.getNumOperands()) + " operands!");
162 }
163
164 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
165
166 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
167
168 switch (ConstraintType) {
169 default: assert(0 && "Unknown constraint type!");
170 case SDTCisVT:
171 // Operand must be a particular type.
172 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
173 case SDTCisPtrTy: {
174 // Operand must be same as target pointer type.
175 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
176 }
177 case SDTCisInt: {
178 // If there is only one integer type supported, this must be it.
179 std::vector<MVT::ValueType> IntVTs =
180 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
181
182 // If we found exactly one supported integer type, apply it.
183 if (IntVTs.size() == 1)
184 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
185 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
186 }
187 case SDTCisFP: {
188 // If there is only one FP type supported, this must be it.
189 std::vector<MVT::ValueType> FPVTs =
190 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
191
192 // If we found exactly one supported FP type, apply it.
193 if (FPVTs.size() == 1)
194 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
195 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
196 }
197 case SDTCisSameAs: {
198 TreePatternNode *OtherNode =
199 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
200 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
201 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
202 }
203 case SDTCisVTSmallerThanOp: {
204 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
205 // have an integer type that is smaller than the VT.
206 if (!NodeToApply->isLeaf() ||
207 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
208 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
209 ->isSubClassOf("ValueType"))
210 TP.error(N->getOperator()->getName() + " expects a VT operand!");
211 MVT::ValueType VT =
212 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
213 if (!MVT::isInteger(VT))
214 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
215
216 TreePatternNode *OtherNode =
217 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
218
219 // It must be integer.
220 bool MadeChange = false;
221 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
222
223 // This code only handles nodes that have one type set. Assert here so
224 // that we can change this if we ever need to deal with multiple value
225 // types at this point.
226 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
227 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
228 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
229 return false;
230 }
231 case SDTCisOpSmallerThanOp: {
232 TreePatternNode *BigOperand =
233 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
234
235 // Both operands must be integer or FP, but we don't care which.
236 bool MadeChange = false;
237
238 // This code does not currently handle nodes which have multiple types,
239 // where some types are integer, and some are fp. Assert that this is not
240 // the case.
241 assert(!(MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
242 MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
243 !(MVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
244 MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
245 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
246 if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
247 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
248 else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
249 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
250 if (MVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
251 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
252 else if (MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
253 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
254
255 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
256
257 if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
258 VTs = FilterVTs(VTs, MVT::isInteger);
259 } else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
260 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
261 } else {
262 VTs.clear();
263 }
264
265 switch (VTs.size()) {
266 default: // Too many VT's to pick from.
267 case 0: break; // No info yet.
268 case 1:
269 // Only one VT of this flavor. Cannot ever satisify the constraints.
270 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
271 case 2:
272 // If we have exactly two possible types, the little operand must be the
273 // small one, the big operand should be the big one. Common with
274 // float/double for example.
275 assert(VTs[0] < VTs[1] && "Should be sorted!");
276 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
277 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
278 break;
279 }
280 return MadeChange;
281 }
282 case SDTCisIntVectorOfSameSize: {
283 TreePatternNode *OtherOperand =
284 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
285 N, NumResults);
286 if (OtherOperand->hasTypeSet()) {
287 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
288 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
289 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
290 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
291 return NodeToApply->UpdateNodeType(IVT, TP);
292 }
293 return false;
294 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000295 case SDTCisEltOfVec: {
296 TreePatternNode *OtherOperand =
297 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
298 N, NumResults);
299 if (OtherOperand->hasTypeSet()) {
300 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
301 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
302 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
303 IVT = MVT::getVectorElementType(IVT);
304 return NodeToApply->UpdateNodeType(IVT, TP);
305 }
306 return false;
307 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000308 }
309 return false;
310}
311
312//===----------------------------------------------------------------------===//
313// SDNodeInfo implementation
314//
315SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
316 EnumName = R->getValueAsString("Opcode");
317 SDClassName = R->getValueAsString("SDClass");
318 Record *TypeProfile = R->getValueAsDef("TypeProfile");
319 NumResults = TypeProfile->getValueAsInt("NumResults");
320 NumOperands = TypeProfile->getValueAsInt("NumOperands");
321
322 // Parse the properties.
323 Properties = 0;
324 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
325 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
326 if (PropList[i]->getName() == "SDNPCommutative") {
327 Properties |= 1 << SDNPCommutative;
328 } else if (PropList[i]->getName() == "SDNPAssociative") {
329 Properties |= 1 << SDNPAssociative;
330 } else if (PropList[i]->getName() == "SDNPHasChain") {
331 Properties |= 1 << SDNPHasChain;
332 } else if (PropList[i]->getName() == "SDNPOutFlag") {
333 Properties |= 1 << SDNPOutFlag;
334 } else if (PropList[i]->getName() == "SDNPInFlag") {
335 Properties |= 1 << SDNPInFlag;
336 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
337 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000338 } else if (PropList[i]->getName() == "SDNPMayStore") {
339 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000340 } else if (PropList[i]->getName() == "SDNPMayLoad") {
341 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000342 } else if (PropList[i]->getName() == "SDNPSideEffect") {
343 Properties |= 1 << SDNPSideEffect;
Chris Lattner6cefb772008-01-05 22:25:12 +0000344 } else {
345 cerr << "Unknown SD Node property '" << PropList[i]->getName()
346 << "' on node '" << R->getName() << "'!\n";
347 exit(1);
348 }
349 }
350
351
352 // Parse the type constraints.
353 std::vector<Record*> ConstraintList =
354 TypeProfile->getValueAsListOfDefs("Constraints");
355 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
356}
357
358//===----------------------------------------------------------------------===//
359// TreePatternNode implementation
360//
361
362TreePatternNode::~TreePatternNode() {
363#if 0 // FIXME: implement refcounted tree nodes!
364 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
365 delete getChild(i);
366#endif
367}
368
369/// UpdateNodeType - Set the node type of N to VT if VT contains
370/// information. If N already contains a conflicting type, then throw an
371/// exception. This returns true if any information was updated.
372///
373bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
374 TreePattern &TP) {
375 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
376
377 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
378 return false;
379 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
380 setTypes(ExtVTs);
381 return true;
382 }
383
384 if (getExtTypeNum(0) == MVT::iPTR) {
385 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
386 return false;
387 if (MVT::isExtIntegerInVTs(ExtVTs)) {
388 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
389 if (FVTs.size()) {
390 setTypes(ExtVTs);
391 return true;
392 }
393 }
394 }
395
396 if (ExtVTs[0] == MVT::isInt && MVT::isExtIntegerInVTs(getExtTypes())) {
397 assert(hasTypeSet() && "should be handled above!");
398 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
399 if (getExtTypes() == FVTs)
400 return false;
401 setTypes(FVTs);
402 return true;
403 }
404 if (ExtVTs[0] == MVT::iPTR && MVT::isExtIntegerInVTs(getExtTypes())) {
405 //assert(hasTypeSet() && "should be handled above!");
406 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
407 if (getExtTypes() == FVTs)
408 return false;
409 if (FVTs.size()) {
410 setTypes(FVTs);
411 return true;
412 }
413 }
414 if (ExtVTs[0] == MVT::isFP && MVT::isExtFloatingPointInVTs(getExtTypes())) {
415 assert(hasTypeSet() && "should be handled above!");
416 std::vector<unsigned char> FVTs =
417 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
418 if (getExtTypes() == FVTs)
419 return false;
420 setTypes(FVTs);
421 return true;
422 }
423
424 // If we know this is an int or fp type, and we are told it is a specific one,
425 // take the advice.
426 //
427 // Similarly, we should probably set the type here to the intersection of
428 // {isInt|isFP} and ExtVTs
429 if ((getExtTypeNum(0) == MVT::isInt && MVT::isExtIntegerInVTs(ExtVTs)) ||
430 (getExtTypeNum(0) == MVT::isFP && MVT::isExtFloatingPointInVTs(ExtVTs))){
431 setTypes(ExtVTs);
432 return true;
433 }
434 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
435 setTypes(ExtVTs);
436 return true;
437 }
438
439 if (isLeaf()) {
440 dump();
441 cerr << " ";
442 TP.error("Type inference contradiction found in node!");
443 } else {
444 TP.error("Type inference contradiction found in node " +
445 getOperator()->getName() + "!");
446 }
447 return true; // unreachable
448}
449
450
451void TreePatternNode::print(std::ostream &OS) const {
452 if (isLeaf()) {
453 OS << *getLeafValue();
454 } else {
455 OS << "(" << getOperator()->getName();
456 }
457
458 // FIXME: At some point we should handle printing all the value types for
459 // nodes that are multiply typed.
460 switch (getExtTypeNum(0)) {
461 case MVT::Other: OS << ":Other"; break;
462 case MVT::isInt: OS << ":isInt"; break;
463 case MVT::isFP : OS << ":isFP"; break;
464 case MVT::isUnknown: ; /*OS << ":?";*/ break;
465 case MVT::iPTR: OS << ":iPTR"; break;
466 default: {
467 std::string VTName = llvm::getName(getTypeNum(0));
468 // Strip off MVT:: prefix if present.
469 if (VTName.substr(0,5) == "MVT::")
470 VTName = VTName.substr(5);
471 OS << ":" << VTName;
472 break;
473 }
474 }
475
476 if (!isLeaf()) {
477 if (getNumChildren() != 0) {
478 OS << " ";
479 getChild(0)->print(OS);
480 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
481 OS << ", ";
482 getChild(i)->print(OS);
483 }
484 }
485 OS << ")";
486 }
487
488 if (!PredicateFn.empty())
489 OS << "<<P:" << PredicateFn << ">>";
490 if (TransformFn)
491 OS << "<<X:" << TransformFn->getName() << ">>";
492 if (!getName().empty())
493 OS << ":$" << getName();
494
495}
496void TreePatternNode::dump() const {
497 print(*cerr.stream());
498}
499
500/// isIsomorphicTo - Return true if this node is recursively isomorphic to
501/// the specified node. For this comparison, all of the state of the node
502/// is considered, except for the assigned name. Nodes with differing names
503/// that are otherwise identical are considered isomorphic.
504bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
505 if (N == this) return true;
506 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
507 getPredicateFn() != N->getPredicateFn() ||
508 getTransformFn() != N->getTransformFn())
509 return false;
510
511 if (isLeaf()) {
512 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
513 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
514 return DI->getDef() == NDI->getDef();
515 return getLeafValue() == N->getLeafValue();
516 }
517
518 if (N->getOperator() != getOperator() ||
519 N->getNumChildren() != getNumChildren()) return false;
520 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
521 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
522 return false;
523 return true;
524}
525
526/// clone - Make a copy of this tree and all of its children.
527///
528TreePatternNode *TreePatternNode::clone() const {
529 TreePatternNode *New;
530 if (isLeaf()) {
531 New = new TreePatternNode(getLeafValue());
532 } else {
533 std::vector<TreePatternNode*> CChildren;
534 CChildren.reserve(Children.size());
535 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
536 CChildren.push_back(getChild(i)->clone());
537 New = new TreePatternNode(getOperator(), CChildren);
538 }
539 New->setName(getName());
540 New->setTypes(getExtTypes());
541 New->setPredicateFn(getPredicateFn());
542 New->setTransformFn(getTransformFn());
543 return New;
544}
545
546/// SubstituteFormalArguments - Replace the formal arguments in this tree
547/// with actual values specified by ArgMap.
548void TreePatternNode::
549SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
550 if (isLeaf()) return;
551
552 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
553 TreePatternNode *Child = getChild(i);
554 if (Child->isLeaf()) {
555 Init *Val = Child->getLeafValue();
556 if (dynamic_cast<DefInit*>(Val) &&
557 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
558 // We found a use of a formal argument, replace it with its value.
559 Child = ArgMap[Child->getName()];
560 assert(Child && "Couldn't find formal argument!");
561 setChild(i, Child);
562 }
563 } else {
564 getChild(i)->SubstituteFormalArguments(ArgMap);
565 }
566 }
567}
568
569
570/// InlinePatternFragments - If this pattern refers to any pattern
571/// fragments, inline them into place, giving us a pattern without any
572/// PatFrag references.
573TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
574 if (isLeaf()) return this; // nothing to do.
575 Record *Op = getOperator();
576
577 if (!Op->isSubClassOf("PatFrag")) {
578 // Just recursively inline children nodes.
579 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
580 setChild(i, getChild(i)->InlinePatternFragments(TP));
581 return this;
582 }
583
584 // Otherwise, we found a reference to a fragment. First, look up its
585 // TreePattern record.
586 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
587
588 // Verify that we are passing the right number of operands.
589 if (Frag->getNumArgs() != Children.size())
590 TP.error("'" + Op->getName() + "' fragment requires " +
591 utostr(Frag->getNumArgs()) + " operands!");
592
593 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
594
595 // Resolve formal arguments to their actual value.
596 if (Frag->getNumArgs()) {
597 // Compute the map of formal to actual arguments.
598 std::map<std::string, TreePatternNode*> ArgMap;
599 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
600 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
601
602 FragTree->SubstituteFormalArguments(ArgMap);
603 }
604
605 FragTree->setName(getName());
606 FragTree->UpdateNodeType(getExtTypes(), TP);
607
608 // Get a new copy of this fragment to stitch into here.
609 //delete this; // FIXME: implement refcounting!
610 return FragTree;
611}
612
613/// getImplicitType - Check to see if the specified record has an implicit
614/// type which should be applied to it. This infer the type of register
615/// references from the register file information, for example.
616///
617static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
618 TreePattern &TP) {
619 // Some common return values
620 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
621 std::vector<unsigned char> Other(1, MVT::Other);
622
623 // Check to see if this is a register or a register class...
624 if (R->isSubClassOf("RegisterClass")) {
625 if (NotRegisters)
626 return Unknown;
627 const CodeGenRegisterClass &RC =
628 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
629 return ConvertVTs(RC.getValueTypes());
630 } else if (R->isSubClassOf("PatFrag")) {
631 // Pattern fragment types will be resolved when they are inlined.
632 return Unknown;
633 } else if (R->isSubClassOf("Register")) {
634 if (NotRegisters)
635 return Unknown;
636 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
637 return T.getRegisterVTs(R);
638 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
639 // Using a VTSDNode or CondCodeSDNode.
640 return Other;
641 } else if (R->isSubClassOf("ComplexPattern")) {
642 if (NotRegisters)
643 return Unknown;
644 std::vector<unsigned char>
645 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
646 return ComplexPat;
647 } else if (R->getName() == "ptr_rc") {
648 Other[0] = MVT::iPTR;
649 return Other;
650 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
651 R->getName() == "zero_reg") {
652 // Placeholder.
653 return Unknown;
654 }
655
656 TP.error("Unknown node flavor used in pattern: " + R->getName());
657 return Other;
658}
659
Chris Lattnere67bde52008-01-06 05:36:50 +0000660
661/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
662/// CodeGenIntrinsic information for it, otherwise return a null pointer.
663const CodeGenIntrinsic *TreePatternNode::
664getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
665 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
666 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
667 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
668 return 0;
669
670 unsigned IID =
671 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
672 return &CDP.getIntrinsicInfo(IID);
673}
674
675
Chris Lattner6cefb772008-01-05 22:25:12 +0000676/// ApplyTypeConstraints - Apply all of the type constraints relevent to
677/// this node and its children in the tree. This returns true if it makes a
678/// change, false otherwise. If a type contradiction is found, throw an
679/// exception.
680bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +0000681 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +0000682 if (isLeaf()) {
683 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
684 // If it's a regclass or something else known, include the type.
685 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
686 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
687 // Int inits are always integers. :)
688 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
689
690 if (hasTypeSet()) {
691 // At some point, it may make sense for this tree pattern to have
692 // multiple types. Assert here that it does not, so we revisit this
693 // code when appropriate.
694 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
695 MVT::ValueType VT = getTypeNum(0);
696 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
697 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
698
699 VT = getTypeNum(0);
700 if (VT != MVT::iPTR) {
701 unsigned Size = MVT::getSizeInBits(VT);
702 // Make sure that the value is representable for this type.
703 if (Size < 32) {
704 int Val = (II->getValue() << (32-Size)) >> (32-Size);
Scott Michel0123b7d2008-02-15 23:05:48 +0000705 if (Val != II->getValue()) {
706 // If sign-extended doesn't fit, does it fit as unsigned?
707 unsigned ValueMask = unsigned(MVT::getIntVTBitMask(VT));
708 unsigned UnsignedVal = unsigned(II->getValue());
709
710 if ((ValueMask & UnsignedVal) != UnsignedVal) {
711 TP.error("Integer value '" + itostr(II->getValue())+
712 "' is out of range for type '" +
713 getEnumName(getTypeNum(0)) + "'!");
714 }
715 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000716 }
717 }
718 }
719
720 return MadeChange;
721 }
722 return false;
723 }
724
725 // special handling for set, which isn't really an SDNode.
726 if (getOperator()->getName() == "set") {
727 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
728 unsigned NC = getNumChildren();
729 bool MadeChange = false;
730 for (unsigned i = 0; i < NC-1; ++i) {
731 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
732 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
733
734 // Types of operands must match.
735 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
736 TP);
737 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
738 TP);
739 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
740 }
741 return MadeChange;
742 } else if (getOperator()->getName() == "implicit" ||
743 getOperator()->getName() == "parallel") {
744 bool MadeChange = false;
745 for (unsigned i = 0; i < getNumChildren(); ++i)
746 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
747 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
748 return MadeChange;
Chris Lattnere67bde52008-01-06 05:36:50 +0000749 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000750 bool MadeChange = false;
751
752 // Apply the result type to the node.
Chris Lattnere67bde52008-01-06 05:36:50 +0000753 MadeChange = UpdateNodeType(Int->ArgVTs[0], TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000754
Chris Lattnere67bde52008-01-06 05:36:50 +0000755 if (getNumChildren() != Int->ArgVTs.size())
756 TP.error("Intrinsic '" + Int->Name + "' expects " +
757 utostr(Int->ArgVTs.size()-1) + " operands, not " +
Chris Lattner6cefb772008-01-05 22:25:12 +0000758 utostr(getNumChildren()-1) + " operands!");
759
760 // Apply type info to the intrinsic ID.
761 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
762
763 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
Chris Lattnere67bde52008-01-06 05:36:50 +0000764 MVT::ValueType OpVT = Int->ArgVTs[i];
Chris Lattner6cefb772008-01-05 22:25:12 +0000765 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
766 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
767 }
768 return MadeChange;
769 } else if (getOperator()->isSubClassOf("SDNode")) {
770 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
771
772 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
773 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
774 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
775 // Branch, etc. do not produce results and top-level forms in instr pattern
776 // must have void types.
777 if (NI.getNumResults() == 0)
778 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
779
780 // If this is a vector_shuffle operation, apply types to the build_vector
781 // operation. The types of the integers don't matter, but this ensures they
782 // won't get checked.
783 if (getOperator()->getName() == "vector_shuffle" &&
784 getChild(2)->getOperator()->getName() == "build_vector") {
785 TreePatternNode *BV = getChild(2);
786 const std::vector<MVT::ValueType> &LegalVTs
787 = CDP.getTargetInfo().getLegalValueTypes();
788 MVT::ValueType LegalIntVT = MVT::Other;
789 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
790 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
791 LegalIntVT = LegalVTs[i];
792 break;
793 }
794 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
795
796 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
797 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
798 }
799 return MadeChange;
800 } else if (getOperator()->isSubClassOf("Instruction")) {
801 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
802 bool MadeChange = false;
803 unsigned NumResults = Inst.getNumResults();
804
805 assert(NumResults <= 1 &&
806 "Only supports zero or one result instrs!");
807
808 CodeGenInstruction &InstInfo =
809 CDP.getTargetInfo().getInstruction(getOperator()->getName());
810 // Apply the result type to the node
811 if (NumResults == 0 || InstInfo.NumDefs == 0) {
812 MadeChange = UpdateNodeType(MVT::isVoid, TP);
813 } else {
814 Record *ResultNode = Inst.getResult(0);
815
816 if (ResultNode->getName() == "ptr_rc") {
817 std::vector<unsigned char> VT;
818 VT.push_back(MVT::iPTR);
819 MadeChange = UpdateNodeType(VT, TP);
820 } else {
821 assert(ResultNode->isSubClassOf("RegisterClass") &&
822 "Operands should be register classes!");
823
824 const CodeGenRegisterClass &RC =
825 CDP.getTargetInfo().getRegisterClass(ResultNode);
826 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
827 }
828 }
829
830 unsigned ChildNo = 0;
831 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
832 Record *OperandNode = Inst.getOperand(i);
833
834 // If the instruction expects a predicate or optional def operand, we
835 // codegen this by setting the operand to it's default value if it has a
836 // non-empty DefaultOps field.
837 if ((OperandNode->isSubClassOf("PredicateOperand") ||
838 OperandNode->isSubClassOf("OptionalDefOperand")) &&
839 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
840 continue;
841
842 // Verify that we didn't run out of provided operands.
843 if (ChildNo >= getNumChildren())
844 TP.error("Instruction '" + getOperator()->getName() +
845 "' expects more operands than were provided.");
846
847 MVT::ValueType VT;
848 TreePatternNode *Child = getChild(ChildNo++);
849 if (OperandNode->isSubClassOf("RegisterClass")) {
850 const CodeGenRegisterClass &RC =
851 CDP.getTargetInfo().getRegisterClass(OperandNode);
852 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
853 } else if (OperandNode->isSubClassOf("Operand")) {
854 VT = getValueType(OperandNode->getValueAsDef("Type"));
855 MadeChange |= Child->UpdateNodeType(VT, TP);
856 } else if (OperandNode->getName() == "ptr_rc") {
857 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
858 } else {
859 assert(0 && "Unknown operand type!");
860 abort();
861 }
862 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
863 }
864
865 if (ChildNo != getNumChildren())
866 TP.error("Instruction '" + getOperator()->getName() +
867 "' was provided too many operands!");
868
869 return MadeChange;
870 } else {
871 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
872
873 // Node transforms always take one operand.
874 if (getNumChildren() != 1)
875 TP.error("Node transform '" + getOperator()->getName() +
876 "' requires one operand!");
877
878 // If either the output or input of the xform does not have exact
879 // type info. We assume they must be the same. Otherwise, it is perfectly
880 // legal to transform from one type to a completely different type.
881 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
882 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
883 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
884 return MadeChange;
885 }
886 return false;
887 }
888}
889
890/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
891/// RHS of a commutative operation, not the on LHS.
892static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
893 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
894 return true;
895 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
896 return true;
897 return false;
898}
899
900
901/// canPatternMatch - If it is impossible for this pattern to match on this
902/// target, fill in Reason and return false. Otherwise, return true. This is
903/// used as a santity check for .td files (to prevent people from writing stuff
904/// that can never possibly work), and to prevent the pattern permuter from
905/// generating stuff that is useless.
906bool TreePatternNode::canPatternMatch(std::string &Reason,
Chris Lattnerfe718932008-01-06 01:10:31 +0000907 CodeGenDAGPatterns &CDP){
Chris Lattner6cefb772008-01-05 22:25:12 +0000908 if (isLeaf()) return true;
909
910 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
911 if (!getChild(i)->canPatternMatch(Reason, CDP))
912 return false;
913
914 // If this is an intrinsic, handle cases that would make it not match. For
915 // example, if an operand is required to be an immediate.
916 if (getOperator()->isSubClassOf("Intrinsic")) {
917 // TODO:
918 return true;
919 }
920
921 // If this node is a commutative operator, check that the LHS isn't an
922 // immediate.
923 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
924 if (NodeInfo.hasProperty(SDNPCommutative)) {
925 // Scan all of the operands of the node and make sure that only the last one
926 // is a constant node, unless the RHS also is.
927 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
928 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
929 if (OnlyOnRHSOfCommutative(getChild(i))) {
930 Reason="Immediate value must be on the RHS of commutative operators!";
931 return false;
932 }
933 }
934 }
935
936 return true;
937}
938
939//===----------------------------------------------------------------------===//
940// TreePattern implementation
941//
942
943TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +0000944 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +0000945 isInputPattern = isInput;
946 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
947 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
948}
949
950TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +0000951 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +0000952 isInputPattern = isInput;
953 Trees.push_back(ParseTreePattern(Pat));
954}
955
956TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +0000957 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +0000958 isInputPattern = isInput;
959 Trees.push_back(Pat);
960}
961
962
963
964void TreePattern::error(const std::string &Msg) const {
965 dump();
966 throw "In " + TheRecord->getName() + ": " + Msg;
967}
968
969TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
970 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
971 if (!OpDef) error("Pattern has unexpected operator type!");
972 Record *Operator = OpDef->getDef();
973
974 if (Operator->isSubClassOf("ValueType")) {
975 // If the operator is a ValueType, then this must be "type cast" of a leaf
976 // node.
977 if (Dag->getNumArgs() != 1)
978 error("Type cast only takes one operand!");
979
980 Init *Arg = Dag->getArg(0);
981 TreePatternNode *New;
982 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
983 Record *R = DI->getDef();
984 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
985 Dag->setArg(0, new DagInit(DI,
986 std::vector<std::pair<Init*, std::string> >()));
987 return ParseTreePattern(Dag);
988 }
989 New = new TreePatternNode(DI);
990 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
991 New = ParseTreePattern(DI);
992 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
993 New = new TreePatternNode(II);
994 if (!Dag->getArgName(0).empty())
995 error("Constant int argument should not have a name!");
996 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
997 // Turn this into an IntInit.
998 Init *II = BI->convertInitializerTo(new IntRecTy());
999 if (II == 0 || !dynamic_cast<IntInit*>(II))
1000 error("Bits value must be constants!");
1001
1002 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1003 if (!Dag->getArgName(0).empty())
1004 error("Constant int argument should not have a name!");
1005 } else {
1006 Arg->dump();
1007 error("Unknown leaf value for tree pattern!");
1008 return 0;
1009 }
1010
1011 // Apply the type cast.
1012 New->UpdateNodeType(getValueType(Operator), *this);
1013 New->setName(Dag->getArgName(0));
1014 return New;
1015 }
1016
1017 // Verify that this is something that makes sense for an operator.
1018 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
1019 !Operator->isSubClassOf("Instruction") &&
1020 !Operator->isSubClassOf("SDNodeXForm") &&
1021 !Operator->isSubClassOf("Intrinsic") &&
1022 Operator->getName() != "set" &&
1023 Operator->getName() != "implicit" &&
1024 Operator->getName() != "parallel")
1025 error("Unrecognized node '" + Operator->getName() + "'!");
1026
1027 // Check to see if this is something that is illegal in an input pattern.
1028 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1029 Operator->isSubClassOf("SDNodeXForm")))
1030 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1031
1032 std::vector<TreePatternNode*> Children;
1033
1034 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1035 Init *Arg = Dag->getArg(i);
1036 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1037 Children.push_back(ParseTreePattern(DI));
1038 if (Children.back()->getName().empty())
1039 Children.back()->setName(Dag->getArgName(i));
1040 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1041 Record *R = DefI->getDef();
1042 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1043 // TreePatternNode if its own.
1044 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1045 Dag->setArg(i, new DagInit(DefI,
1046 std::vector<std::pair<Init*, std::string> >()));
1047 --i; // Revisit this node...
1048 } else {
1049 TreePatternNode *Node = new TreePatternNode(DefI);
1050 Node->setName(Dag->getArgName(i));
1051 Children.push_back(Node);
1052
1053 // Input argument?
1054 if (R->getName() == "node") {
1055 if (Dag->getArgName(i).empty())
1056 error("'node' argument requires a name to match with operand list");
1057 Args.push_back(Dag->getArgName(i));
1058 }
1059 }
1060 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1061 TreePatternNode *Node = new TreePatternNode(II);
1062 if (!Dag->getArgName(i).empty())
1063 error("Constant int argument should not have a name!");
1064 Children.push_back(Node);
1065 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1066 // Turn this into an IntInit.
1067 Init *II = BI->convertInitializerTo(new IntRecTy());
1068 if (II == 0 || !dynamic_cast<IntInit*>(II))
1069 error("Bits value must be constants!");
1070
1071 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1072 if (!Dag->getArgName(i).empty())
1073 error("Constant int argument should not have a name!");
1074 Children.push_back(Node);
1075 } else {
1076 cerr << '"';
1077 Arg->dump();
1078 cerr << "\": ";
1079 error("Unknown leaf value for tree pattern!");
1080 }
1081 }
1082
1083 // If the operator is an intrinsic, then this is just syntactic sugar for for
1084 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1085 // convert the intrinsic name to a number.
1086 if (Operator->isSubClassOf("Intrinsic")) {
1087 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1088 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1089
1090 // If this intrinsic returns void, it must have side-effects and thus a
1091 // chain.
1092 if (Int.ArgVTs[0] == MVT::isVoid) {
1093 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1094 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1095 // Has side-effects, requires chain.
1096 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1097 } else {
1098 // Otherwise, no chain.
1099 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1100 }
1101
1102 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1103 Children.insert(Children.begin(), IIDNode);
1104 }
1105
1106 return new TreePatternNode(Operator, Children);
1107}
1108
1109/// InferAllTypes - Infer/propagate as many types throughout the expression
1110/// patterns as possible. Return true if all types are infered, false
1111/// otherwise. Throw an exception if a type contradiction is found.
1112bool TreePattern::InferAllTypes() {
1113 bool MadeChange = true;
1114 while (MadeChange) {
1115 MadeChange = false;
1116 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1117 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1118 }
1119
1120 bool HasUnresolvedTypes = false;
1121 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1122 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1123 return !HasUnresolvedTypes;
1124}
1125
1126void TreePattern::print(std::ostream &OS) const {
1127 OS << getRecord()->getName();
1128 if (!Args.empty()) {
1129 OS << "(" << Args[0];
1130 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1131 OS << ", " << Args[i];
1132 OS << ")";
1133 }
1134 OS << ": ";
1135
1136 if (Trees.size() > 1)
1137 OS << "[\n";
1138 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1139 OS << "\t";
1140 Trees[i]->print(OS);
1141 OS << "\n";
1142 }
1143
1144 if (Trees.size() > 1)
1145 OS << "]\n";
1146}
1147
1148void TreePattern::dump() const { print(*cerr.stream()); }
1149
1150//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001151// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001152//
1153
1154// FIXME: REMOVE OSTREAM ARGUMENT
Chris Lattnerfe718932008-01-06 01:10:31 +00001155CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001156 Intrinsics = LoadIntrinsics(Records);
1157 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001158 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001159 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001160 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001161 ParseDefaultOperands();
1162 ParseInstructions();
1163 ParsePatterns();
1164
1165 // Generate variants. For example, commutative patterns can match
1166 // multiple ways. Add them to PatternsToMatch as well.
1167 GenerateVariants();
1168}
1169
Chris Lattnerfe718932008-01-06 01:10:31 +00001170CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001171 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1172 E = PatternFragments.end(); I != E; ++I)
1173 delete I->second;
1174}
1175
1176
Chris Lattnerfe718932008-01-06 01:10:31 +00001177Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001178 Record *N = Records.getDef(Name);
1179 if (!N || !N->isSubClassOf("SDNode")) {
1180 cerr << "Error getting SDNode '" << Name << "'!\n";
1181 exit(1);
1182 }
1183 return N;
1184}
1185
1186// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001187void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001188 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1189 while (!Nodes.empty()) {
1190 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1191 Nodes.pop_back();
1192 }
1193
1194 // Get the buildin intrinsic nodes.
1195 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1196 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1197 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1198}
1199
1200/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1201/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001202void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001203 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1204 while (!Xforms.empty()) {
1205 Record *XFormNode = Xforms.back();
1206 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1207 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001208 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001209
1210 Xforms.pop_back();
1211 }
1212}
1213
Chris Lattnerfe718932008-01-06 01:10:31 +00001214void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001215 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1216 while (!AMs.empty()) {
1217 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1218 AMs.pop_back();
1219 }
1220}
1221
1222
1223/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1224/// file, building up the PatternFragments map. After we've collected them all,
1225/// inline fragments together as necessary, so that there are no references left
1226/// inside a pattern fragment to a pattern fragment.
1227///
Chris Lattnerfe718932008-01-06 01:10:31 +00001228void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001229 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1230
Chris Lattnerdc32f982008-01-05 22:43:57 +00001231 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001232 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1233 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1234 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1235 PatternFragments[Fragments[i]] = P;
1236
Chris Lattnerdc32f982008-01-05 22:43:57 +00001237 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001238 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001239 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001240
Chris Lattnerdc32f982008-01-05 22:43:57 +00001241 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001242 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1243
1244 // Parse the operands list.
1245 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1246 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1247 // Special cases: ops == outs == ins. Different names are used to
1248 // improve readibility.
1249 if (!OpsOp ||
1250 (OpsOp->getDef()->getName() != "ops" &&
1251 OpsOp->getDef()->getName() != "outs" &&
1252 OpsOp->getDef()->getName() != "ins"))
1253 P->error("Operands list should start with '(ops ... '!");
1254
1255 // Copy over the arguments.
1256 Args.clear();
1257 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1258 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1259 static_cast<DefInit*>(OpsList->getArg(j))->
1260 getDef()->getName() != "node")
1261 P->error("Operands list should all be 'node' values.");
1262 if (OpsList->getArgName(j).empty())
1263 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001264 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001265 P->error("'" + OpsList->getArgName(j) +
1266 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001267 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001268 Args.push_back(OpsList->getArgName(j));
1269 }
1270
Chris Lattnerdc32f982008-01-05 22:43:57 +00001271 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001272 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001273 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001274
Chris Lattnerdc32f982008-01-05 22:43:57 +00001275 // If there is a code init for this fragment, keep track of the fact that
1276 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001277 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001278 if (!Code.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001279 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001280
1281 // If there is a node transformation corresponding to this, keep track of
1282 // it.
1283 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1284 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1285 P->getOnlyTree()->setTransformFn(Transform);
1286 }
1287
Chris Lattner6cefb772008-01-05 22:25:12 +00001288 // Now that we've parsed all of the tree fragments, do a closure on them so
1289 // that there are not references to PatFrags left inside of them.
1290 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1291 E = PatternFragments.end(); I != E; ++I) {
1292 TreePattern *ThePat = I->second;
1293 ThePat->InlinePatternFragments();
1294
1295 // Infer as many types as possible. Don't worry about it if we don't infer
1296 // all of them, some may depend on the inputs of the pattern.
1297 try {
1298 ThePat->InferAllTypes();
1299 } catch (...) {
1300 // If this pattern fragment is not supported by this target (no types can
1301 // satisfy its constraints), just ignore it. If the bogus pattern is
1302 // actually used by instructions, the type consistency error will be
1303 // reported there.
1304 }
1305
1306 // If debugging, print out the pattern fragment result.
1307 DEBUG(ThePat->dump());
1308 }
1309}
1310
Chris Lattnerfe718932008-01-06 01:10:31 +00001311void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001312 std::vector<Record*> DefaultOps[2];
1313 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1314 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1315
1316 // Find some SDNode.
1317 assert(!SDNodes.empty() && "No SDNodes parsed?");
1318 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1319
1320 for (unsigned iter = 0; iter != 2; ++iter) {
1321 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1322 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1323
1324 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1325 // SomeSDnode so that we can parse this.
1326 std::vector<std::pair<Init*, std::string> > Ops;
1327 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1328 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1329 DefaultInfo->getArgName(op)));
1330 DagInit *DI = new DagInit(SomeSDNode, Ops);
1331
1332 // Create a TreePattern to parse this.
1333 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1334 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1335
1336 // Copy the operands over into a DAGDefaultOperand.
1337 DAGDefaultOperand DefaultOpInfo;
1338
1339 TreePatternNode *T = P.getTree(0);
1340 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1341 TreePatternNode *TPN = T->getChild(op);
1342 while (TPN->ApplyTypeConstraints(P, false))
1343 /* Resolve all types */;
1344
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001345 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001346 if (iter == 0)
1347 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1348 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1349 else
1350 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1351 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001352 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001353 DefaultOpInfo.DefaultOps.push_back(TPN);
1354 }
1355
1356 // Insert it into the DefaultOperands map so we can find it later.
1357 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1358 }
1359 }
1360}
1361
1362/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1363/// instruction input. Return true if this is a real use.
1364static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1365 std::map<std::string, TreePatternNode*> &InstInputs,
1366 std::vector<Record*> &InstImpInputs) {
1367 // No name -> not interesting.
1368 if (Pat->getName().empty()) {
1369 if (Pat->isLeaf()) {
1370 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1371 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1372 I->error("Input " + DI->getDef()->getName() + " must be named!");
1373 else if (DI && DI->getDef()->isSubClassOf("Register"))
1374 InstImpInputs.push_back(DI->getDef());
1375 ;
1376 }
1377 return false;
1378 }
1379
1380 Record *Rec;
1381 if (Pat->isLeaf()) {
1382 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1383 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1384 Rec = DI->getDef();
1385 } else {
1386 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1387 Rec = Pat->getOperator();
1388 }
1389
1390 // SRCVALUE nodes are ignored.
1391 if (Rec->getName() == "srcvalue")
1392 return false;
1393
1394 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1395 if (!Slot) {
1396 Slot = Pat;
1397 } else {
1398 Record *SlotRec;
1399 if (Slot->isLeaf()) {
1400 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1401 } else {
1402 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1403 SlotRec = Slot->getOperator();
1404 }
1405
1406 // Ensure that the inputs agree if we've already seen this input.
1407 if (Rec != SlotRec)
1408 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1409 if (Slot->getExtTypes() != Pat->getExtTypes())
1410 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1411 }
1412 return true;
1413}
1414
1415/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1416/// part of "I", the instruction), computing the set of inputs and outputs of
1417/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001418void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001419FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1420 std::map<std::string, TreePatternNode*> &InstInputs,
1421 std::map<std::string, TreePatternNode*>&InstResults,
1422 std::vector<Record*> &InstImpInputs,
1423 std::vector<Record*> &InstImpResults) {
1424 if (Pat->isLeaf()) {
1425 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1426 if (!isUse && Pat->getTransformFn())
1427 I->error("Cannot specify a transform function for a non-input value!");
1428 return;
1429 } else if (Pat->getOperator()->getName() == "implicit") {
1430 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1431 TreePatternNode *Dest = Pat->getChild(i);
1432 if (!Dest->isLeaf())
1433 I->error("implicitly defined value should be a register!");
1434
1435 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1436 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1437 I->error("implicitly defined value should be a register!");
1438 InstImpResults.push_back(Val->getDef());
1439 }
1440 return;
1441 } else if (Pat->getOperator()->getName() != "set") {
1442 // If this is not a set, verify that the children nodes are not void typed,
1443 // and recurse.
1444 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1445 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1446 I->error("Cannot have void nodes inside of patterns!");
1447 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1448 InstImpInputs, InstImpResults);
1449 }
1450
1451 // If this is a non-leaf node with no children, treat it basically as if
1452 // it were a leaf. This handles nodes like (imm).
1453 bool isUse = false;
1454 if (Pat->getNumChildren() == 0)
1455 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1456
1457 if (!isUse && Pat->getTransformFn())
1458 I->error("Cannot specify a transform function for a non-input value!");
1459 return;
1460 }
1461
1462 // Otherwise, this is a set, validate and collect instruction results.
1463 if (Pat->getNumChildren() == 0)
1464 I->error("set requires operands!");
1465
1466 if (Pat->getTransformFn())
1467 I->error("Cannot specify a transform function on a set node!");
1468
1469 // Check the set destinations.
1470 unsigned NumDests = Pat->getNumChildren()-1;
1471 for (unsigned i = 0; i != NumDests; ++i) {
1472 TreePatternNode *Dest = Pat->getChild(i);
1473 if (!Dest->isLeaf())
1474 I->error("set destination should be a register!");
1475
1476 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1477 if (!Val)
1478 I->error("set destination should be a register!");
1479
1480 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1481 Val->getDef()->getName() == "ptr_rc") {
1482 if (Dest->getName().empty())
1483 I->error("set destination must have a name!");
1484 if (InstResults.count(Dest->getName()))
1485 I->error("cannot set '" + Dest->getName() +"' multiple times");
1486 InstResults[Dest->getName()] = Dest;
1487 } else if (Val->getDef()->isSubClassOf("Register")) {
1488 InstImpResults.push_back(Val->getDef());
1489 } else {
1490 I->error("set destination should be a register!");
1491 }
1492 }
1493
1494 // Verify and collect info from the computation.
1495 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1496 InstInputs, InstResults,
1497 InstImpInputs, InstImpResults);
1498}
1499
1500/// ParseInstructions - Parse all of the instructions, inlining and resolving
1501/// any fragments involved. This populates the Instructions list with fully
1502/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001503void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001504 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1505
1506 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1507 ListInit *LI = 0;
1508
1509 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1510 LI = Instrs[i]->getValueAsListInit("Pattern");
1511
1512 // If there is no pattern, only collect minimal information about the
1513 // instruction for its operand list. We have to assume that there is one
1514 // result, as we have no detailed info.
1515 if (!LI || LI->getSize() == 0) {
1516 std::vector<Record*> Results;
1517 std::vector<Record*> Operands;
1518
1519 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1520
1521 if (InstInfo.OperandList.size() != 0) {
1522 if (InstInfo.NumDefs == 0) {
1523 // These produce no results
1524 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1525 Operands.push_back(InstInfo.OperandList[j].Rec);
1526 } else {
1527 // Assume the first operand is the result.
1528 Results.push_back(InstInfo.OperandList[0].Rec);
1529
1530 // The rest are inputs.
1531 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1532 Operands.push_back(InstInfo.OperandList[j].Rec);
1533 }
1534 }
1535
1536 // Create and insert the instruction.
1537 std::vector<Record*> ImpResults;
1538 std::vector<Record*> ImpOperands;
1539 Instructions.insert(std::make_pair(Instrs[i],
1540 DAGInstruction(0, Results, Operands, ImpResults,
1541 ImpOperands)));
1542 continue; // no pattern.
1543 }
1544
1545 // Parse the instruction.
1546 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1547 // Inline pattern fragments into it.
1548 I->InlinePatternFragments();
1549
1550 // Infer as many types as possible. If we cannot infer all of them, we can
1551 // never do anything with this instruction pattern: report it to the user.
1552 if (!I->InferAllTypes())
1553 I->error("Could not infer all types in pattern!");
1554
1555 // InstInputs - Keep track of all of the inputs of the instruction, along
1556 // with the record they are declared as.
1557 std::map<std::string, TreePatternNode*> InstInputs;
1558
1559 // InstResults - Keep track of all the virtual registers that are 'set'
1560 // in the instruction, including what reg class they are.
1561 std::map<std::string, TreePatternNode*> InstResults;
1562
1563 std::vector<Record*> InstImpInputs;
1564 std::vector<Record*> InstImpResults;
1565
1566 // Verify that the top-level forms in the instruction are of void type, and
1567 // fill in the InstResults map.
1568 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1569 TreePatternNode *Pat = I->getTree(j);
1570 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1571 I->error("Top-level forms in instruction pattern should have"
1572 " void types");
1573
1574 // Find inputs and outputs, and verify the structure of the uses/defs.
1575 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1576 InstImpInputs, InstImpResults);
1577 }
1578
1579 // Now that we have inputs and outputs of the pattern, inspect the operands
1580 // list for the instruction. This determines the order that operands are
1581 // added to the machine instruction the node corresponds to.
1582 unsigned NumResults = InstResults.size();
1583
1584 // Parse the operands list from the (ops) list, validating it.
1585 assert(I->getArgList().empty() && "Args list should still be empty here!");
1586 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1587
1588 // Check that all of the results occur first in the list.
1589 std::vector<Record*> Results;
1590 TreePatternNode *Res0Node = NULL;
1591 for (unsigned i = 0; i != NumResults; ++i) {
1592 if (i == CGI.OperandList.size())
1593 I->error("'" + InstResults.begin()->first +
1594 "' set but does not appear in operand list!");
1595 const std::string &OpName = CGI.OperandList[i].Name;
1596
1597 // Check that it exists in InstResults.
1598 TreePatternNode *RNode = InstResults[OpName];
1599 if (RNode == 0)
1600 I->error("Operand $" + OpName + " does not exist in operand list!");
1601
1602 if (i == 0)
1603 Res0Node = RNode;
1604 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1605 if (R == 0)
1606 I->error("Operand $" + OpName + " should be a set destination: all "
1607 "outputs must occur before inputs in operand list!");
1608
1609 if (CGI.OperandList[i].Rec != R)
1610 I->error("Operand $" + OpName + " class mismatch!");
1611
1612 // Remember the return type.
1613 Results.push_back(CGI.OperandList[i].Rec);
1614
1615 // Okay, this one checks out.
1616 InstResults.erase(OpName);
1617 }
1618
1619 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1620 // the copy while we're checking the inputs.
1621 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1622
1623 std::vector<TreePatternNode*> ResultNodeOperands;
1624 std::vector<Record*> Operands;
1625 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1626 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1627 const std::string &OpName = Op.Name;
1628 if (OpName.empty())
1629 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1630
1631 if (!InstInputsCheck.count(OpName)) {
1632 // If this is an predicate operand or optional def operand with an
1633 // DefaultOps set filled in, we can ignore this. When we codegen it,
1634 // we will do so as always executed.
1635 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1636 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1637 // Does it have a non-empty DefaultOps field? If so, ignore this
1638 // operand.
1639 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1640 continue;
1641 }
1642 I->error("Operand $" + OpName +
1643 " does not appear in the instruction pattern");
1644 }
1645 TreePatternNode *InVal = InstInputsCheck[OpName];
1646 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1647
1648 if (InVal->isLeaf() &&
1649 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1650 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1651 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1652 I->error("Operand $" + OpName + "'s register class disagrees"
1653 " between the operand and pattern");
1654 }
1655 Operands.push_back(Op.Rec);
1656
1657 // Construct the result for the dest-pattern operand list.
1658 TreePatternNode *OpNode = InVal->clone();
1659
1660 // No predicate is useful on the result.
1661 OpNode->setPredicateFn("");
1662
1663 // Promote the xform function to be an explicit node if set.
1664 if (Record *Xform = OpNode->getTransformFn()) {
1665 OpNode->setTransformFn(0);
1666 std::vector<TreePatternNode*> Children;
1667 Children.push_back(OpNode);
1668 OpNode = new TreePatternNode(Xform, Children);
1669 }
1670
1671 ResultNodeOperands.push_back(OpNode);
1672 }
1673
1674 if (!InstInputsCheck.empty())
1675 I->error("Input operand $" + InstInputsCheck.begin()->first +
1676 " occurs in pattern but not in operands list!");
1677
1678 TreePatternNode *ResultPattern =
1679 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1680 // Copy fully inferred output node type to instruction result pattern.
1681 if (NumResults > 0)
1682 ResultPattern->setTypes(Res0Node->getExtTypes());
1683
1684 // Create and insert the instruction.
1685 // FIXME: InstImpResults and InstImpInputs should not be part of
1686 // DAGInstruction.
1687 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1688 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1689
1690 // Use a temporary tree pattern to infer all types and make sure that the
1691 // constructed result is correct. This depends on the instruction already
1692 // being inserted into the Instructions map.
1693 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1694 Temp.InferAllTypes();
1695
1696 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1697 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1698
1699 DEBUG(I->dump());
1700 }
1701
1702 // If we can, convert the instructions to be patterns that are matched!
1703 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1704 E = Instructions.end(); II != E; ++II) {
1705 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00001706 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00001707 if (I == 0) continue; // No pattern.
1708
1709 // FIXME: Assume only the first tree is the pattern. The others are clobber
1710 // nodes.
1711 TreePatternNode *Pattern = I->getTree(0);
1712 TreePatternNode *SrcPattern;
1713 if (Pattern->getOperator()->getName() == "set") {
1714 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1715 } else{
1716 // Not a set (store or something?)
1717 SrcPattern = Pattern;
1718 }
1719
1720 std::string Reason;
1721 if (!SrcPattern->canPatternMatch(Reason, *this))
1722 I->error("Instruction can never match: " + Reason);
1723
1724 Record *Instr = II->first;
1725 TreePatternNode *DstPattern = TheInst.getResultPattern();
1726 PatternsToMatch.
1727 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1728 SrcPattern, DstPattern, TheInst.getImpResults(),
1729 Instr->getValueAsInt("AddedComplexity")));
1730 }
1731}
1732
Chris Lattnerfe718932008-01-06 01:10:31 +00001733void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001734 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1735
1736 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1737 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1738 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
1739 Record *Operator = OpDef->getDef();
1740 TreePattern *Pattern;
1741 if (Operator->getName() != "parallel")
1742 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1743 else {
1744 std::vector<Init*> Values;
1745 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
1746 Values.push_back(Tree->getArg(j));
1747 ListInit *LI = new ListInit(Values);
1748 Pattern = new TreePattern(Patterns[i], LI, true, *this);
1749 }
1750
1751 // Inline pattern fragments into it.
1752 Pattern->InlinePatternFragments();
1753
1754 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1755 if (LI->getSize() == 0) continue; // no pattern.
1756
1757 // Parse the instruction.
1758 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1759
1760 // Inline pattern fragments into it.
1761 Result->InlinePatternFragments();
1762
1763 if (Result->getNumTrees() != 1)
1764 Result->error("Cannot handle instructions producing instructions "
1765 "with temporaries yet!");
1766
1767 bool IterateInference;
1768 bool InferredAllPatternTypes, InferredAllResultTypes;
1769 do {
1770 // Infer as many types as possible. If we cannot infer all of them, we
1771 // can never do anything with this pattern: report it to the user.
1772 InferredAllPatternTypes = Pattern->InferAllTypes();
1773
1774 // Infer as many types as possible. If we cannot infer all of them, we
1775 // can never do anything with this pattern: report it to the user.
1776 InferredAllResultTypes = Result->InferAllTypes();
1777
1778 // Apply the type of the result to the source pattern. This helps us
1779 // resolve cases where the input type is known to be a pointer type (which
1780 // is considered resolved), but the result knows it needs to be 32- or
1781 // 64-bits. Infer the other way for good measure.
1782 IterateInference = Pattern->getTree(0)->
1783 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
1784 IterateInference |= Result->getTree(0)->
1785 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
1786 } while (IterateInference);
1787
1788 // Verify that we inferred enough types that we can do something with the
1789 // pattern and result. If these fire the user has to add type casts.
1790 if (!InferredAllPatternTypes)
1791 Pattern->error("Could not infer all types in pattern!");
1792 if (!InferredAllResultTypes)
1793 Result->error("Could not infer all types in pattern result!");
1794
1795 // Validate that the input pattern is correct.
1796 std::map<std::string, TreePatternNode*> InstInputs;
1797 std::map<std::string, TreePatternNode*> InstResults;
1798 std::vector<Record*> InstImpInputs;
1799 std::vector<Record*> InstImpResults;
1800 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
1801 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
1802 InstInputs, InstResults,
1803 InstImpInputs, InstImpResults);
1804
1805 // Promote the xform function to be an explicit node if set.
1806 TreePatternNode *DstPattern = Result->getOnlyTree();
1807 std::vector<TreePatternNode*> ResultNodeOperands;
1808 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1809 TreePatternNode *OpNode = DstPattern->getChild(ii);
1810 if (Record *Xform = OpNode->getTransformFn()) {
1811 OpNode->setTransformFn(0);
1812 std::vector<TreePatternNode*> Children;
1813 Children.push_back(OpNode);
1814 OpNode = new TreePatternNode(Xform, Children);
1815 }
1816 ResultNodeOperands.push_back(OpNode);
1817 }
1818 DstPattern = Result->getOnlyTree();
1819 if (!DstPattern->isLeaf())
1820 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1821 ResultNodeOperands);
1822 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1823 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1824 Temp.InferAllTypes();
1825
1826 std::string Reason;
1827 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
1828 Pattern->error("Pattern can never match: " + Reason);
1829
1830 PatternsToMatch.
1831 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1832 Pattern->getTree(0),
1833 Temp.getOnlyTree(), InstImpResults,
1834 Patterns[i]->getValueAsInt("AddedComplexity")));
1835 }
1836}
1837
1838/// CombineChildVariants - Given a bunch of permutations of each child of the
1839/// 'operator' node, put them together in all possible ways.
1840static void CombineChildVariants(TreePatternNode *Orig,
1841 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1842 std::vector<TreePatternNode*> &OutVariants,
Chris Lattnerfe718932008-01-06 01:10:31 +00001843 CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001844 // Make sure that each operand has at least one variant to choose from.
1845 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1846 if (ChildVariants[i].empty())
1847 return;
1848
1849 // The end result is an all-pairs construction of the resultant pattern.
1850 std::vector<unsigned> Idxs;
1851 Idxs.resize(ChildVariants.size());
1852 bool NotDone = true;
1853 while (NotDone) {
1854 // Create the variant and add it to the output list.
1855 std::vector<TreePatternNode*> NewChildren;
1856 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1857 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1858 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1859
1860 // Copy over properties.
1861 R->setName(Orig->getName());
1862 R->setPredicateFn(Orig->getPredicateFn());
1863 R->setTransformFn(Orig->getTransformFn());
1864 R->setTypes(Orig->getExtTypes());
1865
1866 // If this pattern cannot every match, do not include it as a variant.
1867 std::string ErrString;
1868 if (!R->canPatternMatch(ErrString, CDP)) {
1869 delete R;
1870 } else {
1871 bool AlreadyExists = false;
1872
1873 // Scan to see if this pattern has already been emitted. We can get
1874 // duplication due to things like commuting:
1875 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1876 // which are the same pattern. Ignore the dups.
1877 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1878 if (R->isIsomorphicTo(OutVariants[i])) {
1879 AlreadyExists = true;
1880 break;
1881 }
1882
1883 if (AlreadyExists)
1884 delete R;
1885 else
1886 OutVariants.push_back(R);
1887 }
1888
1889 // Increment indices to the next permutation.
1890 NotDone = false;
1891 // Look for something we can increment without causing a wrap-around.
1892 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1893 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1894 NotDone = true; // Found something to increment.
1895 break;
1896 }
1897 Idxs[IdxsIdx] = 0;
1898 }
1899 }
1900}
1901
1902/// CombineChildVariants - A helper function for binary operators.
1903///
1904static void CombineChildVariants(TreePatternNode *Orig,
1905 const std::vector<TreePatternNode*> &LHS,
1906 const std::vector<TreePatternNode*> &RHS,
1907 std::vector<TreePatternNode*> &OutVariants,
Chris Lattnerfe718932008-01-06 01:10:31 +00001908 CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001909 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1910 ChildVariants.push_back(LHS);
1911 ChildVariants.push_back(RHS);
1912 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP);
1913}
1914
1915
1916static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1917 std::vector<TreePatternNode *> &Children) {
1918 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1919 Record *Operator = N->getOperator();
1920
1921 // Only permit raw nodes.
1922 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1923 N->getTransformFn()) {
1924 Children.push_back(N);
1925 return;
1926 }
1927
1928 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1929 Children.push_back(N->getChild(0));
1930 else
1931 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1932
1933 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1934 Children.push_back(N->getChild(1));
1935 else
1936 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1937}
1938
1939/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1940/// the (potentially recursive) pattern by using algebraic laws.
1941///
1942static void GenerateVariantsOf(TreePatternNode *N,
1943 std::vector<TreePatternNode*> &OutVariants,
Chris Lattnerfe718932008-01-06 01:10:31 +00001944 CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001945 // We cannot permute leaves.
1946 if (N->isLeaf()) {
1947 OutVariants.push_back(N);
1948 return;
1949 }
1950
1951 // Look up interesting info about the node.
1952 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
1953
1954 // If this node is associative, reassociate.
1955 if (NodeInfo.hasProperty(SDNPAssociative)) {
1956 // Reassociate by pulling together all of the linked operators
1957 std::vector<TreePatternNode*> MaximalChildren;
1958 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1959
1960 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1961 // permutations.
1962 if (MaximalChildren.size() == 3) {
1963 // Find the variants of all of our maximal children.
1964 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1965 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP);
1966 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP);
1967 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP);
1968
1969 // There are only two ways we can permute the tree:
1970 // (A op B) op C and A op (B op C)
1971 // Within these forms, we can also permute A/B/C.
1972
1973 // Generate legal pair permutations of A/B/C.
1974 std::vector<TreePatternNode*> ABVariants;
1975 std::vector<TreePatternNode*> BAVariants;
1976 std::vector<TreePatternNode*> ACVariants;
1977 std::vector<TreePatternNode*> CAVariants;
1978 std::vector<TreePatternNode*> BCVariants;
1979 std::vector<TreePatternNode*> CBVariants;
1980 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP);
1981 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP);
1982 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP);
1983 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP);
1984 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP);
1985 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP);
1986
1987 // Combine those into the result: (x op x) op x
1988 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP);
1989 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP);
1990 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP);
1991 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP);
1992 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP);
1993 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP);
1994
1995 // Combine those into the result: x op (x op x)
1996 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP);
1997 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP);
1998 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP);
1999 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP);
2000 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP);
2001 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP);
2002 return;
2003 }
2004 }
2005
2006 // Compute permutations of all children.
2007 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2008 ChildVariants.resize(N->getNumChildren());
2009 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2010 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP);
2011
2012 // Build all permutations based on how the children were formed.
2013 CombineChildVariants(N, ChildVariants, OutVariants, CDP);
2014
2015 // If this node is commutative, consider the commuted order.
2016 if (NodeInfo.hasProperty(SDNPCommutative)) {
2017 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
2018 // Don't count children which are actually register references.
2019 unsigned NC = 0;
2020 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2021 TreePatternNode *Child = N->getChild(i);
2022 if (Child->isLeaf())
2023 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2024 Record *RR = DI->getDef();
2025 if (RR->isSubClassOf("Register"))
2026 continue;
2027 }
2028 NC++;
2029 }
2030 // Consider the commuted order.
2031 if (NC == 2)
2032 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2033 OutVariants, CDP);
2034 }
2035}
2036
2037
2038// GenerateVariants - Generate variants. For example, commutative patterns can
2039// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002040void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002041 DOUT << "Generating instruction variants.\n";
2042
2043 // Loop over all of the patterns we've collected, checking to see if we can
2044 // generate variants of the instruction, through the exploitation of
2045 // identities. This permits the target to provide agressive matching without
2046 // the .td file having to contain tons of variants of instructions.
2047 //
2048 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2049 // intentionally do not reconsider these. Any variants of added patterns have
2050 // already been added.
2051 //
2052 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2053 std::vector<TreePatternNode*> Variants;
2054 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
2055
2056 assert(!Variants.empty() && "Must create at least original variant!");
2057 Variants.erase(Variants.begin()); // Remove the original pattern.
2058
2059 if (Variants.empty()) // No variants for this pattern.
2060 continue;
2061
2062 DOUT << "FOUND VARIANTS OF: ";
2063 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2064 DOUT << "\n";
2065
2066 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2067 TreePatternNode *Variant = Variants[v];
2068
2069 DOUT << " VAR#" << v << ": ";
2070 DEBUG(Variant->dump());
2071 DOUT << "\n";
2072
2073 // Scan to see if an instruction or explicit pattern already matches this.
2074 bool AlreadyExists = false;
2075 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2076 // Check to see if this variant already exists.
2077 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
2078 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2079 AlreadyExists = true;
2080 break;
2081 }
2082 }
2083 // If we already have it, ignore the variant.
2084 if (AlreadyExists) continue;
2085
2086 // Otherwise, add it to the list of patterns we have.
2087 PatternsToMatch.
2088 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2089 Variant, PatternsToMatch[i].getDstPattern(),
2090 PatternsToMatch[i].getDstRegs(),
2091 PatternsToMatch[i].getAddedComplexity()));
2092 }
2093
2094 DOUT << "\n";
2095 }
2096}
2097