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