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