blob: 2fbc0966f3ed36011ca34f8590e0014bd9c287a6 [file] [log] [blame]
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Support/Debug.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000018#include <algorithm>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000019#include <set>
20using namespace llvm;
21
Chris Lattnerca559d02005-09-08 21:03:01 +000022//===----------------------------------------------------------------------===//
Chris Lattner3c7e18d2005-10-14 06:12:03 +000023// Helpers for working with extended types.
24
25/// FilterVTs - Filter a list of VT's according to a predicate.
26///
27template<typename T>
28static std::vector<MVT::ValueType>
29FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
32 if (Filter(InVTs[i]))
33 Result.push_back(InVTs[i]);
34 return Result;
35}
36
Nate Begemanb73628b2005-12-30 00:12:56 +000037template<typename T>
38static std::vector<unsigned char>
39FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40 std::vector<unsigned char> Result;
41 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42 if (Filter((MVT::ValueType)InVTs[i]))
43 Result.push_back(InVTs[i]);
44 return Result;
Chris Lattner3c7e18d2005-10-14 06:12:03 +000045}
46
Nate Begemanb73628b2005-12-30 00:12:56 +000047static std::vector<unsigned char>
48ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49 std::vector<unsigned char> Result;
50 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51 Result.push_back(InVTs[i]);
52 return Result;
53}
54
55static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56 const std::vector<unsigned char> &RHS) {
57 if (LHS.size() > RHS.size()) return false;
58 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
Duraid Madinad47ae092005-12-30 16:41:48 +000059 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
Nate Begemanb73628b2005-12-30 00:12:56 +000060 return false;
61 return true;
62}
63
64/// isExtIntegerVT - Return true if the specified extended value type vector
65/// contains isInt or an integer value type.
66static bool isExtIntegerInVTs(std::vector<unsigned char> EVTs) {
67 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
69}
70
71/// isExtFloatingPointVT - Return true if the specified extended value type
72/// vector contains isFP or a FP value type.
73static bool isExtFloatingPointInVTs(std::vector<unsigned char> EVTs) {
74 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
75 return EVTs[0] == MVT::isFP || !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
Chris Lattner3c7e18d2005-10-14 06:12:03 +000076}
77
78//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000079// SDTypeConstraint implementation
80//
81
82SDTypeConstraint::SDTypeConstraint(Record *R) {
83 OperandNo = R->getValueAsInt("OperandNum");
84
85 if (R->isSubClassOf("SDTCisVT")) {
86 ConstraintType = SDTCisVT;
87 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattner5b21be72005-12-09 22:57:42 +000088 } else if (R->isSubClassOf("SDTCisPtrTy")) {
89 ConstraintType = SDTCisPtrTy;
Chris Lattner33c92e92005-09-08 21:27:15 +000090 } else if (R->isSubClassOf("SDTCisInt")) {
91 ConstraintType = SDTCisInt;
92 } else if (R->isSubClassOf("SDTCisFP")) {
93 ConstraintType = SDTCisFP;
94 } else if (R->isSubClassOf("SDTCisSameAs")) {
95 ConstraintType = SDTCisSameAs;
96 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
97 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
98 ConstraintType = SDTCisVTSmallerThanOp;
99 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
100 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +0000101 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
102 ConstraintType = SDTCisOpSmallerThanOp;
103 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
104 R->getValueAsInt("BigOperandNum");
Chris Lattner33c92e92005-09-08 21:27:15 +0000105 } else {
106 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
107 exit(1);
108 }
109}
110
Chris Lattner32707602005-09-08 23:22:48 +0000111/// getOperandNum - Return the node corresponding to operand #OpNo in tree
112/// N, which has NumResults results.
113TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
114 TreePatternNode *N,
115 unsigned NumResults) const {
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000116 assert(NumResults <= 1 &&
117 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000118
119 if (OpNo < NumResults)
120 return N; // FIXME: need value #
121 else
122 return N->getChild(OpNo-NumResults);
123}
124
125/// ApplyTypeConstraint - Given a node in a pattern, apply this type
126/// constraint to the nodes operands. This returns true if it makes a
127/// change, false otherwise. If a type contradiction is found, throw an
128/// exception.
129bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
130 const SDNodeInfo &NodeInfo,
131 TreePattern &TP) const {
132 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000133 assert(NumResults <= 1 &&
134 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000135
136 // Check that the number of operands is sane.
137 if (NodeInfo.getNumOperands() >= 0) {
138 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
139 TP.error(N->getOperator()->getName() + " node requires exactly " +
140 itostr(NodeInfo.getNumOperands()) + " operands!");
141 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000142
143 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000144
145 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
146
147 switch (ConstraintType) {
148 default: assert(0 && "Unknown constraint type!");
149 case SDTCisVT:
150 // Operand must be a particular type.
151 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000152 case SDTCisPtrTy: {
153 // Operand must be same as target pointer type.
154 return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
155 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000156 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000157 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000158 std::vector<MVT::ValueType> IntVTs =
159 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000160
161 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000162 if (IntVTs.size() == 1)
163 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000164 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000165 }
166 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000167 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000168 std::vector<MVT::ValueType> FPVTs =
169 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000170
171 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000172 if (FPVTs.size() == 1)
173 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000174 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000175 }
Chris Lattner32707602005-09-08 23:22:48 +0000176 case SDTCisSameAs: {
177 TreePatternNode *OtherNode =
178 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Nate Begemanb73628b2005-12-30 00:12:56 +0000179 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
180 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000181 }
182 case SDTCisVTSmallerThanOp: {
183 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
184 // have an integer type that is smaller than the VT.
185 if (!NodeToApply->isLeaf() ||
186 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
187 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
188 ->isSubClassOf("ValueType"))
189 TP.error(N->getOperator()->getName() + " expects a VT operand!");
190 MVT::ValueType VT =
191 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
192 if (!MVT::isInteger(VT))
193 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
194
195 TreePatternNode *OtherNode =
196 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000197
198 // It must be integer.
199 bool MadeChange = false;
200 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
201
Nate Begemanb73628b2005-12-30 00:12:56 +0000202 // This code only handles nodes that have one type set. Assert here so
203 // that we can change this if we ever need to deal with multiple value
204 // types at this point.
205 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
206 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000207 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
208 return false;
209 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000210 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000211 TreePatternNode *BigOperand =
212 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
213
214 // Both operands must be integer or FP, but we don't care which.
215 bool MadeChange = false;
216
Nate Begemanb73628b2005-12-30 00:12:56 +0000217 // This code does not currently handle nodes which have multiple types,
218 // where some types are integer, and some are fp. Assert that this is not
219 // the case.
220 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
221 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
222 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
223 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
224 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
225 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000226 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000227 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000228 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000229 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000230 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000231 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000232 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
233
234 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
235
Nate Begemanb73628b2005-12-30 00:12:56 +0000236 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000237 VTs = FilterVTs(VTs, MVT::isInteger);
Nate Begemanb73628b2005-12-30 00:12:56 +0000238 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000239 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
240 } else {
241 VTs.clear();
242 }
243
244 switch (VTs.size()) {
245 default: // Too many VT's to pick from.
246 case 0: break; // No info yet.
247 case 1:
248 // Only one VT of this flavor. Cannot ever satisify the constraints.
249 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
250 case 2:
251 // If we have exactly two possible types, the little operand must be the
252 // small one, the big operand should be the big one. Common with
253 // float/double for example.
254 assert(VTs[0] < VTs[1] && "Should be sorted!");
255 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
256 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
257 break;
258 }
259 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000260 }
Chris Lattner32707602005-09-08 23:22:48 +0000261 }
262 return false;
263}
264
265
Chris Lattner33c92e92005-09-08 21:27:15 +0000266//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000267// SDNodeInfo implementation
268//
269SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
270 EnumName = R->getValueAsString("Opcode");
271 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000272 Record *TypeProfile = R->getValueAsDef("TypeProfile");
273 NumResults = TypeProfile->getValueAsInt("NumResults");
274 NumOperands = TypeProfile->getValueAsInt("NumOperands");
275
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000276 // Parse the properties.
277 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000278 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000279 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
280 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000281 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000282 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000283 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000284 } else if (PropList[i]->getName() == "SDNPHasChain") {
285 Properties |= 1 << SDNPHasChain;
Evan Cheng51fecc82006-01-09 18:27:06 +0000286 } else if (PropList[i]->getName() == "SDNPOutFlag") {
287 Properties |= 1 << SDNPOutFlag;
288 } else if (PropList[i]->getName() == "SDNPInFlag") {
289 Properties |= 1 << SDNPInFlag;
290 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
291 Properties |= 1 << SDNPOptInFlag;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000292 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000293 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000294 << "' on node '" << R->getName() << "'!\n";
295 exit(1);
296 }
297 }
298
299
Chris Lattner33c92e92005-09-08 21:27:15 +0000300 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000301 std::vector<Record*> ConstraintList =
302 TypeProfile->getValueAsListOfDefs("Constraints");
303 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000304}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000305
306//===----------------------------------------------------------------------===//
307// TreePatternNode implementation
308//
309
310TreePatternNode::~TreePatternNode() {
311#if 0 // FIXME: implement refcounted tree nodes!
312 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
313 delete getChild(i);
314#endif
315}
316
Chris Lattner32707602005-09-08 23:22:48 +0000317/// UpdateNodeType - Set the node type of N to VT if VT contains
318/// information. If N already contains a conflicting type, then throw an
319/// exception. This returns true if any information was updated.
320///
Nate Begemanb73628b2005-12-30 00:12:56 +0000321bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
322 TreePattern &TP) {
323 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
324
325 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
326 return false;
327 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
328 setTypes(ExtVTs);
Chris Lattner32707602005-09-08 23:22:48 +0000329 return true;
330 }
331
Nate Begemanb73628b2005-12-30 00:12:56 +0000332 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
333 assert(hasTypeSet() && "should be handled above!");
334 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
335 if (getExtTypes() == FVTs)
336 return false;
337 setTypes(FVTs);
338 return true;
339 }
340 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
341 assert(hasTypeSet() && "should be handled above!");
342 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
343 if (getExtTypes() == FVTs)
344 return false;
345 setTypes(FVTs);
346 return true;
347 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000348
349 // If we know this is an int or fp type, and we are told it is a specific one,
350 // take the advice.
Nate Begemanb73628b2005-12-30 00:12:56 +0000351 //
352 // Similarly, we should probably set the type here to the intersection of
353 // {isInt|isFP} and ExtVTs
354 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
355 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
356 setTypes(ExtVTs);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000357 return true;
358 }
359
Chris Lattner1531f202005-10-26 16:59:37 +0000360 if (isLeaf()) {
361 dump();
Evan Chengbcecf332005-12-17 01:19:28 +0000362 std::cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000363 TP.error("Type inference contradiction found in node!");
364 } else {
365 TP.error("Type inference contradiction found in node " +
366 getOperator()->getName() + "!");
367 }
Chris Lattner32707602005-09-08 23:22:48 +0000368 return true; // unreachable
369}
370
371
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000372void TreePatternNode::print(std::ostream &OS) const {
373 if (isLeaf()) {
374 OS << *getLeafValue();
375 } else {
376 OS << "(" << getOperator()->getName();
377 }
378
Nate Begemanb73628b2005-12-30 00:12:56 +0000379 // FIXME: At some point we should handle printing all the value types for
380 // nodes that are multiply typed.
381 switch (getExtTypeNum(0)) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000382 case MVT::Other: OS << ":Other"; break;
383 case MVT::isInt: OS << ":isInt"; break;
384 case MVT::isFP : OS << ":isFP"; break;
385 case MVT::isUnknown: ; /*OS << ":?";*/ break;
Nate Begemanb73628b2005-12-30 00:12:56 +0000386 default: OS << ":" << getTypeNum(0); break;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000387 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000388
389 if (!isLeaf()) {
390 if (getNumChildren() != 0) {
391 OS << " ";
392 getChild(0)->print(OS);
393 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
394 OS << ", ";
395 getChild(i)->print(OS);
396 }
397 }
398 OS << ")";
399 }
400
401 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000402 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000403 if (TransformFn)
404 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000405 if (!getName().empty())
406 OS << ":$" << getName();
407
408}
409void TreePatternNode::dump() const {
410 print(std::cerr);
411}
412
Chris Lattnere46e17b2005-09-29 19:28:10 +0000413/// isIsomorphicTo - Return true if this node is recursively isomorphic to
414/// the specified node. For this comparison, all of the state of the node
415/// is considered, except for the assigned name. Nodes with differing names
416/// that are otherwise identical are considered isomorphic.
417bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
418 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000419 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000420 getPredicateFn() != N->getPredicateFn() ||
421 getTransformFn() != N->getTransformFn())
422 return false;
423
424 if (isLeaf()) {
425 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
426 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
427 return DI->getDef() == NDI->getDef();
428 return getLeafValue() == N->getLeafValue();
429 }
430
431 if (N->getOperator() != getOperator() ||
432 N->getNumChildren() != getNumChildren()) return false;
433 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
434 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
435 return false;
436 return true;
437}
438
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000439/// clone - Make a copy of this tree and all of its children.
440///
441TreePatternNode *TreePatternNode::clone() const {
442 TreePatternNode *New;
443 if (isLeaf()) {
444 New = new TreePatternNode(getLeafValue());
445 } else {
446 std::vector<TreePatternNode*> CChildren;
447 CChildren.reserve(Children.size());
448 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
449 CChildren.push_back(getChild(i)->clone());
450 New = new TreePatternNode(getOperator(), CChildren);
451 }
452 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000453 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000454 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000455 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000456 return New;
457}
458
Chris Lattner32707602005-09-08 23:22:48 +0000459/// SubstituteFormalArguments - Replace the formal arguments in this tree
460/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000461void TreePatternNode::
462SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
463 if (isLeaf()) return;
464
465 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
466 TreePatternNode *Child = getChild(i);
467 if (Child->isLeaf()) {
468 Init *Val = Child->getLeafValue();
469 if (dynamic_cast<DefInit*>(Val) &&
470 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
471 // We found a use of a formal argument, replace it with its value.
472 Child = ArgMap[Child->getName()];
473 assert(Child && "Couldn't find formal argument!");
474 setChild(i, Child);
475 }
476 } else {
477 getChild(i)->SubstituteFormalArguments(ArgMap);
478 }
479 }
480}
481
482
483/// InlinePatternFragments - If this pattern refers to any pattern
484/// fragments, inline them into place, giving us a pattern without any
485/// PatFrag references.
486TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
487 if (isLeaf()) return this; // nothing to do.
488 Record *Op = getOperator();
489
490 if (!Op->isSubClassOf("PatFrag")) {
491 // Just recursively inline children nodes.
492 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
493 setChild(i, getChild(i)->InlinePatternFragments(TP));
494 return this;
495 }
496
497 // Otherwise, we found a reference to a fragment. First, look up its
498 // TreePattern record.
499 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
500
501 // Verify that we are passing the right number of operands.
502 if (Frag->getNumArgs() != Children.size())
503 TP.error("'" + Op->getName() + "' fragment requires " +
504 utostr(Frag->getNumArgs()) + " operands!");
505
Chris Lattner37937092005-09-09 01:15:01 +0000506 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000507
508 // Resolve formal arguments to their actual value.
509 if (Frag->getNumArgs()) {
510 // Compute the map of formal to actual arguments.
511 std::map<std::string, TreePatternNode*> ArgMap;
512 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
513 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
514
515 FragTree->SubstituteFormalArguments(ArgMap);
516 }
517
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000518 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000519 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000520
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000521 // Get a new copy of this fragment to stitch into here.
522 //delete this; // FIXME: implement refcounting!
523 return FragTree;
524}
525
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000526/// getIntrinsicType - Check to see if the specified record has an intrinsic
527/// type which should be applied to it. This infer the type of register
528/// references from the register file information, for example.
529///
Nate Begemanb73628b2005-12-30 00:12:56 +0000530static std::vector<unsigned char> getIntrinsicType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000531 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000532 // Some common return values
533 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
534 std::vector<unsigned char> Other(1, MVT::Other);
535
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000536 // Check to see if this is a register or a register class...
537 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000538 if (NotRegisters)
539 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000540 const CodeGenRegisterClass &RC =
541 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000542 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000543 } else if (R->isSubClassOf("PatFrag")) {
544 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000545 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000546 } else if (R->isSubClassOf("Register")) {
Evan Cheng37e90052006-01-15 10:04:45 +0000547 if (NotRegisters)
548 return Unknown;
Chris Lattner22faeab2005-12-05 02:36:37 +0000549 // If the register appears in exactly one regclass, and the regclass has one
550 // value type, use it as the known type.
551 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
552 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
Nate Begemanb73628b2005-12-30 00:12:56 +0000553 return ConvertVTs(RC->getValueTypes());
554 return Unknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000555 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
556 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000557 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000558 } else if (R->isSubClassOf("ComplexPattern")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000559 std::vector<unsigned char>
560 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
561 return ComplexPat;
Evan Cheng01f318b2005-12-14 02:21:57 +0000562 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000563 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000564 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000565 }
566
567 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000568 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000569}
570
Chris Lattner32707602005-09-08 23:22:48 +0000571/// ApplyTypeConstraints - Apply all of the type constraints relevent to
572/// this node and its children in the tree. This returns true if it makes a
573/// change, false otherwise. If a type contradiction is found, throw an
574/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000575bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
576 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000577 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000578 // If it's a regclass or something else known, include the type.
579 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
580 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000581 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
582 // Int inits are always integers. :)
583 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
584
585 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000586 // At some point, it may make sense for this tree pattern to have
587 // multiple types. Assert here that it does not, so we revisit this
588 // code when appropriate.
589 assert(getExtTypes().size() == 1 && "TreePattern has too many types!");
590
591 unsigned Size = MVT::getSizeInBits(getTypeNum(0));
Chris Lattner465c7372005-11-03 05:46:11 +0000592 // Make sure that the value is representable for this type.
593 if (Size < 32) {
594 int Val = (II->getValue() << (32-Size)) >> (32-Size);
595 if (Val != II->getValue())
596 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
597 "' is out of range for type 'MVT::" +
Nate Begemanb73628b2005-12-30 00:12:56 +0000598 getEnumName(getTypeNum(0)) + "'!");
Chris Lattner465c7372005-11-03 05:46:11 +0000599 }
600 }
601
602 return MadeChange;
603 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000604 return false;
605 }
Chris Lattner32707602005-09-08 23:22:48 +0000606
607 // special handling for set, which isn't really an SDNode.
608 if (getOperator()->getName() == "set") {
609 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000610 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
611 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000612
613 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000614 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
615 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000616 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
617 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000618 } else if (getOperator()->isSubClassOf("SDNode")) {
619 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
620
621 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
622 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000623 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000624 // Branch, etc. do not produce results and top-level forms in instr pattern
625 // must have void types.
626 if (NI.getNumResults() == 0)
627 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000628 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000629 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000630 const DAGInstruction &Inst =
631 TP.getDAGISelEmitter().getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000632 bool MadeChange = false;
633 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000634
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000635 assert(NumResults <= 1 &&
636 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000637 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000638 if (NumResults == 0) {
639 MadeChange = UpdateNodeType(MVT::isVoid, TP);
640 } else {
641 Record *ResultNode = Inst.getResult(0);
642 assert(ResultNode->isSubClassOf("RegisterClass") &&
643 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000644
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000645 const CodeGenRegisterClass &RC =
646 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000647 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000648 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000649
650 if (getNumChildren() != Inst.getNumOperands())
651 TP.error("Instruction '" + getOperator()->getName() + " expects " +
652 utostr(Inst.getNumOperands()) + " operands, not " +
653 utostr(getNumChildren()) + " operands!");
654 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000655 Record *OperandNode = Inst.getOperand(i);
656 MVT::ValueType VT;
657 if (OperandNode->isSubClassOf("RegisterClass")) {
658 const CodeGenRegisterClass &RC =
659 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000660 //VT = RC.getValueTypeNum(0);
661 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
662 TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000663 } else if (OperandNode->isSubClassOf("Operand")) {
664 VT = getValueType(OperandNode->getValueAsDef("Type"));
Nate Begemanb73628b2005-12-30 00:12:56 +0000665 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000666 } else {
667 assert(0 && "Unknown operand type!");
668 abort();
669 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000670 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000671 }
672 return MadeChange;
673 } else {
674 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
675
676 // Node transforms always take one operand, and take and return the same
677 // type.
678 if (getNumChildren() != 1)
679 TP.error("Node transform '" + getOperator()->getName() +
680 "' requires one operand!");
Nate Begemanb73628b2005-12-30 00:12:56 +0000681 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
682 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000683 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000684 }
Chris Lattner32707602005-09-08 23:22:48 +0000685}
686
Chris Lattnere97603f2005-09-28 19:27:25 +0000687/// canPatternMatch - If it is impossible for this pattern to match on this
688/// target, fill in Reason and return false. Otherwise, return true. This is
689/// used as a santity check for .td files (to prevent people from writing stuff
690/// that can never possibly work), and to prevent the pattern permuter from
691/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000692bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000693 if (isLeaf()) return true;
694
695 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
696 if (!getChild(i)->canPatternMatch(Reason, ISE))
697 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000698
Chris Lattnere97603f2005-09-28 19:27:25 +0000699 // If this node is a commutative operator, check that the LHS isn't an
700 // immediate.
701 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
702 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
703 // Scan all of the operands of the node and make sure that only the last one
704 // is a constant node.
705 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
706 if (!getChild(i)->isLeaf() &&
707 getChild(i)->getOperator()->getName() == "imm") {
708 Reason = "Immediate value must be on the RHS of commutative operators!";
709 return false;
710 }
711 }
712
713 return true;
714}
Chris Lattner32707602005-09-08 23:22:48 +0000715
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000716//===----------------------------------------------------------------------===//
717// TreePattern implementation
718//
719
Chris Lattneredbd8712005-10-21 01:19:59 +0000720TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000721 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000722 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000723 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
724 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000725}
726
Chris Lattneredbd8712005-10-21 01:19:59 +0000727TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000728 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000729 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000730 Trees.push_back(ParseTreePattern(Pat));
731}
732
Chris Lattneredbd8712005-10-21 01:19:59 +0000733TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000734 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000735 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000736 Trees.push_back(Pat);
737}
738
739
740
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000741void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000742 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000743 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000744}
745
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000746TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
747 Record *Operator = Dag->getNodeType();
748
749 if (Operator->isSubClassOf("ValueType")) {
750 // If the operator is a ValueType, then this must be "type cast" of a leaf
751 // node.
752 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000753 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000754
755 Init *Arg = Dag->getArg(0);
756 TreePatternNode *New;
757 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000758 Record *R = DI->getDef();
759 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
760 Dag->setArg(0, new DagInit(R,
761 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000762 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000763 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000764 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000765 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
766 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000767 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
768 New = new TreePatternNode(II);
769 if (!Dag->getArgName(0).empty())
770 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000771 } else {
772 Arg->dump();
773 error("Unknown leaf value for tree pattern!");
774 return 0;
775 }
776
Chris Lattner32707602005-09-08 23:22:48 +0000777 // Apply the type cast.
778 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000779 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000780 return New;
781 }
782
783 // Verify that this is something that makes sense for an operator.
784 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000785 !Operator->isSubClassOf("Instruction") &&
786 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000787 Operator->getName() != "set")
788 error("Unrecognized node '" + Operator->getName() + "'!");
789
Chris Lattneredbd8712005-10-21 01:19:59 +0000790 // Check to see if this is something that is illegal in an input pattern.
791 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
792 Operator->isSubClassOf("SDNodeXForm")))
793 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
794
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000795 std::vector<TreePatternNode*> Children;
796
797 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
798 Init *Arg = Dag->getArg(i);
799 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
800 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000801 if (Children.back()->getName().empty())
802 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000803 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
804 Record *R = DefI->getDef();
805 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
806 // TreePatternNode if its own.
807 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
808 Dag->setArg(i, new DagInit(R,
809 std::vector<std::pair<Init*, std::string> >()));
810 --i; // Revisit this node...
811 } else {
812 TreePatternNode *Node = new TreePatternNode(DefI);
813 Node->setName(Dag->getArgName(i));
814 Children.push_back(Node);
815
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000816 // Input argument?
817 if (R->getName() == "node") {
818 if (Dag->getArgName(i).empty())
819 error("'node' argument requires a name to match with operand list");
820 Args.push_back(Dag->getArgName(i));
821 }
822 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000823 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
824 TreePatternNode *Node = new TreePatternNode(II);
825 if (!Dag->getArgName(i).empty())
826 error("Constant int argument should not have a name!");
827 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000828 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000829 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000830 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000831 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000832 error("Unknown leaf value for tree pattern!");
833 }
834 }
835
836 return new TreePatternNode(Operator, Children);
837}
838
Chris Lattner32707602005-09-08 23:22:48 +0000839/// InferAllTypes - Infer/propagate as many types throughout the expression
840/// patterns as possible. Return true if all types are infered, false
841/// otherwise. Throw an exception if a type contradiction is found.
842bool TreePattern::InferAllTypes() {
843 bool MadeChange = true;
844 while (MadeChange) {
845 MadeChange = false;
846 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000847 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000848 }
849
850 bool HasUnresolvedTypes = false;
851 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
852 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
853 return !HasUnresolvedTypes;
854}
855
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000856void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000857 OS << getRecord()->getName();
858 if (!Args.empty()) {
859 OS << "(" << Args[0];
860 for (unsigned i = 1, e = Args.size(); i != e; ++i)
861 OS << ", " << Args[i];
862 OS << ")";
863 }
864 OS << ": ";
865
866 if (Trees.size() > 1)
867 OS << "[\n";
868 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
869 OS << "\t";
870 Trees[i]->print(OS);
871 OS << "\n";
872 }
873
874 if (Trees.size() > 1)
875 OS << "]\n";
876}
877
878void TreePattern::dump() const { print(std::cerr); }
879
880
881
882//===----------------------------------------------------------------------===//
883// DAGISelEmitter implementation
884//
885
Chris Lattnerca559d02005-09-08 21:03:01 +0000886// Parse all of the SDNode definitions for the target, populating SDNodes.
887void DAGISelEmitter::ParseNodeInfo() {
888 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
889 while (!Nodes.empty()) {
890 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
891 Nodes.pop_back();
892 }
893}
894
Chris Lattner24eeeb82005-09-13 21:51:00 +0000895/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
896/// map, and emit them to the file as functions.
897void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
898 OS << "\n// Node transformations.\n";
899 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
900 while (!Xforms.empty()) {
901 Record *XFormNode = Xforms.back();
902 Record *SDNode = XFormNode->getValueAsDef("Opcode");
903 std::string Code = XFormNode->getValueAsCode("XFormFunction");
904 SDNodeXForms.insert(std::make_pair(XFormNode,
905 std::make_pair(SDNode, Code)));
906
Chris Lattner1048b7a2005-09-13 22:03:37 +0000907 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000908 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
909 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
910
Chris Lattner1048b7a2005-09-13 22:03:37 +0000911 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000912 << "(SDNode *" << C2 << ") {\n";
913 if (ClassName != "SDNode")
914 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
915 OS << Code << "\n}\n";
916 }
917
918 Xforms.pop_back();
919 }
920}
921
Evan Cheng0fc71982005-12-08 02:00:36 +0000922void DAGISelEmitter::ParseComplexPatterns() {
923 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
924 while (!AMs.empty()) {
925 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
926 AMs.pop_back();
927 }
928}
Chris Lattner24eeeb82005-09-13 21:51:00 +0000929
930
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000931/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
932/// file, building up the PatternFragments map. After we've collected them all,
933/// inline fragments together as necessary, so that there are no references left
934/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000935///
936/// This also emits all of the predicate functions to the output file.
937///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000938void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000939 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
940
941 // First step, parse all of the fragments and emit predicate functions.
942 OS << "\n// Predicate functions.\n";
943 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000944 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000945 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000946 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000947
948 // Validate the argument list, converting it to map, to discard duplicates.
949 std::vector<std::string> &Args = P->getArgList();
950 std::set<std::string> OperandsMap(Args.begin(), Args.end());
951
952 if (OperandsMap.count(""))
953 P->error("Cannot have unnamed 'node' values in pattern fragment!");
954
955 // Parse the operands list.
956 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
957 if (OpsList->getNodeType()->getName() != "ops")
958 P->error("Operands list should start with '(ops ... '!");
959
960 // Copy over the arguments.
961 Args.clear();
962 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
963 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
964 static_cast<DefInit*>(OpsList->getArg(j))->
965 getDef()->getName() != "node")
966 P->error("Operands list should all be 'node' values.");
967 if (OpsList->getArgName(j).empty())
968 P->error("Operands list should have names for each operand!");
969 if (!OperandsMap.count(OpsList->getArgName(j)))
970 P->error("'" + OpsList->getArgName(j) +
971 "' does not occur in pattern or was multiply specified!");
972 OperandsMap.erase(OpsList->getArgName(j));
973 Args.push_back(OpsList->getArgName(j));
974 }
975
976 if (!OperandsMap.empty())
977 P->error("Operands list does not contain an entry for operand '" +
978 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000979
980 // If there is a code init for this fragment, emit the predicate code and
981 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000982 std::string Code = Fragments[i]->getValueAsCode("Predicate");
983 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000984 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000985 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000986 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000987 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
988
Chris Lattner1048b7a2005-09-13 22:03:37 +0000989 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000990 << "(SDNode *" << C2 << ") {\n";
991 if (ClassName != "SDNode")
992 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000993 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000994 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000995 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000996
997 // If there is a node transformation corresponding to this, keep track of
998 // it.
999 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1000 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001001 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001002 }
1003
1004 OS << "\n\n";
1005
1006 // Now that we've parsed all of the tree fragments, do a closure on them so
1007 // that there are not references to PatFrags left inside of them.
1008 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1009 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001010 TreePattern *ThePat = I->second;
1011 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001012
Chris Lattner32707602005-09-08 23:22:48 +00001013 // Infer as many types as possible. Don't worry about it if we don't infer
1014 // all of them, some may depend on the inputs of the pattern.
1015 try {
1016 ThePat->InferAllTypes();
1017 } catch (...) {
1018 // If this pattern fragment is not supported by this target (no types can
1019 // satisfy its constraints), just ignore it. If the bogus pattern is
1020 // actually used by instructions, the type consistency error will be
1021 // reported there.
1022 }
1023
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001024 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001025 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001026 }
1027}
1028
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001029/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001030/// instruction input. Return true if this is a real use.
1031static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001032 std::map<std::string, TreePatternNode*> &InstInputs,
1033 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001034 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001035 if (Pat->getName().empty()) {
1036 if (Pat->isLeaf()) {
1037 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1038 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1039 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001040 else if (DI && DI->getDef()->isSubClassOf("Register"))
1041 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001042 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001043 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001044 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001045
1046 Record *Rec;
1047 if (Pat->isLeaf()) {
1048 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1049 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1050 Rec = DI->getDef();
1051 } else {
1052 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1053 Rec = Pat->getOperator();
1054 }
1055
Evan Cheng01f318b2005-12-14 02:21:57 +00001056 // SRCVALUE nodes are ignored.
1057 if (Rec->getName() == "srcvalue")
1058 return false;
1059
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001060 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1061 if (!Slot) {
1062 Slot = Pat;
1063 } else {
1064 Record *SlotRec;
1065 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001066 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001067 } else {
1068 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1069 SlotRec = Slot->getOperator();
1070 }
1071
1072 // Ensure that the inputs agree if we've already seen this input.
1073 if (Rec != SlotRec)
1074 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001075 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001076 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1077 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001078 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001079}
1080
1081/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1082/// part of "I", the instruction), computing the set of inputs and outputs of
1083/// the pattern. Report errors if we see anything naughty.
1084void DAGISelEmitter::
1085FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1086 std::map<std::string, TreePatternNode*> &InstInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001087 std::map<std::string, Record*> &InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001088 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001089 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001090 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001091 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001092 if (!isUse && Pat->getTransformFn())
1093 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001094 return;
1095 } else if (Pat->getOperator()->getName() != "set") {
1096 // If this is not a set, verify that the children nodes are not void typed,
1097 // and recurse.
1098 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001099 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001100 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001101 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001102 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001103 }
1104
1105 // If this is a non-leaf node with no children, treat it basically as if
1106 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001107 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001108 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001109 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001110
Chris Lattnerf1311842005-09-14 23:05:13 +00001111 if (!isUse && Pat->getTransformFn())
1112 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001113 return;
1114 }
1115
1116 // Otherwise, this is a set, validate and collect instruction results.
1117 if (Pat->getNumChildren() == 0)
1118 I->error("set requires operands!");
1119 else if (Pat->getNumChildren() & 1)
1120 I->error("set requires an even number of operands");
1121
Chris Lattnerf1311842005-09-14 23:05:13 +00001122 if (Pat->getTransformFn())
1123 I->error("Cannot specify a transform function on a set node!");
1124
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001125 // Check the set destinations.
1126 unsigned NumValues = Pat->getNumChildren()/2;
1127 for (unsigned i = 0; i != NumValues; ++i) {
1128 TreePatternNode *Dest = Pat->getChild(i);
1129 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001130 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001131
1132 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1133 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001134 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001135
Evan Chengbcecf332005-12-17 01:19:28 +00001136 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1137 if (Dest->getName().empty())
1138 I->error("set destination must have a name!");
1139 if (InstResults.count(Dest->getName()))
1140 I->error("cannot set '" + Dest->getName() +"' multiple times");
1141 InstResults[Dest->getName()] = Val->getDef();
Evan Cheng7b05bd52005-12-23 22:11:47 +00001142 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001143 InstImpResults.push_back(Val->getDef());
1144 } else {
1145 I->error("set destination should be a register!");
1146 }
1147
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001148 // Verify and collect info from the computation.
1149 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001150 InstInputs, InstResults,
1151 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001152 }
1153}
1154
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001155/// ParseInstructions - Parse all of the instructions, inlining and resolving
1156/// any fragments involved. This populates the Instructions list with fully
1157/// resolved instructions.
1158void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001159 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1160
1161 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001162 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001163
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001164 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1165 LI = Instrs[i]->getValueAsListInit("Pattern");
1166
1167 // If there is no pattern, only collect minimal information about the
1168 // instruction for its operand list. We have to assume that there is one
1169 // result, as we have no detailed info.
1170 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001171 std::vector<Record*> Results;
1172 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001173
1174 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001175
Evan Cheng3a217f32005-12-22 02:35:21 +00001176 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001177 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001178 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001179 // These produce no results
1180 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1181 Operands.push_back(InstInfo.OperandList[j].Rec);
1182 } else {
1183 // Assume the first operand is the result.
1184 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001185
Evan Cheng3a217f32005-12-22 02:35:21 +00001186 // The rest are inputs.
1187 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1188 Operands.push_back(InstInfo.OperandList[j].Rec);
1189 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001190 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001191
1192 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001193 std::vector<Record*> ImpResults;
1194 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001195 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001196 DAGInstruction(0, Results, Operands, ImpResults,
1197 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001198 continue; // no pattern.
1199 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001200
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001201 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001202 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001203 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001204 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001205
Chris Lattner95f6b762005-09-08 23:26:30 +00001206 // Infer as many types as possible. If we cannot infer all of them, we can
1207 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001208 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001209 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001210
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001211 // InstInputs - Keep track of all of the inputs of the instruction, along
1212 // with the record they are declared as.
1213 std::map<std::string, TreePatternNode*> InstInputs;
1214
1215 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001216 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001217 std::map<std::string, Record*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001218
1219 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001220 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001221
Chris Lattner1f39e292005-09-14 00:09:24 +00001222 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001223 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001224 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1225 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001226 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001227 I->error("Top-level forms in instruction pattern should have"
1228 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001229
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001230 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001231 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001232 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001233 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001234
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001235 // Now that we have inputs and outputs of the pattern, inspect the operands
1236 // list for the instruction. This determines the order that operands are
1237 // added to the machine instruction the node corresponds to.
1238 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001239
1240 // Parse the operands list from the (ops) list, validating it.
1241 std::vector<std::string> &Args = I->getArgList();
1242 assert(Args.empty() && "Args list should still be empty here!");
1243 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1244
1245 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001246 std::vector<Record*> Results;
Chris Lattner39e8af92005-09-14 18:19:25 +00001247 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001248 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001249 I->error("'" + InstResults.begin()->first +
1250 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001251 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001252
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001253 // Check that it exists in InstResults.
1254 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001255 if (R == 0)
1256 I->error("Operand $" + OpName + " should be a set destination: all "
1257 "outputs must occur before inputs in operand list!");
1258
1259 if (CGI.OperandList[i].Rec != R)
1260 I->error("Operand $" + OpName + " class mismatch!");
1261
Chris Lattnerae6d8282005-09-15 21:51:12 +00001262 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001263 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001264
Chris Lattner39e8af92005-09-14 18:19:25 +00001265 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001266 InstResults.erase(OpName);
1267 }
1268
Chris Lattner0b592252005-09-14 21:59:34 +00001269 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1270 // the copy while we're checking the inputs.
1271 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001272
1273 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001274 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001275 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1276 const std::string &OpName = CGI.OperandList[i].Name;
1277 if (OpName.empty())
1278 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1279
Chris Lattner0b592252005-09-14 21:59:34 +00001280 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001281 I->error("Operand $" + OpName +
1282 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001283 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001284 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001285
1286 if (InVal->isLeaf() &&
1287 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1288 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001289 if (CGI.OperandList[i].Rec != InRec &&
1290 !InRec->isSubClassOf("ComplexPattern"))
Nate Begemanddb39542005-12-01 00:06:14 +00001291 I->error("Operand $" + OpName +
Evan Cheng0fc71982005-12-08 02:00:36 +00001292 "'s register class disagrees between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001293 }
1294 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001295
Chris Lattner2175c182005-09-14 23:01:59 +00001296 // Construct the result for the dest-pattern operand list.
1297 TreePatternNode *OpNode = InVal->clone();
1298
1299 // No predicate is useful on the result.
1300 OpNode->setPredicateFn("");
1301
1302 // Promote the xform function to be an explicit node if set.
1303 if (Record *Xform = OpNode->getTransformFn()) {
1304 OpNode->setTransformFn(0);
1305 std::vector<TreePatternNode*> Children;
1306 Children.push_back(OpNode);
1307 OpNode = new TreePatternNode(Xform, Children);
1308 }
1309
1310 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001311 }
1312
Chris Lattner0b592252005-09-14 21:59:34 +00001313 if (!InstInputsCheck.empty())
1314 I->error("Input operand $" + InstInputsCheck.begin()->first +
1315 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001316
1317 TreePatternNode *ResultPattern =
1318 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001319
1320 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001321 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001322 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1323
1324 // Use a temporary tree pattern to infer all types and make sure that the
1325 // constructed result is correct. This depends on the instruction already
1326 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001327 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001328 Temp.InferAllTypes();
1329
1330 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1331 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001332
Chris Lattner32707602005-09-08 23:22:48 +00001333 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001334 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001335
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001336 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001337 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1338 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001339 DAGInstruction &TheInst = II->second;
1340 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001341 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001342
Chris Lattner1f39e292005-09-14 00:09:24 +00001343 if (I->getNumTrees() != 1) {
1344 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1345 continue;
1346 }
1347 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001348 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001349 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001350 if (Pattern->getNumChildren() != 2)
1351 continue; // Not a set of a single value (not handled so far)
1352
1353 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001354 } else{
1355 // Not a set (store or something?)
1356 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001357 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001358
1359 std::string Reason;
1360 if (!SrcPattern->canPatternMatch(Reason, *this))
1361 I->error("Instruction can never match: " + Reason);
1362
Evan Cheng58e84a62005-12-14 22:02:59 +00001363 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001364 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001365 PatternsToMatch.
1366 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1367 SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001368 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001369}
1370
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001371void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001372 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001373
Chris Lattnerabbb6052005-09-15 21:42:00 +00001374 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001375 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001376 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001377
Chris Lattnerabbb6052005-09-15 21:42:00 +00001378 // Inline pattern fragments into it.
1379 Pattern->InlinePatternFragments();
1380
1381 // Infer as many types as possible. If we cannot infer all of them, we can
1382 // never do anything with this pattern: report it to the user.
1383 if (!Pattern->InferAllTypes())
1384 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001385
1386 // Validate that the input pattern is correct.
1387 {
1388 std::map<std::string, TreePatternNode*> InstInputs;
1389 std::map<std::string, Record*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001390 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001391 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001392 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001393 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001394 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001395 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001396
1397 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1398 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001399
1400 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001401 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001402
1403 // Inline pattern fragments into it.
1404 Result->InlinePatternFragments();
1405
1406 // Infer as many types as possible. If we cannot infer all of them, we can
1407 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001408 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001409 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001410
1411 if (Result->getNumTrees() != 1)
1412 Result->error("Cannot handle instructions producing instructions "
1413 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001414
1415 std::string Reason;
1416 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1417 Pattern->error("Pattern can never match: " + Reason);
1418
Evan Cheng58e84a62005-12-14 22:02:59 +00001419 PatternsToMatch.
1420 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1421 Pattern->getOnlyTree(),
1422 Result->getOnlyTree()));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001423 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001424}
1425
Chris Lattnere46e17b2005-09-29 19:28:10 +00001426/// CombineChildVariants - Given a bunch of permutations of each child of the
1427/// 'operator' node, put them together in all possible ways.
1428static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001429 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001430 std::vector<TreePatternNode*> &OutVariants,
1431 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001432 // Make sure that each operand has at least one variant to choose from.
1433 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1434 if (ChildVariants[i].empty())
1435 return;
1436
Chris Lattnere46e17b2005-09-29 19:28:10 +00001437 // The end result is an all-pairs construction of the resultant pattern.
1438 std::vector<unsigned> Idxs;
1439 Idxs.resize(ChildVariants.size());
1440 bool NotDone = true;
1441 while (NotDone) {
1442 // Create the variant and add it to the output list.
1443 std::vector<TreePatternNode*> NewChildren;
1444 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1445 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1446 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1447
1448 // Copy over properties.
1449 R->setName(Orig->getName());
1450 R->setPredicateFn(Orig->getPredicateFn());
1451 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001452 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001453
1454 // If this pattern cannot every match, do not include it as a variant.
1455 std::string ErrString;
1456 if (!R->canPatternMatch(ErrString, ISE)) {
1457 delete R;
1458 } else {
1459 bool AlreadyExists = false;
1460
1461 // Scan to see if this pattern has already been emitted. We can get
1462 // duplication due to things like commuting:
1463 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1464 // which are the same pattern. Ignore the dups.
1465 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1466 if (R->isIsomorphicTo(OutVariants[i])) {
1467 AlreadyExists = true;
1468 break;
1469 }
1470
1471 if (AlreadyExists)
1472 delete R;
1473 else
1474 OutVariants.push_back(R);
1475 }
1476
1477 // Increment indices to the next permutation.
1478 NotDone = false;
1479 // Look for something we can increment without causing a wrap-around.
1480 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1481 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1482 NotDone = true; // Found something to increment.
1483 break;
1484 }
1485 Idxs[IdxsIdx] = 0;
1486 }
1487 }
1488}
1489
Chris Lattneraf302912005-09-29 22:36:54 +00001490/// CombineChildVariants - A helper function for binary operators.
1491///
1492static void CombineChildVariants(TreePatternNode *Orig,
1493 const std::vector<TreePatternNode*> &LHS,
1494 const std::vector<TreePatternNode*> &RHS,
1495 std::vector<TreePatternNode*> &OutVariants,
1496 DAGISelEmitter &ISE) {
1497 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1498 ChildVariants.push_back(LHS);
1499 ChildVariants.push_back(RHS);
1500 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1501}
1502
1503
1504static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1505 std::vector<TreePatternNode *> &Children) {
1506 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1507 Record *Operator = N->getOperator();
1508
1509 // Only permit raw nodes.
1510 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1511 N->getTransformFn()) {
1512 Children.push_back(N);
1513 return;
1514 }
1515
1516 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1517 Children.push_back(N->getChild(0));
1518 else
1519 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1520
1521 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1522 Children.push_back(N->getChild(1));
1523 else
1524 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1525}
1526
Chris Lattnere46e17b2005-09-29 19:28:10 +00001527/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1528/// the (potentially recursive) pattern by using algebraic laws.
1529///
1530static void GenerateVariantsOf(TreePatternNode *N,
1531 std::vector<TreePatternNode*> &OutVariants,
1532 DAGISelEmitter &ISE) {
1533 // We cannot permute leaves.
1534 if (N->isLeaf()) {
1535 OutVariants.push_back(N);
1536 return;
1537 }
1538
1539 // Look up interesting info about the node.
1540 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1541
1542 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001543 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1544 // Reassociate by pulling together all of the linked operators
1545 std::vector<TreePatternNode*> MaximalChildren;
1546 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1547
1548 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1549 // permutations.
1550 if (MaximalChildren.size() == 3) {
1551 // Find the variants of all of our maximal children.
1552 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1553 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1554 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1555 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1556
1557 // There are only two ways we can permute the tree:
1558 // (A op B) op C and A op (B op C)
1559 // Within these forms, we can also permute A/B/C.
1560
1561 // Generate legal pair permutations of A/B/C.
1562 std::vector<TreePatternNode*> ABVariants;
1563 std::vector<TreePatternNode*> BAVariants;
1564 std::vector<TreePatternNode*> ACVariants;
1565 std::vector<TreePatternNode*> CAVariants;
1566 std::vector<TreePatternNode*> BCVariants;
1567 std::vector<TreePatternNode*> CBVariants;
1568 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1569 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1570 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1571 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1572 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1573 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1574
1575 // Combine those into the result: (x op x) op x
1576 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1577 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1578 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1579 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1580 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1581 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1582
1583 // Combine those into the result: x op (x op x)
1584 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1585 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1586 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1587 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1588 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1589 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1590 return;
1591 }
1592 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001593
1594 // Compute permutations of all children.
1595 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1596 ChildVariants.resize(N->getNumChildren());
1597 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1598 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1599
1600 // Build all permutations based on how the children were formed.
1601 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1602
1603 // If this node is commutative, consider the commuted order.
1604 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1605 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001606 // Consider the commuted order.
1607 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1608 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001609 }
1610}
1611
1612
Chris Lattnere97603f2005-09-28 19:27:25 +00001613// GenerateVariants - Generate variants. For example, commutative patterns can
1614// match multiple ways. Add them to PatternsToMatch as well.
1615void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001616
1617 DEBUG(std::cerr << "Generating instruction variants.\n");
1618
1619 // Loop over all of the patterns we've collected, checking to see if we can
1620 // generate variants of the instruction, through the exploitation of
1621 // identities. This permits the target to provide agressive matching without
1622 // the .td file having to contain tons of variants of instructions.
1623 //
1624 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1625 // intentionally do not reconsider these. Any variants of added patterns have
1626 // already been added.
1627 //
1628 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1629 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001630 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001631
1632 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001633 Variants.erase(Variants.begin()); // Remove the original pattern.
1634
1635 if (Variants.empty()) // No variants for this pattern.
1636 continue;
1637
1638 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001639 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001640 std::cerr << "\n");
1641
1642 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1643 TreePatternNode *Variant = Variants[v];
1644
1645 DEBUG(std::cerr << " VAR#" << v << ": ";
1646 Variant->dump();
1647 std::cerr << "\n");
1648
1649 // Scan to see if an instruction or explicit pattern already matches this.
1650 bool AlreadyExists = false;
1651 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1652 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001653 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001654 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1655 AlreadyExists = true;
1656 break;
1657 }
1658 }
1659 // If we already have it, ignore the variant.
1660 if (AlreadyExists) continue;
1661
1662 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001663 PatternsToMatch.
1664 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1665 Variant, PatternsToMatch[i].getDstPattern()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001666 }
1667
1668 DEBUG(std::cerr << "\n");
1669 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001670}
1671
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001672
Evan Cheng0fc71982005-12-08 02:00:36 +00001673// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1674// ComplexPattern.
1675static bool NodeIsComplexPattern(TreePatternNode *N)
1676{
1677 return (N->isLeaf() &&
1678 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1679 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1680 isSubClassOf("ComplexPattern"));
1681}
1682
1683// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1684// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1685static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1686 DAGISelEmitter &ISE)
1687{
1688 if (N->isLeaf() &&
1689 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1690 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1691 isSubClassOf("ComplexPattern")) {
1692 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1693 ->getDef());
1694 }
1695 return NULL;
1696}
1697
Chris Lattner05814af2005-09-28 17:57:56 +00001698/// getPatternSize - Return the 'size' of this pattern. We want to match large
1699/// patterns before small ones. This is used to determine the size of a
1700/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001701static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng4a7c2842006-01-06 22:19:44 +00001702 assert(isExtIntegerInVTs(P->getExtTypes()) ||
1703 isExtFloatingPointInVTs(P->getExtTypes()) ||
1704 P->getExtTypeNum(0) == MVT::isVoid ||
1705 P->getExtTypeNum(0) == MVT::Flag &&
1706 "Not a valid pattern node to size!");
Evan Chenge1050d62006-01-06 02:30:23 +00001707 unsigned Size = 2; // The node itself.
Evan Cheng0fc71982005-12-08 02:00:36 +00001708
1709 // FIXME: This is a hack to statically increase the priority of patterns
1710 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1711 // Later we can allow complexity / cost for each pattern to be (optionally)
1712 // specified. To get best possible pattern match we'll need to dynamically
1713 // calculate the complexity of all patterns a dag can potentially map to.
1714 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1715 if (AM)
Evan Cheng4a7c2842006-01-06 22:19:44 +00001716 Size += AM->getNumOperands() * 2;
Evan Cheng0fc71982005-12-08 02:00:36 +00001717
Chris Lattner05814af2005-09-28 17:57:56 +00001718 // Count children in the count if they are also nodes.
1719 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1720 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001721 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001722 Size += getPatternSize(Child, ISE);
1723 else if (Child->isLeaf()) {
1724 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Cheng4a7c2842006-01-06 22:19:44 +00001725 Size += 3; // Matches a ConstantSDNode.
1726 else if (NodeIsComplexPattern(Child))
1727 Size += getPatternSize(Child, ISE);
Chris Lattner2f041d42005-10-19 04:41:05 +00001728 }
Chris Lattner05814af2005-09-28 17:57:56 +00001729 }
1730
1731 return Size;
1732}
1733
1734/// getResultPatternCost - Compute the number of instructions for this pattern.
1735/// This is a temporary hack. We should really include the instruction
1736/// latencies in this calculation.
1737static unsigned getResultPatternCost(TreePatternNode *P) {
1738 if (P->isLeaf()) return 0;
1739
1740 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1741 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1742 Cost += getResultPatternCost(P->getChild(i));
1743 return Cost;
1744}
1745
1746// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1747// In particular, we want to match maximal patterns first and lowest cost within
1748// a particular complexity first.
1749struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001750 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1751 DAGISelEmitter &ISE;
1752
Evan Cheng58e84a62005-12-14 22:02:59 +00001753 bool operator()(PatternToMatch *LHS,
1754 PatternToMatch *RHS) {
1755 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1756 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001757 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1758 if (LHSSize < RHSSize) return false;
1759
1760 // If the patterns have equal complexity, compare generated instruction cost
Evan Cheng58e84a62005-12-14 22:02:59 +00001761 return getResultPatternCost(LHS->getDstPattern()) <
1762 getResultPatternCost(RHS->getDstPattern());
Chris Lattner05814af2005-09-28 17:57:56 +00001763 }
1764};
1765
Nate Begeman6510b222005-12-01 04:51:06 +00001766/// getRegisterValueType - Look up and return the first ValueType of specified
1767/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001768static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001769 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1770 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001771 return MVT::Other;
1772}
1773
Chris Lattner72fe91c2005-09-24 00:40:24 +00001774
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001775/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1776/// type information from it.
1777static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001778 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001779 if (!N->isLeaf())
1780 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1781 RemoveAllTypes(N->getChild(i));
1782}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001783
Chris Lattner0614b622005-11-02 06:49:14 +00001784Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1785 Record *N = Records.getDef(Name);
1786 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1787 return N;
1788}
1789
Evan Cheng51fecc82006-01-09 18:27:06 +00001790/// NodeHasProperty - return true if TreePatternNode has the specified
1791/// property.
1792static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1793 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001794{
1795 if (N->isLeaf()) return false;
1796 Record *Operator = N->getOperator();
1797 if (!Operator->isSubClassOf("SDNode")) return false;
1798
1799 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00001800 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00001801}
1802
Evan Cheng51fecc82006-01-09 18:27:06 +00001803static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1804 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001805{
Evan Cheng51fecc82006-01-09 18:27:06 +00001806 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00001807 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00001808
1809 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1810 TreePatternNode *Child = N->getChild(i);
1811 if (PatternHasProperty(Child, Property, ISE))
1812 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001813 }
1814
1815 return false;
1816}
1817
Evan Chengb915f312005-12-09 22:45:35 +00001818class PatternCodeEmitter {
1819private:
1820 DAGISelEmitter &ISE;
1821
Evan Cheng58e84a62005-12-14 22:02:59 +00001822 // Predicates.
1823 ListInit *Predicates;
1824 // Instruction selector pattern.
1825 TreePatternNode *Pattern;
1826 // Matched instruction.
1827 TreePatternNode *Instruction;
Evan Chengb915f312005-12-09 22:45:35 +00001828 unsigned PatternNo;
1829 std::ostream &OS;
1830 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00001831 std::map<std::string, std::string> VariableMap;
1832 // Node to operator mapping
1833 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00001834 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001835 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb915f312005-12-09 22:45:35 +00001836 unsigned TmpNo;
1837
1838public:
Evan Cheng58e84a62005-12-14 22:02:59 +00001839 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1840 TreePatternNode *pattern, TreePatternNode *instr,
Evan Chengb915f312005-12-09 22:45:35 +00001841 unsigned PatNum, std::ostream &os) :
Evan Cheng58e84a62005-12-14 22:02:59 +00001842 ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001843 PatternNo(PatNum), OS(os), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00001844
1845 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1846 /// if the match fails. At this point, we already know that the opcode for N
1847 /// matches, and the SDNode for the result has the RootName specified name.
1848 void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001849 bool &FoundChain, bool isRoot = false) {
Evan Cheng58e84a62005-12-14 22:02:59 +00001850
1851 // Emit instruction predicates. Each predicate is just a string for now.
1852 if (isRoot) {
1853 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1854 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1855 Record *Def = Pred->getDef();
1856 if (Def->isSubClassOf("Predicate")) {
1857 if (i == 0)
1858 OS << " if (";
1859 else
1860 OS << " && ";
Evan Cheng5fb5e102005-12-20 20:08:01 +00001861 OS << "!(" << Def->getValueAsString("CondString") << ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00001862 if (i == e-1)
1863 OS << ") goto P" << PatternNo << "Fail;\n";
1864 } else {
1865 Def->dump();
1866 assert(0 && "Unknown predicate type!");
1867 }
1868 }
1869 }
1870 }
1871
Evan Chengb915f312005-12-09 22:45:35 +00001872 if (N->isLeaf()) {
1873 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1874 OS << " if (cast<ConstantSDNode>(" << RootName
1875 << ")->getSignExtended() != " << II->getValue() << ")\n"
1876 << " goto P" << PatternNo << "Fail;\n";
1877 return;
1878 } else if (!NodeIsComplexPattern(N)) {
1879 assert(0 && "Cannot match this as a leaf value!");
1880 abort();
1881 }
1882 }
1883
1884 // If this node has a name associated with it, capture it in VariableMap. If
1885 // we already saw this in the pattern, emit code to verify dagness.
1886 if (!N->getName().empty()) {
1887 std::string &VarMapEntry = VariableMap[N->getName()];
1888 if (VarMapEntry.empty()) {
1889 VarMapEntry = RootName;
1890 } else {
1891 // If we get here, this is a second reference to a specific name. Since
1892 // we already have checked that the first reference is valid, we don't
1893 // have to recursively match it, just check that it's the same as the
1894 // previously named thing.
1895 OS << " if (" << VarMapEntry << " != " << RootName
1896 << ") goto P" << PatternNo << "Fail;\n";
1897 return;
1898 }
Evan Chengf805c2e2006-01-12 19:35:54 +00001899
1900 if (!N->isLeaf())
1901 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00001902 }
1903
1904
1905 // Emit code to load the child nodes and match their contents recursively.
1906 unsigned OpNo = 0;
Evan Cheng51fecc82006-01-09 18:27:06 +00001907 bool HasChain = NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng86217892005-12-12 19:37:43 +00001908 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00001909 OpNo = 1;
1910 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00001911 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Evan Chengb915f312005-12-09 22:45:35 +00001912 OS << " if (!" << RootName << ".hasOneUse()) goto P"
1913 << PatternNo << "Fail; // Multiple uses of actual result?\n";
1914 OS << " if (CodeGenMap.count(" << RootName
Evan Cheng1129e872005-12-10 00:09:17 +00001915 << ".getValue(" << CInfo.getNumResults() << "))) goto P"
Evan Chengb915f312005-12-09 22:45:35 +00001916 << PatternNo << "Fail; // Already selected for a chain use?\n";
1917 }
Evan Cheng1cf6db22006-01-06 00:41:12 +00001918 if (!FoundChain) {
1919 OS << " SDOperand Chain = " << RootName << ".getOperand(0);\n";
1920 FoundChain = true;
1921 }
Evan Chengb915f312005-12-09 22:45:35 +00001922 }
1923
1924 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00001925 OS << " SDOperand " << RootName << OpNo << " = "
1926 << RootName << ".getOperand(" << OpNo << ");\n";
Evan Chengb915f312005-12-09 22:45:35 +00001927 TreePatternNode *Child = N->getChild(i);
1928
1929 if (!Child->isLeaf()) {
1930 // If it's not a leaf, recursively match.
1931 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1932 OS << " if (" << RootName << OpNo << ".getOpcode() != "
1933 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00001934 EmitMatchCode(Child, RootName + utostr(OpNo), FoundChain);
Evan Cheng51fecc82006-01-09 18:27:06 +00001935 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE)) {
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001936 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
1937 CInfo.getNumResults()));
1938 }
Evan Chengb915f312005-12-09 22:45:35 +00001939 } else {
1940 // If this child has a name associated with it, capture it in VarMap. If
1941 // we already saw this in the pattern, emit code to verify dagness.
1942 if (!Child->getName().empty()) {
1943 std::string &VarMapEntry = VariableMap[Child->getName()];
1944 if (VarMapEntry.empty()) {
1945 VarMapEntry = RootName + utostr(OpNo);
1946 } else {
1947 // If we get here, this is a second reference to a specific name. Since
1948 // we already have checked that the first reference is valid, we don't
1949 // have to recursively match it, just check that it's the same as the
1950 // previously named thing.
1951 OS << " if (" << VarMapEntry << " != " << RootName << OpNo
1952 << ") goto P" << PatternNo << "Fail;\n";
1953 continue;
1954 }
1955 }
1956
1957 // Handle leaves of various types.
1958 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1959 Record *LeafRec = DI->getDef();
1960 if (LeafRec->isSubClassOf("RegisterClass")) {
1961 // Handle register references. Nothing to do here.
1962 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00001963 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00001964 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1965 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00001966 } else if (LeafRec->getName() == "srcvalue") {
1967 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00001968 } else if (LeafRec->isSubClassOf("ValueType")) {
1969 // Make sure this is the specified value type.
1970 OS << " if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
1971 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1972 << "Fail;\n";
1973 } else if (LeafRec->isSubClassOf("CondCode")) {
1974 // Make sure this is the specified cond code.
1975 OS << " if (cast<CondCodeSDNode>(" << RootName << OpNo
1976 << ")->get() != " << "ISD::" << LeafRec->getName()
1977 << ") goto P" << PatternNo << "Fail;\n";
1978 } else {
1979 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00001980 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00001981 assert(0 && "Unknown leaf type!");
1982 }
1983 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1984 OS << " if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1985 << " cast<ConstantSDNode>(" << RootName << OpNo
1986 << ")->getSignExtended() != " << II->getValue() << ")\n"
1987 << " goto P" << PatternNo << "Fail;\n";
1988 } else {
1989 Child->dump();
1990 assert(0 && "Unknown leaf type!");
1991 }
1992 }
1993 }
1994
1995 // If there is a node predicate for this, emit the call.
1996 if (!N->getPredicateFn().empty())
1997 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1998 << ".Val)) goto P" << PatternNo << "Fail;\n";
1999 }
2000
2001 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2002 /// we actually have to build a DAG!
2003 std::pair<unsigned, unsigned>
2004 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
2005 // This is something selected from the pattern we matched.
2006 if (!N->getName().empty()) {
2007 assert(!isRoot && "Root of pattern cannot be a leaf!");
2008 std::string &Val = VariableMap[N->getName()];
2009 assert(!Val.empty() &&
2010 "Variable referenced but not defined and not caught earlier!");
2011 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2012 // Already selected this operand, just return the tmpval.
2013 return std::make_pair(1, atoi(Val.c_str()+3));
2014 }
2015
2016 const ComplexPattern *CP;
2017 unsigned ResNo = TmpNo++;
2018 unsigned NumRes = 1;
2019 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002020 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2021 switch (N->getTypeNum(0)) {
Evan Chengb915f312005-12-09 22:45:35 +00002022 default: assert(0 && "Unknown type for constant node!");
2023 case MVT::i1: OS << " bool Tmp"; break;
2024 case MVT::i8: OS << " unsigned char Tmp"; break;
2025 case MVT::i16: OS << " unsigned short Tmp"; break;
2026 case MVT::i32: OS << " unsigned Tmp"; break;
2027 case MVT::i64: OS << " uint64_t Tmp"; break;
2028 }
2029 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002030 OS << " SDOperand Tmp" << utostr(ResNo)
2031 << " = CurDAG->getTargetConstant(Tmp"
Nate Begemanb73628b2005-12-30 00:12:56 +00002032 << ResNo << "C, MVT::" << getEnumName(N->getTypeNum(0)) << ");\n";
Evan Chengbb48e332006-01-12 07:54:57 +00002033 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002034 Record *Op = OperatorMap[N->getName()];
2035 // Transform ExternalSymbol to TargetExternalSymbol
2036 if (Op && Op->getName() == "externalsym") {
2037 OS << " SDOperand Tmp" << ResNo
2038 << " = CurDAG->getTargetExternalSymbol(cast<ExternalSymbolSDNode>("
2039 << Val << ")->getSymbol(), MVT::" << getEnumName(N->getTypeNum(0))
2040 << ");\n";
2041 } else
2042 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Evan Chengb915f312005-12-09 22:45:35 +00002043 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002044 Record *Op = OperatorMap[N->getName()];
2045 // Transform GlobalAddress to TargetGlobalAddress
2046 if (Op && Op->getName() == "globaladdr") {
2047 OS << " SDOperand Tmp" << ResNo
2048 << " = CurDAG->getTargetGlobalAddress(cast<GlobalAddressSDNode>("
2049 << Val << ")->getGlobal(), MVT::" << getEnumName(N->getTypeNum(0))
2050 << ");\n";
2051 } else
2052 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002053 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2054 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Evan Chengbb48e332006-01-12 07:54:57 +00002055 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2056 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Evan Chengb915f312005-12-09 22:45:35 +00002057 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2058 std::string Fn = CP->getSelectFunc();
2059 NumRes = CP->getNumOperands();
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002060 OS << " SDOperand ";
Jeff Cohen60e91872006-01-04 03:23:30 +00002061 for (unsigned i = 0; i < NumRes - 1; ++i)
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002062 OS << "Tmp" << (i+ResNo) << ",";
Jeff Cohen60e91872006-01-04 03:23:30 +00002063 OS << "Tmp" << (NumRes - 1 + ResNo) << ";\n";
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002064
Evan Chengb915f312005-12-09 22:45:35 +00002065 OS << " if (!" << Fn << "(" << Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002066 for (unsigned i = 0; i < NumRes; i++)
Evan Chengbcecf332005-12-17 01:19:28 +00002067 OS << ", Tmp" << i + ResNo;
Evan Chengb915f312005-12-09 22:45:35 +00002068 OS << ")) goto P" << PatternNo << "Fail;\n";
2069 TmpNo = ResNo + NumRes;
2070 } else {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002071 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
Evan Chengb915f312005-12-09 22:45:35 +00002072 }
2073 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2074 // value if used multiple times by this pattern result.
2075 Val = "Tmp"+utostr(ResNo);
2076 return std::make_pair(NumRes, ResNo);
2077 }
2078
2079 if (N->isLeaf()) {
2080 // If this is an explicit register reference, handle it.
2081 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2082 unsigned ResNo = TmpNo++;
2083 if (DI->getDef()->isSubClassOf("Register")) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002084 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
Evan Chengb915f312005-12-09 22:45:35 +00002085 << ISE.getQualifiedName(DI->getDef()) << ", MVT::"
Nate Begemanb73628b2005-12-30 00:12:56 +00002086 << getEnumName(N->getTypeNum(0))
Evan Chengb915f312005-12-09 22:45:35 +00002087 << ");\n";
2088 return std::make_pair(1, ResNo);
2089 }
2090 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2091 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002092 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002093 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
Evan Chengb915f312005-12-09 22:45:35 +00002094 << II->getValue() << ", MVT::"
Nate Begemanb73628b2005-12-30 00:12:56 +00002095 << getEnumName(N->getTypeNum(0))
Evan Chengb915f312005-12-09 22:45:35 +00002096 << ");\n";
2097 return std::make_pair(1, ResNo);
2098 }
2099
2100 N->dump();
2101 assert(0 && "Unknown leaf type!");
2102 return std::make_pair(1, ~0U);
2103 }
2104
2105 Record *Op = N->getOperator();
2106 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002107 const CodeGenTarget &CGT = ISE.getTargetInfo();
2108 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002109 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002110 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2111 bool HasImpResults = Inst.getNumImpResults() > 0;
Evan Cheng51fecc82006-01-09 18:27:06 +00002112 bool HasOptInFlag = isRoot &&
2113 NodeHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2114 bool HasInFlag = isRoot &&
2115 NodeHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2116 bool HasOutFlag = HasImpResults ||
2117 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2118 bool HasChain = II.hasCtrlDep ||
2119 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
Evan Cheng4fba2812005-12-20 07:37:41 +00002120
Evan Cheng51fecc82006-01-09 18:27:06 +00002121 if (HasOutFlag || HasInFlag || HasOptInFlag || HasImpInputs)
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002122 OS << " SDOperand InFlag = SDOperand(0, 0);\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002123
Evan Chengb915f312005-12-09 22:45:35 +00002124 // Determine operand emission order. Complex pattern first.
2125 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2126 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2127 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2128 TreePatternNode *Child = N->getChild(i);
2129 if (i == 0) {
2130 EmitOrder.push_back(std::make_pair(i, Child));
2131 OI = EmitOrder.begin();
2132 } else if (NodeIsComplexPattern(Child)) {
2133 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2134 } else {
2135 EmitOrder.push_back(std::make_pair(i, Child));
2136 }
2137 }
2138
2139 // Emit all of the operands.
2140 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2141 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2142 unsigned OpOrder = EmitOrder[i].first;
2143 TreePatternNode *Child = EmitOrder[i].second;
2144 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2145 NumTemps[OpOrder] = NumTemp;
2146 }
2147
2148 // List all the operands in the right order.
2149 std::vector<unsigned> Ops;
2150 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2151 for (unsigned j = 0; j < NumTemps[i].first; j++)
2152 Ops.push_back(NumTemps[i].second + j);
2153 }
2154
Evan Chengb915f312005-12-09 22:45:35 +00002155 // Emit all the chain and CopyToReg stuff.
Evan Chengb2c6d492006-01-11 22:16:13 +00002156 bool ChainEmitted = HasChain;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002157 if (HasChain)
Evan Cheng86217892005-12-12 19:37:43 +00002158 OS << " Chain = Select(Chain);\n";
Evan Cheng51fecc82006-01-09 18:27:06 +00002159 if (HasImpInputs)
Evan Chengb2c6d492006-01-11 22:16:13 +00002160 EmitCopyToRegs(Pattern, "N", ChainEmitted, true);
Evan Cheng51fecc82006-01-09 18:27:06 +00002161 if (HasInFlag || HasOptInFlag) {
2162 unsigned FlagNo = (unsigned) HasChain + Pattern->getNumChildren();
2163 if (HasOptInFlag)
2164 OS << " if (N.getNumOperands() == " << FlagNo+1 << ") ";
2165 else
2166 OS << " ";
2167 OS << "InFlag = Select(N.getOperand(" << FlagNo << "));\n";
2168 }
Evan Chengb915f312005-12-09 22:45:35 +00002169
Evan Chengb915f312005-12-09 22:45:35 +00002170 unsigned NumResults = Inst.getNumResults();
2171 unsigned ResNo = TmpNo++;
2172 if (!isRoot) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002173 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
Evan Chengbcecf332005-12-17 01:19:28 +00002174 << II.Namespace << "::" << II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002175 if (N->getTypeNum(0) != MVT::isVoid)
2176 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
Evan Cheng7b05bd52005-12-23 22:11:47 +00002177 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002178 OS << ", MVT::Flag";
Evan Chengbcecf332005-12-17 01:19:28 +00002179
Evan Chengb915f312005-12-09 22:45:35 +00002180 unsigned LastOp = 0;
2181 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2182 LastOp = Ops[i];
2183 OS << ", Tmp" << LastOp;
2184 }
2185 OS << ");\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002186 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002187 // Must have at least one result
2188 OS << " Chain = Tmp" << LastOp << ".getValue("
2189 << NumResults << ");\n";
2190 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002191 } else if (HasChain || HasOutFlag) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002192 OS << " SDOperand Result = CurDAG->getTargetNode("
Evan Chengb915f312005-12-09 22:45:35 +00002193 << II.Namespace << "::" << II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002194
2195 // Output order: results, chain, flags
2196 // Result types.
Evan Chengbcecf332005-12-17 01:19:28 +00002197 if (NumResults > 0) {
Nate Begemanb73628b2005-12-30 00:12:56 +00002198 if (N->getTypeNum(0) != MVT::isVoid)
2199 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
Evan Chengbcecf332005-12-17 01:19:28 +00002200 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002201 if (HasChain)
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002202 OS << ", MVT::Other";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002203 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002204 OS << ", MVT::Flag";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002205
2206 // Inputs.
Evan Chengb915f312005-12-09 22:45:35 +00002207 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2208 OS << ", Tmp" << Ops[i];
Evan Cheng7b05bd52005-12-23 22:11:47 +00002209 if (HasChain) OS << ", Chain";
Evan Cheng51fecc82006-01-09 18:27:06 +00002210 if (HasInFlag || HasImpInputs) OS << ", InFlag";
Evan Chengb915f312005-12-09 22:45:35 +00002211 OS << ");\n";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002212
2213 unsigned ValNo = 0;
Evan Chengf9fc25d2005-12-19 22:40:04 +00002214 for (unsigned i = 0; i < NumResults; i++) {
2215 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = Result"
2216 << ".getValue(" << ValNo << ");\n";
2217 ValNo++;
2218 }
2219
Evan Cheng7b05bd52005-12-23 22:11:47 +00002220 if (HasChain)
Evan Cheng4fba2812005-12-20 07:37:41 +00002221 OS << " Chain = Result.getValue(" << ValNo << ");\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002222
Evan Cheng7b05bd52005-12-23 22:11:47 +00002223 if (HasOutFlag)
Evan Cheng97938882005-12-22 02:24:50 +00002224 OS << " InFlag = Result.getValue("
Evan Cheng7b05bd52005-12-23 22:11:47 +00002225 << ValNo + (unsigned)HasChain << ");\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002226
Evan Cheng7b05bd52005-12-23 22:11:47 +00002227 if (HasImpResults) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002228 if (EmitCopyFromRegs(N, ChainEmitted)) {
Evan Cheng97938882005-12-22 02:24:50 +00002229 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = "
2230 << "Result.getValue(" << ValNo << ");\n";
2231 ValNo++;
2232 }
2233 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002234
Evan Cheng7b05bd52005-12-23 22:11:47 +00002235 // User does not expect that the instruction produces a chain!
Evan Cheng51fecc82006-01-09 18:27:06 +00002236 bool NodeHasChain =
2237 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2238 bool AddedChain = HasChain && !NodeHasChain;
2239 if (NodeHasChain)
Evan Cheng97938882005-12-22 02:24:50 +00002240 OS << " CodeGenMap[N.getValue(" << ValNo++ << ")] = Chain;\n";
2241
2242 if (FoldedChains.size() > 0) {
Evan Cheng4fba2812005-12-20 07:37:41 +00002243 OS << " ";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002244 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng4fba2812005-12-20 07:37:41 +00002245 OS << "CodeGenMap[" << FoldedChains[j].first << ".getValue("
2246 << FoldedChains[j].second << ")] = ";
2247 OS << "Chain;\n";
Evan Chengb915f312005-12-09 22:45:35 +00002248 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002249
Evan Cheng7b05bd52005-12-23 22:11:47 +00002250 if (HasOutFlag)
Evan Cheng97938882005-12-22 02:24:50 +00002251 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = InFlag;\n";
2252
Evan Cheng7b05bd52005-12-23 22:11:47 +00002253 if (AddedChain && HasOutFlag) {
Evan Cheng97938882005-12-22 02:24:50 +00002254 if (NumResults == 0) {
2255 OS << " return Result.getValue(N.ResNo+1);\n";
2256 } else {
2257 OS << " if (N.ResNo < " << NumResults << ")\n";
2258 OS << " return Result.getValue(N.ResNo);\n";
2259 OS << " else\n";
2260 OS << " return Result.getValue(N.ResNo+1);\n";
2261 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002262 } else {
Evan Chenge0870512005-12-20 00:06:17 +00002263 OS << " return Result.getValue(N.ResNo);\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002264 }
Evan Chengb915f312005-12-09 22:45:35 +00002265 } else {
2266 // If this instruction is the root, and if there is only one use of it,
2267 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2268 OS << " if (N.Val->hasOneUse()) {\n";
2269 OS << " return CurDAG->SelectNodeTo(N.Val, "
Evan Chengbcecf332005-12-17 01:19:28 +00002270 << II.Namespace << "::" << II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002271 if (N->getTypeNum(0) != MVT::isVoid)
2272 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
Evan Cheng7b05bd52005-12-23 22:11:47 +00002273 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002274 OS << ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002275 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2276 OS << ", Tmp" << Ops[i];
Evan Cheng51fecc82006-01-09 18:27:06 +00002277 if (HasInFlag || HasImpInputs)
Evan Chengb915f312005-12-09 22:45:35 +00002278 OS << ", InFlag";
2279 OS << ");\n";
2280 OS << " } else {\n";
2281 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
Evan Chengbcecf332005-12-17 01:19:28 +00002282 << II.Namespace << "::" << II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002283 if (N->getTypeNum(0) != MVT::isVoid)
2284 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
Evan Cheng7b05bd52005-12-23 22:11:47 +00002285 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002286 OS << ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002287 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2288 OS << ", Tmp" << Ops[i];
Evan Cheng51fecc82006-01-09 18:27:06 +00002289 if (HasInFlag || HasImpInputs)
Evan Chengb915f312005-12-09 22:45:35 +00002290 OS << ", InFlag";
2291 OS << ");\n";
2292 OS << " }\n";
2293 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002294
Evan Chengb915f312005-12-09 22:45:35 +00002295 return std::make_pair(1, ResNo);
2296 } else if (Op->isSubClassOf("SDNodeXForm")) {
2297 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng58e84a62005-12-14 22:02:59 +00002298 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
Evan Chengb915f312005-12-09 22:45:35 +00002299 unsigned ResNo = TmpNo++;
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002300 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
Evan Chengb915f312005-12-09 22:45:35 +00002301 << "(Tmp" << OpVal << ".Val);\n";
2302 if (isRoot) {
2303 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
2304 OS << " return Tmp" << ResNo << ";\n";
2305 }
2306 return std::make_pair(1, ResNo);
2307 } else {
2308 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002309 std::cerr << "\n";
2310 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002311 }
2312 }
2313
2314 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2315 /// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2316 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2317 /// for, this returns true otherwise false if Pat has all types.
2318 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2319 const std::string &Prefix) {
2320 // Did we find one?
2321 if (!Pat->hasTypeSet()) {
2322 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002323 Pat->setTypes(Other->getExtTypes());
Evan Chengb915f312005-12-09 22:45:35 +00002324 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
Nate Begemanb73628b2005-12-30 00:12:56 +00002325 << getName(Pat->getTypeNum(0)) << ") goto P" << PatternNo << "Fail;\n";
Evan Chengb915f312005-12-09 22:45:35 +00002326 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002327 }
2328
Evan Cheng51fecc82006-01-09 18:27:06 +00002329 unsigned OpNo =
2330 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002331 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2332 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2333 Prefix + utostr(OpNo)))
2334 return true;
2335 return false;
2336 }
2337
2338private:
Evan Cheng51fecc82006-01-09 18:27:06 +00002339 /// EmitCopyToRegs - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002340 /// being built.
Evan Cheng51fecc82006-01-09 18:27:06 +00002341 void EmitCopyToRegs(TreePatternNode *N, const std::string &RootName,
Evan Chengb2c6d492006-01-11 22:16:13 +00002342 bool &ChainEmitted, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002343 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002344 unsigned OpNo =
2345 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002346 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2347 TreePatternNode *Child = N->getChild(i);
2348 if (!Child->isLeaf()) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002349 EmitCopyToRegs(Child, RootName + utostr(OpNo), ChainEmitted);
Evan Chengb915f312005-12-09 22:45:35 +00002350 } else {
2351 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2352 Record *RR = DI->getDef();
2353 if (RR->isSubClassOf("Register")) {
2354 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002355 if (RVT == MVT::Flag) {
2356 OS << " InFlag = Select(" << RootName << OpNo << ");\n";
Evan Chengb2c6d492006-01-11 22:16:13 +00002357 } else {
2358 if (!ChainEmitted) {
2359 OS << " SDOperand Chain = CurDAG->getEntryNode();\n";
2360 ChainEmitted = true;
2361 }
Evan Chengb915f312005-12-09 22:45:35 +00002362 OS << " SDOperand " << RootName << "CR" << i << ";\n";
2363 OS << " " << RootName << "CR" << i
2364 << " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
2365 << ISE.getQualifiedName(RR) << ", MVT::"
2366 << getEnumName(RVT) << ")"
2367 << ", Select(" << RootName << OpNo << "), InFlag);\n";
2368 OS << " Chain = " << RootName << "CR" << i
2369 << ".getValue(0);\n";
2370 OS << " InFlag = " << RootName << "CR" << i
2371 << ".getValue(1);\n";
Evan Chengb915f312005-12-09 22:45:35 +00002372 }
2373 }
2374 }
2375 }
2376 }
2377 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002378
2379 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002380 /// as specified by the instruction. It returns true if any copy is
2381 /// emitted.
Evan Chengb2c6d492006-01-11 22:16:13 +00002382 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002383 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002384 Record *Op = N->getOperator();
2385 if (Op->isSubClassOf("Instruction")) {
2386 const DAGInstruction &Inst = ISE.getInstruction(Op);
2387 const CodeGenTarget &CGT = ISE.getTargetInfo();
2388 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2389 unsigned NumImpResults = Inst.getNumImpResults();
2390 for (unsigned i = 0; i < NumImpResults; i++) {
2391 Record *RR = Inst.getImpResult(i);
2392 if (RR->isSubClassOf("Register")) {
2393 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2394 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002395 if (!ChainEmitted) {
2396 OS << " SDOperand Chain = CurDAG->getEntryNode();\n";
2397 ChainEmitted = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002398 }
Evan Chengb2c6d492006-01-11 22:16:13 +00002399 OS << " Result = CurDAG->getCopyFromReg(Chain, "
2400 << ISE.getQualifiedName(RR)
2401 << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2402 OS << " Chain = Result.getValue(1);\n";
2403 OS << " InFlag = Result.getValue(2);\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002404 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002405 }
2406 }
2407 }
2408 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002409 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002410 }
Evan Chengb915f312005-12-09 22:45:35 +00002411};
2412
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002413/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2414/// stream to match the pattern, and generate the code for the match if it
2415/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00002416void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2417 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002418 static unsigned PatternCount = 0;
2419 unsigned PatternNo = PatternCount++;
2420 OS << " { // Pattern #" << PatternNo << ": ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002421 Pattern.getSrcPattern()->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00002422 OS << "\n // Emits: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002423 Pattern.getDstPattern()->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00002424 OS << "\n";
Evan Cheng58e84a62005-12-14 22:02:59 +00002425 OS << " // Pattern complexity = "
2426 << getPatternSize(Pattern.getSrcPattern(), *this)
2427 << " cost = "
2428 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002429
Evan Cheng58e84a62005-12-14 22:02:59 +00002430 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2431 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2432 PatternNo, OS);
Evan Chengb915f312005-12-09 22:45:35 +00002433
Chris Lattner8fc35682005-09-23 23:16:51 +00002434 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002435 bool FoundChain = false;
2436 Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", FoundChain,
2437 true /*the root*/);
Evan Chengb915f312005-12-09 22:45:35 +00002438
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002439 // TP - Get *SOME* tree pattern, we don't care which.
2440 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002441
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002442 // At this point, we know that we structurally match the pattern, but the
2443 // types of the nodes may not match. Figure out the fewest number of type
2444 // comparisons we need to emit. For example, if there is only one integer
2445 // type supported by a target, there should be no type comparisons at all for
2446 // integer patterns!
2447 //
2448 // To figure out the fewest number of type checks needed, clone the pattern,
2449 // remove the types, then perform type inference on the pattern as a whole.
2450 // If there are unresolved types, emit an explicit check for those types,
2451 // apply the type to the tree, then rerun type inference. Iterate until all
2452 // types are resolved.
2453 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002454 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002455 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002456
2457 do {
2458 // Resolve/propagate as many types as possible.
2459 try {
2460 bool MadeChange = true;
2461 while (MadeChange)
2462 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2463 } catch (...) {
2464 assert(0 && "Error: could not find consistent types for something we"
2465 " already decided was ok!");
2466 abort();
2467 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002468
Chris Lattner7e82f132005-10-15 21:34:21 +00002469 // Insert a check for an unresolved type and add it to the tree. If we find
2470 // an unresolved type to add a check for, this returns true and we iterate,
2471 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002472 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002473
Evan Cheng58e84a62005-12-14 22:02:59 +00002474 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
Evan Chengb915f312005-12-09 22:45:35 +00002475
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002476 delete Pat;
2477
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002478 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002479}
2480
Chris Lattner37481472005-09-26 21:59:35 +00002481
2482namespace {
2483 /// CompareByRecordName - An ordering predicate that implements less-than by
2484 /// comparing the names records.
2485 struct CompareByRecordName {
2486 bool operator()(const Record *LHS, const Record *RHS) const {
2487 // Sort by name first.
2488 if (LHS->getName() < RHS->getName()) return true;
2489 // If both names are equal, sort by pointer.
2490 return LHS->getName() == RHS->getName() && LHS < RHS;
2491 }
2492 };
2493}
2494
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002495void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002496 std::string InstNS = Target.inst_begin()->second.Namespace;
2497 if (!InstNS.empty()) InstNS += "::";
2498
Chris Lattner602f6922006-01-04 00:25:00 +00002499 // Group the patterns by their top-level opcodes.
2500 std::map<Record*, std::vector<PatternToMatch*>,
2501 CompareByRecordName> PatternsByOpcode;
2502 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2503 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2504 if (!Node->isLeaf()) {
2505 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2506 } else {
2507 const ComplexPattern *CP;
2508 if (IntInit *II =
2509 dynamic_cast<IntInit*>(Node->getLeafValue())) {
2510 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2511 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2512 std::vector<Record*> OpNodes = CP->getRootNodes();
2513 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2514 PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2515 &PatternsToMatch[i]);
2516 }
2517 } else {
2518 std::cerr << "Unrecognized opcode '";
2519 Node->dump();
2520 std::cerr << "' on tree pattern '";
2521 std::cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
2522 std::cerr << "'!\n";
2523 exit(1);
2524 }
2525 }
2526 }
2527
2528 // Emit one Select_* method for each top-level opcode. We do this instead of
2529 // emitting one giant switch statement to support compilers where this will
2530 // result in the recursive functions taking less stack space.
2531 for (std::map<Record*, std::vector<PatternToMatch*>,
2532 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2533 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2534 OS << "SDOperand Select_" << PBOI->first->getName() << "(SDOperand N) {\n";
2535
2536 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2537 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2538
2539 // We want to emit all of the matching code now. However, we want to emit
2540 // the matches in order of minimal cost. Sort the patterns so the least
2541 // cost one is at the start.
2542 std::stable_sort(Patterns.begin(), Patterns.end(),
2543 PatternSortingPredicate(*this));
2544
2545 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2546 EmitCodeForPattern(*Patterns[i], OS);
2547
2548 OS << " std::cerr << \"Cannot yet select: \";\n"
2549 << " N.Val->dump(CurDAG);\n"
2550 << " std::cerr << '\\n';\n"
2551 << " abort();\n"
2552 << "}\n\n";
2553 }
2554
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002555 // Emit boilerplate.
2556 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002557 << "SDOperand SelectCode(SDOperand N) {\n"
2558 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002559 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2560 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002561 << " return N; // Already selected.\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002562 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng481c8e02005-12-12 23:22:48 +00002563 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002564 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002565 << " default: break;\n"
2566 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00002567 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00002568 << " case ISD::Register:\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002569 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002570 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002571 << " case ISD::AssertZext: {\n"
2572 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2573 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2574 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002575 << " }\n"
2576 << " case ISD::TokenFactor:\n"
2577 << " if (N.getNumOperands() == 2) {\n"
2578 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2579 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2580 << " return CodeGenMap[N] =\n"
2581 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2582 << " } else {\n"
2583 << " std::vector<SDOperand> Ops;\n"
2584 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2585 << " Ops.push_back(Select(N.getOperand(i)));\n"
2586 << " return CodeGenMap[N] = \n"
2587 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2588 << " }\n"
2589 << " case ISD::CopyFromReg: {\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002590 << " SDOperand Chain = Select(N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002591 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2592 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002593 << " if (N.Val->getNumValues() == 2) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002594 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2595 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
2596 << " CodeGenMap[N.getValue(0)] = New;\n"
2597 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2598 << " return New.getValue(N.ResNo);\n"
2599 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00002600 << " SDOperand Flag(0, 0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002601 << " if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
2602 << " if (Chain == N.getOperand(0) &&\n"
2603 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002604 << " return N; // No change\n"
2605 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
2606 << " CodeGenMap[N.getValue(0)] = New;\n"
2607 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2608 << " CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
2609 << " return New.getValue(N.ResNo);\n"
2610 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002611 << " }\n"
2612 << " case ISD::CopyToReg: {\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002613 << " SDOperand Chain = Select(N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002614 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002615 << " SDOperand Val = Select(N.getOperand(2));\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002616 << " SDOperand Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002617 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002618 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002619 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002620 << " return CodeGenMap[N] = Result;\n"
2621 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00002622 << " SDOperand Flag(0, 0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002623 << " if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002624 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002625 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
2626 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002627 << " CodeGenMap[N.getValue(0)] = Result;\n"
2628 << " CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
2629 << " return Result.getValue(N.ResNo);\n"
2630 << " }\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002631 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002632
Chris Lattner602f6922006-01-04 00:25:00 +00002633 // Loop over all of the case statements, emiting a call to each method we
2634 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00002635 for (std::map<Record*, std::vector<PatternToMatch*>,
2636 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2637 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00002638 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00002639 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00002640 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Chris Lattner602f6922006-01-04 00:25:00 +00002641 << "return Select_" << PBOI->first->getName() << "(N);\n";
Chris Lattner81303322005-09-23 19:36:15 +00002642 }
Chris Lattner81303322005-09-23 19:36:15 +00002643
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002644 OS << " } // end of big switch.\n\n"
2645 << " std::cerr << \"Cannot yet select: \";\n"
Evan Cheng97938882005-12-22 02:24:50 +00002646 << " N.Val->dump(CurDAG);\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002647 << " std::cerr << '\\n';\n"
2648 << " abort();\n"
2649 << "}\n";
2650}
2651
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002652void DAGISelEmitter::run(std::ostream &OS) {
2653 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2654 " target", OS);
2655
Chris Lattner1f39e292005-09-14 00:09:24 +00002656 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2657 << "// *** instruction selector class. These functions are really "
2658 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002659
Chris Lattner296dfe32005-09-24 00:50:51 +00002660 OS << "// Instance var to keep track of multiply used nodes that have \n"
2661 << "// already been selected.\n"
2662 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2663
Chris Lattnerca559d02005-09-08 21:03:01 +00002664 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00002665 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00002666 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002667 ParsePatternFragments(OS);
2668 ParseInstructions();
2669 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00002670
Chris Lattnere97603f2005-09-28 19:27:25 +00002671 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00002672 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00002673 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002674
Chris Lattnere46e17b2005-09-29 19:28:10 +00002675
2676 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2677 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002678 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
2679 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00002680 std::cerr << "\n";
2681 });
2682
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002683 // At this point, we have full information about the 'Patterns' we need to
2684 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002685 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002686 EmitInstructionSelector(OS);
2687
2688 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2689 E = PatternFragments.end(); I != E; ++I)
2690 delete I->second;
2691 PatternFragments.clear();
2692
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002693 Instructions.clear();
2694}