blob: d991aa140d619d7b0778721c90a471e3d9ac4439 [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.
Chris Lattner697f8842006-03-20 05:39:48 +000066static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000067 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.
Chris Lattner697f8842006-03-20 05:39:48 +000073static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000074 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
Chris Lattner488580c2006-01-28 19:06:51 +000075 return EVTs[0] == MVT::isFP ||
76 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
Chris Lattner3c7e18d2005-10-14 06:12:03 +000077}
78
79//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000080// SDTypeConstraint implementation
81//
82
83SDTypeConstraint::SDTypeConstraint(Record *R) {
84 OperandNo = R->getValueAsInt("OperandNum");
85
86 if (R->isSubClassOf("SDTCisVT")) {
87 ConstraintType = SDTCisVT;
88 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattner5b21be72005-12-09 22:57:42 +000089 } else if (R->isSubClassOf("SDTCisPtrTy")) {
90 ConstraintType = SDTCisPtrTy;
Chris Lattner33c92e92005-09-08 21:27:15 +000091 } else if (R->isSubClassOf("SDTCisInt")) {
92 ConstraintType = SDTCisInt;
93 } else if (R->isSubClassOf("SDTCisFP")) {
94 ConstraintType = SDTCisFP;
95 } else if (R->isSubClassOf("SDTCisSameAs")) {
96 ConstraintType = SDTCisSameAs;
97 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
98 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
99 ConstraintType = SDTCisVTSmallerThanOp;
100 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
101 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +0000102 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
103 ConstraintType = SDTCisOpSmallerThanOp;
104 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
105 R->getValueAsInt("BigOperandNum");
Chris Lattner697f8842006-03-20 05:39:48 +0000106 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
107 ConstraintType = SDTCisIntVectorOfSameSize;
108 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
109 R->getValueAsInt("OtherOpNum");
Chris Lattner33c92e92005-09-08 21:27:15 +0000110 } else {
111 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
112 exit(1);
113 }
114}
115
Chris Lattner32707602005-09-08 23:22:48 +0000116/// getOperandNum - Return the node corresponding to operand #OpNo in tree
117/// N, which has NumResults results.
118TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
119 TreePatternNode *N,
120 unsigned NumResults) const {
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000121 assert(NumResults <= 1 &&
122 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000123
Evan Cheng50c997e2006-06-13 21:47:27 +0000124 if (OpNo >= (NumResults + N->getNumChildren())) {
125 std::cerr << "Invalid operand number " << OpNo << " ";
126 N->dump();
127 std::cerr << '\n';
128 exit(1);
129 }
130
Chris Lattner32707602005-09-08 23:22:48 +0000131 if (OpNo < NumResults)
132 return N; // FIXME: need value #
133 else
134 return N->getChild(OpNo-NumResults);
135}
136
137/// ApplyTypeConstraint - Given a node in a pattern, apply this type
138/// constraint to the nodes operands. This returns true if it makes a
139/// change, false otherwise. If a type contradiction is found, throw an
140/// exception.
141bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
142 const SDNodeInfo &NodeInfo,
143 TreePattern &TP) const {
144 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000145 assert(NumResults <= 1 &&
146 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000147
Chris Lattner8f60d542006-06-16 18:25:06 +0000148 // Check that the number of operands is sane. Negative operands -> varargs.
Chris Lattner32707602005-09-08 23:22:48 +0000149 if (NodeInfo.getNumOperands() >= 0) {
150 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
151 TP.error(N->getOperator()->getName() + " node requires exactly " +
152 itostr(NodeInfo.getNumOperands()) + " operands!");
153 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000154
155 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000156
157 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
158
159 switch (ConstraintType) {
160 default: assert(0 && "Unknown constraint type!");
161 case SDTCisVT:
162 // Operand must be a particular type.
163 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000164 case SDTCisPtrTy: {
165 // Operand must be same as target pointer type.
Evan Cheng2618d072006-05-17 20:37:59 +0000166 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000167 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000168 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000169 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000170 std::vector<MVT::ValueType> IntVTs =
171 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000172
173 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000174 if (IntVTs.size() == 1)
175 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000176 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000177 }
178 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000179 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000180 std::vector<MVT::ValueType> FPVTs =
181 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000182
183 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000184 if (FPVTs.size() == 1)
185 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000186 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000187 }
Chris Lattner32707602005-09-08 23:22:48 +0000188 case SDTCisSameAs: {
189 TreePatternNode *OtherNode =
190 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Nate Begemanb73628b2005-12-30 00:12:56 +0000191 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
192 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000193 }
194 case SDTCisVTSmallerThanOp: {
195 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
196 // have an integer type that is smaller than the VT.
197 if (!NodeToApply->isLeaf() ||
198 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
199 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
200 ->isSubClassOf("ValueType"))
201 TP.error(N->getOperator()->getName() + " expects a VT operand!");
202 MVT::ValueType VT =
203 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
204 if (!MVT::isInteger(VT))
205 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
206
207 TreePatternNode *OtherNode =
208 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000209
210 // It must be integer.
211 bool MadeChange = false;
212 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
213
Nate Begemanb73628b2005-12-30 00:12:56 +0000214 // This code only handles nodes that have one type set. Assert here so
215 // that we can change this if we ever need to deal with multiple value
216 // types at this point.
217 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
218 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000219 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
220 return false;
221 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000222 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000223 TreePatternNode *BigOperand =
224 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
225
226 // Both operands must be integer or FP, but we don't care which.
227 bool MadeChange = false;
228
Nate Begemanb73628b2005-12-30 00:12:56 +0000229 // This code does not currently handle nodes which have multiple types,
230 // where some types are integer, and some are fp. Assert that this is not
231 // the case.
232 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
233 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
234 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
235 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
236 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
237 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000238 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000239 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000240 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000241 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000242 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000243 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000244 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
245
246 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
247
Nate Begemanb73628b2005-12-30 00:12:56 +0000248 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000249 VTs = FilterVTs(VTs, MVT::isInteger);
Nate Begemanb73628b2005-12-30 00:12:56 +0000250 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000251 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
252 } else {
253 VTs.clear();
254 }
255
256 switch (VTs.size()) {
257 default: // Too many VT's to pick from.
258 case 0: break; // No info yet.
259 case 1:
260 // Only one VT of this flavor. Cannot ever satisify the constraints.
261 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
262 case 2:
263 // If we have exactly two possible types, the little operand must be the
264 // small one, the big operand should be the big one. Common with
265 // float/double for example.
266 assert(VTs[0] < VTs[1] && "Should be sorted!");
267 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
268 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
269 break;
270 }
271 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000272 }
Chris Lattner697f8842006-03-20 05:39:48 +0000273 case SDTCisIntVectorOfSameSize: {
274 TreePatternNode *OtherOperand =
275 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
276 N, NumResults);
277 if (OtherOperand->hasTypeSet()) {
278 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
279 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
280 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
281 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
282 return NodeToApply->UpdateNodeType(IVT, TP);
283 }
284 return false;
285 }
Chris Lattner32707602005-09-08 23:22:48 +0000286 }
287 return false;
288}
289
290
Chris Lattner33c92e92005-09-08 21:27:15 +0000291//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000292// SDNodeInfo implementation
293//
294SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
295 EnumName = R->getValueAsString("Opcode");
296 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000297 Record *TypeProfile = R->getValueAsDef("TypeProfile");
298 NumResults = TypeProfile->getValueAsInt("NumResults");
299 NumOperands = TypeProfile->getValueAsInt("NumOperands");
300
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000301 // Parse the properties.
302 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000303 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000304 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
305 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000306 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000307 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000308 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000309 } else if (PropList[i]->getName() == "SDNPHasChain") {
310 Properties |= 1 << SDNPHasChain;
Evan Cheng51fecc82006-01-09 18:27:06 +0000311 } else if (PropList[i]->getName() == "SDNPOutFlag") {
312 Properties |= 1 << SDNPOutFlag;
313 } else if (PropList[i]->getName() == "SDNPInFlag") {
314 Properties |= 1 << SDNPInFlag;
315 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
316 Properties |= 1 << SDNPOptInFlag;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000317 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000318 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000319 << "' on node '" << R->getName() << "'!\n";
320 exit(1);
321 }
322 }
323
324
Chris Lattner33c92e92005-09-08 21:27:15 +0000325 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000326 std::vector<Record*> ConstraintList =
327 TypeProfile->getValueAsListOfDefs("Constraints");
328 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000329}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000330
331//===----------------------------------------------------------------------===//
332// TreePatternNode implementation
333//
334
335TreePatternNode::~TreePatternNode() {
336#if 0 // FIXME: implement refcounted tree nodes!
337 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
338 delete getChild(i);
339#endif
340}
341
Chris Lattner32707602005-09-08 23:22:48 +0000342/// UpdateNodeType - Set the node type of N to VT if VT contains
343/// information. If N already contains a conflicting type, then throw an
344/// exception. This returns true if any information was updated.
345///
Nate Begemanb73628b2005-12-30 00:12:56 +0000346bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
347 TreePattern &TP) {
348 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
349
350 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
351 return false;
352 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
353 setTypes(ExtVTs);
Chris Lattner32707602005-09-08 23:22:48 +0000354 return true;
355 }
Evan Cheng2618d072006-05-17 20:37:59 +0000356
357 if (getExtTypeNum(0) == MVT::iPTR) {
358 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
359 return false;
360 if (isExtIntegerInVTs(ExtVTs)) {
361 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
362 if (FVTs.size()) {
363 setTypes(ExtVTs);
364 return true;
365 }
366 }
367 }
Chris Lattner32707602005-09-08 23:22:48 +0000368
Nate Begemanb73628b2005-12-30 00:12:56 +0000369 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
370 assert(hasTypeSet() && "should be handled above!");
371 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
372 if (getExtTypes() == FVTs)
373 return false;
374 setTypes(FVTs);
375 return true;
376 }
Evan Cheng2618d072006-05-17 20:37:59 +0000377 if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
378 //assert(hasTypeSet() && "should be handled above!");
379 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
380 if (getExtTypes() == FVTs)
381 return false;
382 if (FVTs.size()) {
383 setTypes(FVTs);
384 return true;
385 }
386 }
Nate Begemanb73628b2005-12-30 00:12:56 +0000387 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
388 assert(hasTypeSet() && "should be handled above!");
Chris Lattner488580c2006-01-28 19:06:51 +0000389 std::vector<unsigned char> FVTs =
390 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
Nate Begemanb73628b2005-12-30 00:12:56 +0000391 if (getExtTypes() == FVTs)
392 return false;
393 setTypes(FVTs);
394 return true;
395 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000396
397 // If we know this is an int or fp type, and we are told it is a specific one,
398 // take the advice.
Nate Begemanb73628b2005-12-30 00:12:56 +0000399 //
400 // Similarly, we should probably set the type here to the intersection of
401 // {isInt|isFP} and ExtVTs
402 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
403 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
404 setTypes(ExtVTs);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000405 return true;
Evan Cheng2618d072006-05-17 20:37:59 +0000406 }
407 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
408 setTypes(ExtVTs);
409 return true;
410 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000411
Chris Lattner1531f202005-10-26 16:59:37 +0000412 if (isLeaf()) {
413 dump();
Evan Chengbcecf332005-12-17 01:19:28 +0000414 std::cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000415 TP.error("Type inference contradiction found in node!");
416 } else {
417 TP.error("Type inference contradiction found in node " +
418 getOperator()->getName() + "!");
419 }
Chris Lattner32707602005-09-08 23:22:48 +0000420 return true; // unreachable
421}
422
423
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000424void TreePatternNode::print(std::ostream &OS) const {
425 if (isLeaf()) {
426 OS << *getLeafValue();
427 } else {
428 OS << "(" << getOperator()->getName();
429 }
430
Nate Begemanb73628b2005-12-30 00:12:56 +0000431 // FIXME: At some point we should handle printing all the value types for
432 // nodes that are multiply typed.
433 switch (getExtTypeNum(0)) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000434 case MVT::Other: OS << ":Other"; break;
435 case MVT::isInt: OS << ":isInt"; break;
436 case MVT::isFP : OS << ":isFP"; break;
437 case MVT::isUnknown: ; /*OS << ":?";*/ break;
Evan Cheng2618d072006-05-17 20:37:59 +0000438 case MVT::iPTR: OS << ":iPTR"; break;
Chris Lattner02cdb372006-06-20 00:56:37 +0000439 default: {
440 std::string VTName = llvm::getName(getTypeNum(0));
441 // Strip off MVT:: prefix if present.
442 if (VTName.substr(0,5) == "MVT::")
443 VTName = VTName.substr(5);
444 OS << ":" << VTName;
445 break;
446 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000447 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000448
449 if (!isLeaf()) {
450 if (getNumChildren() != 0) {
451 OS << " ";
452 getChild(0)->print(OS);
453 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
454 OS << ", ";
455 getChild(i)->print(OS);
456 }
457 }
458 OS << ")";
459 }
460
461 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000462 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000463 if (TransformFn)
464 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000465 if (!getName().empty())
466 OS << ":$" << getName();
467
468}
469void TreePatternNode::dump() const {
470 print(std::cerr);
471}
472
Chris Lattnere46e17b2005-09-29 19:28:10 +0000473/// isIsomorphicTo - Return true if this node is recursively isomorphic to
474/// the specified node. For this comparison, all of the state of the node
475/// is considered, except for the assigned name. Nodes with differing names
476/// that are otherwise identical are considered isomorphic.
477bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
478 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000479 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000480 getPredicateFn() != N->getPredicateFn() ||
481 getTransformFn() != N->getTransformFn())
482 return false;
483
484 if (isLeaf()) {
485 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
486 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
487 return DI->getDef() == NDI->getDef();
488 return getLeafValue() == N->getLeafValue();
489 }
490
491 if (N->getOperator() != getOperator() ||
492 N->getNumChildren() != getNumChildren()) return false;
493 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
494 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
495 return false;
496 return true;
497}
498
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000499/// clone - Make a copy of this tree and all of its children.
500///
501TreePatternNode *TreePatternNode::clone() const {
502 TreePatternNode *New;
503 if (isLeaf()) {
504 New = new TreePatternNode(getLeafValue());
505 } else {
506 std::vector<TreePatternNode*> CChildren;
507 CChildren.reserve(Children.size());
508 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
509 CChildren.push_back(getChild(i)->clone());
510 New = new TreePatternNode(getOperator(), CChildren);
511 }
512 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000513 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000514 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000515 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000516 return New;
517}
518
Chris Lattner32707602005-09-08 23:22:48 +0000519/// SubstituteFormalArguments - Replace the formal arguments in this tree
520/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000521void TreePatternNode::
522SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
523 if (isLeaf()) return;
524
525 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
526 TreePatternNode *Child = getChild(i);
527 if (Child->isLeaf()) {
528 Init *Val = Child->getLeafValue();
529 if (dynamic_cast<DefInit*>(Val) &&
530 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
531 // We found a use of a formal argument, replace it with its value.
532 Child = ArgMap[Child->getName()];
533 assert(Child && "Couldn't find formal argument!");
534 setChild(i, Child);
535 }
536 } else {
537 getChild(i)->SubstituteFormalArguments(ArgMap);
538 }
539 }
540}
541
542
543/// InlinePatternFragments - If this pattern refers to any pattern
544/// fragments, inline them into place, giving us a pattern without any
545/// PatFrag references.
546TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
547 if (isLeaf()) return this; // nothing to do.
548 Record *Op = getOperator();
549
550 if (!Op->isSubClassOf("PatFrag")) {
551 // Just recursively inline children nodes.
552 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
553 setChild(i, getChild(i)->InlinePatternFragments(TP));
554 return this;
555 }
556
557 // Otherwise, we found a reference to a fragment. First, look up its
558 // TreePattern record.
559 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
560
561 // Verify that we are passing the right number of operands.
562 if (Frag->getNumArgs() != Children.size())
563 TP.error("'" + Op->getName() + "' fragment requires " +
564 utostr(Frag->getNumArgs()) + " operands!");
565
Chris Lattner37937092005-09-09 01:15:01 +0000566 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000567
568 // Resolve formal arguments to their actual value.
569 if (Frag->getNumArgs()) {
570 // Compute the map of formal to actual arguments.
571 std::map<std::string, TreePatternNode*> ArgMap;
572 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
573 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
574
575 FragTree->SubstituteFormalArguments(ArgMap);
576 }
577
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000578 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000579 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000580
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000581 // Get a new copy of this fragment to stitch into here.
582 //delete this; // FIXME: implement refcounting!
583 return FragTree;
584}
585
Chris Lattner52793e22006-04-06 20:19:52 +0000586/// getImplicitType - Check to see if the specified record has an implicit
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000587/// type which should be applied to it. This infer the type of register
588/// references from the register file information, for example.
589///
Chris Lattner52793e22006-04-06 20:19:52 +0000590static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000591 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000592 // Some common return values
593 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
594 std::vector<unsigned char> Other(1, MVT::Other);
595
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000596 // Check to see if this is a register or a register class...
597 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000598 if (NotRegisters)
599 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000600 const CodeGenRegisterClass &RC =
601 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000602 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000603 } else if (R->isSubClassOf("PatFrag")) {
604 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000605 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000606 } else if (R->isSubClassOf("Register")) {
Evan Cheng37e90052006-01-15 10:04:45 +0000607 if (NotRegisters)
608 return Unknown;
Chris Lattner22faeab2005-12-05 02:36:37 +0000609 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
Evan Cheng44a65fa2006-05-16 07:05:30 +0000610 return T.getRegisterVTs(R);
Chris Lattner1531f202005-10-26 16:59:37 +0000611 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
612 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000613 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000614 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng57c517d2006-01-17 07:36:41 +0000615 if (NotRegisters)
616 return Unknown;
Nate Begemanb73628b2005-12-30 00:12:56 +0000617 std::vector<unsigned char>
618 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
619 return ComplexPat;
Evan Cheng01f318b2005-12-14 02:21:57 +0000620 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000621 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000622 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000623 }
624
625 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000626 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000627}
628
Chris Lattner32707602005-09-08 23:22:48 +0000629/// ApplyTypeConstraints - Apply all of the type constraints relevent to
630/// this node and its children in the tree. This returns true if it makes a
631/// change, false otherwise. If a type contradiction is found, throw an
632/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000633bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000634 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000635 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000636 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000637 // If it's a regclass or something else known, include the type.
Chris Lattner52793e22006-04-06 20:19:52 +0000638 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000639 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
640 // Int inits are always integers. :)
641 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
642
643 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000644 // At some point, it may make sense for this tree pattern to have
645 // multiple types. Assert here that it does not, so we revisit this
646 // code when appropriate.
Evan Cheng2618d072006-05-17 20:37:59 +0000647 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Evan Cheng44a65fa2006-05-16 07:05:30 +0000648 MVT::ValueType VT = getTypeNum(0);
649 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
650 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
Nate Begemanb73628b2005-12-30 00:12:56 +0000651
Evan Cheng2618d072006-05-17 20:37:59 +0000652 VT = getTypeNum(0);
653 if (VT != MVT::iPTR) {
654 unsigned Size = MVT::getSizeInBits(VT);
655 // Make sure that the value is representable for this type.
656 if (Size < 32) {
657 int Val = (II->getValue() << (32-Size)) >> (32-Size);
658 if (Val != II->getValue())
659 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
660 "' is out of range for type '" +
661 getEnumName(getTypeNum(0)) + "'!");
662 }
Chris Lattner465c7372005-11-03 05:46:11 +0000663 }
664 }
665
666 return MadeChange;
667 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000668 return false;
669 }
Chris Lattner32707602005-09-08 23:22:48 +0000670
671 // special handling for set, which isn't really an SDNode.
672 if (getOperator()->getName() == "set") {
673 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000674 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
675 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000676
677 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000678 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
679 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000680 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
681 return MadeChange;
Chris Lattner5a1df382006-03-24 23:10:39 +0000682 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
683 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
684 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
685 unsigned IID =
686 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
687 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
688 bool MadeChange = false;
689
690 // Apply the result type to the node.
691 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
692
693 if (getNumChildren() != Int.ArgVTs.size())
Chris Lattner2c4e65d2006-03-27 22:21:18 +0000694 TP.error("Intrinsic '" + Int.Name + "' expects " +
Chris Lattner5a1df382006-03-24 23:10:39 +0000695 utostr(Int.ArgVTs.size()-1) + " operands, not " +
696 utostr(getNumChildren()-1) + " operands!");
697
698 // Apply type info to the intrinsic ID.
Evan Cheng2618d072006-05-17 20:37:59 +0000699 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5a1df382006-03-24 23:10:39 +0000700
701 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
702 MVT::ValueType OpVT = Int.ArgVTs[i];
703 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
704 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
705 }
706 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000707 } else if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000708 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
Chris Lattnerabbb6052005-09-15 21:42:00 +0000709
710 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
711 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000712 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000713 // Branch, etc. do not produce results and top-level forms in instr pattern
714 // must have void types.
715 if (NI.getNumResults() == 0)
716 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner91ded082006-04-06 20:36:51 +0000717
718 // If this is a vector_shuffle operation, apply types to the build_vector
719 // operation. The types of the integers don't matter, but this ensures they
720 // won't get checked.
721 if (getOperator()->getName() == "vector_shuffle" &&
722 getChild(2)->getOperator()->getName() == "build_vector") {
723 TreePatternNode *BV = getChild(2);
724 const std::vector<MVT::ValueType> &LegalVTs
725 = ISE.getTargetInfo().getLegalValueTypes();
726 MVT::ValueType LegalIntVT = MVT::Other;
727 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
728 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
729 LegalIntVT = LegalVTs[i];
730 break;
731 }
732 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
733
734 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
735 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
736 }
Chris Lattnerabbb6052005-09-15 21:42:00 +0000737 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000738 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000739 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000740 bool MadeChange = false;
741 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000742
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000743 assert(NumResults <= 1 &&
744 "Only supports zero or one result instrs!");
Evan Chengeb1f40d2006-07-20 23:36:20 +0000745
746 CodeGenInstruction &InstInfo =
747 ISE.getTargetInfo().getInstruction(getOperator()->getName());
Chris Lattnera28aec12005-09-15 22:23:50 +0000748 // Apply the result type to the node
Evan Chengeb1f40d2006-07-20 23:36:20 +0000749 if (NumResults == 0 || InstInfo.noResults) { // FIXME: temporary hack...
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000750 MadeChange = UpdateNodeType(MVT::isVoid, TP);
751 } else {
752 Record *ResultNode = Inst.getResult(0);
753 assert(ResultNode->isSubClassOf("RegisterClass") &&
754 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000755
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000756 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000757 ISE.getTargetInfo().getRegisterClass(ResultNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000758 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000759 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000760
761 if (getNumChildren() != Inst.getNumOperands())
762 TP.error("Instruction '" + getOperator()->getName() + " expects " +
763 utostr(Inst.getNumOperands()) + " operands, not " +
764 utostr(getNumChildren()) + " operands!");
765 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000766 Record *OperandNode = Inst.getOperand(i);
767 MVT::ValueType VT;
768 if (OperandNode->isSubClassOf("RegisterClass")) {
769 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000770 ISE.getTargetInfo().getRegisterClass(OperandNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000771 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
772 TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000773 } else if (OperandNode->isSubClassOf("Operand")) {
774 VT = getValueType(OperandNode->getValueAsDef("Type"));
Nate Begemanb73628b2005-12-30 00:12:56 +0000775 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000776 } else {
777 assert(0 && "Unknown operand type!");
778 abort();
779 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000780 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000781 }
782 return MadeChange;
783 } else {
784 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
785
Evan Chengf26ba692006-03-20 08:09:17 +0000786 // Node transforms always take one operand.
Chris Lattnera28aec12005-09-15 22:23:50 +0000787 if (getNumChildren() != 1)
788 TP.error("Node transform '" + getOperator()->getName() +
789 "' requires one operand!");
Chris Lattner4e2f54d2006-03-21 06:42:58 +0000790
791 // If either the output or input of the xform does not have exact
792 // type info. We assume they must be the same. Otherwise, it is perfectly
793 // legal to transform from one type to a completely different type.
794 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Evan Chengf26ba692006-03-20 08:09:17 +0000795 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
796 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
797 return MadeChange;
798 }
799 return false;
Chris Lattner32707602005-09-08 23:22:48 +0000800 }
Chris Lattner32707602005-09-08 23:22:48 +0000801}
802
Chris Lattnere97603f2005-09-28 19:27:25 +0000803/// canPatternMatch - If it is impossible for this pattern to match on this
804/// target, fill in Reason and return false. Otherwise, return true. This is
805/// used as a santity check for .td files (to prevent people from writing stuff
806/// that can never possibly work), and to prevent the pattern permuter from
807/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000808bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000809 if (isLeaf()) return true;
810
811 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
812 if (!getChild(i)->canPatternMatch(Reason, ISE))
813 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000814
Chris Lattner550525e2006-03-24 21:48:51 +0000815 // If this is an intrinsic, handle cases that would make it not match. For
816 // example, if an operand is required to be an immediate.
817 if (getOperator()->isSubClassOf("Intrinsic")) {
818 // TODO:
819 return true;
820 }
821
Chris Lattnere97603f2005-09-28 19:27:25 +0000822 // If this node is a commutative operator, check that the LHS isn't an
823 // immediate.
824 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
825 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
826 // Scan all of the operands of the node and make sure that only the last one
Chris Lattner7905c552006-09-14 23:54:24 +0000827 // is a constant node, unless the RHS also is.
828 if (getChild(getNumChildren()-1)->isLeaf() ||
829 getChild(getNumChildren()-1)->getOperator()->getName() != "imm") {
830 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
831 if (!getChild(i)->isLeaf() &&
832 getChild(i)->getOperator()->getName() == "imm") {
833 Reason = "Immediate value must be on the RHS of commutative operators!";
834 return false;
835 }
836 }
Chris Lattnere97603f2005-09-28 19:27:25 +0000837 }
838
839 return true;
840}
Chris Lattner32707602005-09-08 23:22:48 +0000841
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000842//===----------------------------------------------------------------------===//
843// TreePattern implementation
844//
845
Chris Lattneredbd8712005-10-21 01:19:59 +0000846TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000847 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000848 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000849 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
850 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000851}
852
Chris Lattneredbd8712005-10-21 01:19:59 +0000853TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000854 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000855 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000856 Trees.push_back(ParseTreePattern(Pat));
857}
858
Chris Lattneredbd8712005-10-21 01:19:59 +0000859TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000860 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000861 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000862 Trees.push_back(Pat);
863}
864
865
866
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000867void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000868 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000869 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000870}
871
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000872TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
Chris Lattner8c063182006-03-30 22:50:40 +0000873 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
874 if (!OpDef) error("Pattern has unexpected operator type!");
875 Record *Operator = OpDef->getDef();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000876
877 if (Operator->isSubClassOf("ValueType")) {
878 // If the operator is a ValueType, then this must be "type cast" of a leaf
879 // node.
880 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000881 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000882
883 Init *Arg = Dag->getArg(0);
884 TreePatternNode *New;
885 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000886 Record *R = DI->getDef();
887 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000888 Dag->setArg(0, new DagInit(DI,
Chris Lattner72fe91c2005-09-24 00:40:24 +0000889 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000890 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000891 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000892 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000893 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
894 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000895 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
896 New = new TreePatternNode(II);
897 if (!Dag->getArgName(0).empty())
898 error("Constant int argument should not have a name!");
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000899 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
900 // Turn this into an IntInit.
901 Init *II = BI->convertInitializerTo(new IntRecTy());
902 if (II == 0 || !dynamic_cast<IntInit*>(II))
903 error("Bits value must be constants!");
904
905 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
906 if (!Dag->getArgName(0).empty())
907 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000908 } else {
909 Arg->dump();
910 error("Unknown leaf value for tree pattern!");
911 return 0;
912 }
913
Chris Lattner32707602005-09-08 23:22:48 +0000914 // Apply the type cast.
915 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000916 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000917 return New;
918 }
919
920 // Verify that this is something that makes sense for an operator.
921 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000922 !Operator->isSubClassOf("Instruction") &&
923 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner550525e2006-03-24 21:48:51 +0000924 !Operator->isSubClassOf("Intrinsic") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000925 Operator->getName() != "set")
926 error("Unrecognized node '" + Operator->getName() + "'!");
927
Chris Lattneredbd8712005-10-21 01:19:59 +0000928 // Check to see if this is something that is illegal in an input pattern.
929 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
Chris Lattner5a1df382006-03-24 23:10:39 +0000930 Operator->isSubClassOf("SDNodeXForm")))
Chris Lattneredbd8712005-10-21 01:19:59 +0000931 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
932
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000933 std::vector<TreePatternNode*> Children;
934
935 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
936 Init *Arg = Dag->getArg(i);
937 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
938 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000939 if (Children.back()->getName().empty())
940 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000941 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
942 Record *R = DefI->getDef();
943 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
944 // TreePatternNode if its own.
945 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000946 Dag->setArg(i, new DagInit(DefI,
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000947 std::vector<std::pair<Init*, std::string> >()));
948 --i; // Revisit this node...
949 } else {
950 TreePatternNode *Node = new TreePatternNode(DefI);
951 Node->setName(Dag->getArgName(i));
952 Children.push_back(Node);
953
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000954 // Input argument?
955 if (R->getName() == "node") {
956 if (Dag->getArgName(i).empty())
957 error("'node' argument requires a name to match with operand list");
958 Args.push_back(Dag->getArgName(i));
959 }
960 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000961 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
962 TreePatternNode *Node = new TreePatternNode(II);
963 if (!Dag->getArgName(i).empty())
964 error("Constant int argument should not have a name!");
965 Children.push_back(Node);
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000966 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
967 // Turn this into an IntInit.
968 Init *II = BI->convertInitializerTo(new IntRecTy());
969 if (II == 0 || !dynamic_cast<IntInit*>(II))
970 error("Bits value must be constants!");
971
972 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
973 if (!Dag->getArgName(i).empty())
974 error("Constant int argument should not have a name!");
975 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000976 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000977 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000978 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000979 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000980 error("Unknown leaf value for tree pattern!");
981 }
982 }
983
Chris Lattner5a1df382006-03-24 23:10:39 +0000984 // If the operator is an intrinsic, then this is just syntactic sugar for for
985 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
986 // convert the intrinsic name to a number.
987 if (Operator->isSubClassOf("Intrinsic")) {
988 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
989 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
990
991 // If this intrinsic returns void, it must have side-effects and thus a
992 // chain.
993 if (Int.ArgVTs[0] == MVT::isVoid) {
994 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
995 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
996 // Has side-effects, requires chain.
997 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
998 } else {
999 // Otherwise, no chain.
1000 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
1001 }
1002
1003 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1004 Children.insert(Children.begin(), IIDNode);
1005 }
1006
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001007 return new TreePatternNode(Operator, Children);
1008}
1009
Chris Lattner32707602005-09-08 23:22:48 +00001010/// InferAllTypes - Infer/propagate as many types throughout the expression
1011/// patterns as possible. Return true if all types are infered, false
1012/// otherwise. Throw an exception if a type contradiction is found.
1013bool TreePattern::InferAllTypes() {
1014 bool MadeChange = true;
1015 while (MadeChange) {
1016 MadeChange = false;
1017 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001018 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +00001019 }
1020
1021 bool HasUnresolvedTypes = false;
1022 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1023 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1024 return !HasUnresolvedTypes;
1025}
1026
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001027void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001028 OS << getRecord()->getName();
1029 if (!Args.empty()) {
1030 OS << "(" << Args[0];
1031 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1032 OS << ", " << Args[i];
1033 OS << ")";
1034 }
1035 OS << ": ";
1036
1037 if (Trees.size() > 1)
1038 OS << "[\n";
1039 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1040 OS << "\t";
1041 Trees[i]->print(OS);
1042 OS << "\n";
1043 }
1044
1045 if (Trees.size() > 1)
1046 OS << "]\n";
1047}
1048
1049void TreePattern::dump() const { print(std::cerr); }
1050
1051
1052
1053//===----------------------------------------------------------------------===//
1054// DAGISelEmitter implementation
1055//
1056
Chris Lattnerca559d02005-09-08 21:03:01 +00001057// Parse all of the SDNode definitions for the target, populating SDNodes.
1058void DAGISelEmitter::ParseNodeInfo() {
1059 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1060 while (!Nodes.empty()) {
1061 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1062 Nodes.pop_back();
1063 }
Chris Lattner5a1df382006-03-24 23:10:39 +00001064
1065 // Get the buildin intrinsic nodes.
1066 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1067 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1068 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
Chris Lattnerca559d02005-09-08 21:03:01 +00001069}
1070
Chris Lattner24eeeb82005-09-13 21:51:00 +00001071/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1072/// map, and emit them to the file as functions.
1073void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1074 OS << "\n// Node transformations.\n";
1075 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1076 while (!Xforms.empty()) {
1077 Record *XFormNode = Xforms.back();
1078 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1079 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1080 SDNodeXForms.insert(std::make_pair(XFormNode,
1081 std::make_pair(SDNode, Code)));
1082
Chris Lattner1048b7a2005-09-13 22:03:37 +00001083 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +00001084 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1085 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1086
Chris Lattner1048b7a2005-09-13 22:03:37 +00001087 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +00001088 << "(SDNode *" << C2 << ") {\n";
1089 if (ClassName != "SDNode")
1090 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1091 OS << Code << "\n}\n";
1092 }
1093
1094 Xforms.pop_back();
1095 }
1096}
1097
Evan Cheng0fc71982005-12-08 02:00:36 +00001098void DAGISelEmitter::ParseComplexPatterns() {
1099 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1100 while (!AMs.empty()) {
1101 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1102 AMs.pop_back();
1103 }
1104}
Chris Lattner24eeeb82005-09-13 21:51:00 +00001105
1106
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001107/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1108/// file, building up the PatternFragments map. After we've collected them all,
1109/// inline fragments together as necessary, so that there are no references left
1110/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001111///
1112/// This also emits all of the predicate functions to the output file.
1113///
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001114void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001115 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1116
1117 // First step, parse all of the fragments and emit predicate functions.
1118 OS << "\n// Predicate functions.\n";
1119 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001120 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +00001121 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001122 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +00001123
1124 // Validate the argument list, converting it to map, to discard duplicates.
1125 std::vector<std::string> &Args = P->getArgList();
1126 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1127
1128 if (OperandsMap.count(""))
1129 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1130
1131 // Parse the operands list.
1132 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Chris Lattner8c063182006-03-30 22:50:40 +00001133 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1134 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
Chris Lattneree9f0c32005-09-13 21:20:49 +00001135 P->error("Operands list should start with '(ops ... '!");
1136
1137 // Copy over the arguments.
1138 Args.clear();
1139 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1140 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1141 static_cast<DefInit*>(OpsList->getArg(j))->
1142 getDef()->getName() != "node")
1143 P->error("Operands list should all be 'node' values.");
1144 if (OpsList->getArgName(j).empty())
1145 P->error("Operands list should have names for each operand!");
1146 if (!OperandsMap.count(OpsList->getArgName(j)))
1147 P->error("'" + OpsList->getArgName(j) +
1148 "' does not occur in pattern or was multiply specified!");
1149 OperandsMap.erase(OpsList->getArgName(j));
1150 Args.push_back(OpsList->getArgName(j));
1151 }
1152
1153 if (!OperandsMap.empty())
1154 P->error("Operands list does not contain an entry for operand '" +
1155 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001156
1157 // If there is a code init for this fragment, emit the predicate code and
1158 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +00001159 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1160 if (!Code.empty()) {
Evan Chengd46bd602006-09-19 19:08:04 +00001161 if (P->getOnlyTree()->isLeaf())
1162 OS << "inline bool Predicate_" << Fragments[i]->getName()
1163 << "(SDNode *N) {\n";
1164 else {
1165 std::string ClassName =
1166 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1167 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001168
Evan Chengd46bd602006-09-19 19:08:04 +00001169 OS << "inline bool Predicate_" << Fragments[i]->getName()
1170 << "(SDNode *" << C2 << ") {\n";
1171 if (ClassName != "SDNode")
1172 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1173 }
Chris Lattner24eeeb82005-09-13 21:51:00 +00001174 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +00001175 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001176 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001177
1178 // If there is a node transformation corresponding to this, keep track of
1179 // it.
1180 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1181 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001182 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001183 }
1184
1185 OS << "\n\n";
1186
1187 // Now that we've parsed all of the tree fragments, do a closure on them so
1188 // that there are not references to PatFrags left inside of them.
1189 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1190 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001191 TreePattern *ThePat = I->second;
1192 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001193
Chris Lattner32707602005-09-08 23:22:48 +00001194 // Infer as many types as possible. Don't worry about it if we don't infer
1195 // all of them, some may depend on the inputs of the pattern.
1196 try {
1197 ThePat->InferAllTypes();
1198 } catch (...) {
1199 // If this pattern fragment is not supported by this target (no types can
1200 // satisfy its constraints), just ignore it. If the bogus pattern is
1201 // actually used by instructions, the type consistency error will be
1202 // reported there.
1203 }
1204
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001205 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001206 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001207 }
1208}
1209
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001210/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001211/// instruction input. Return true if this is a real use.
1212static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001213 std::map<std::string, TreePatternNode*> &InstInputs,
1214 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001215 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001216 if (Pat->getName().empty()) {
1217 if (Pat->isLeaf()) {
1218 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1219 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1220 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001221 else if (DI && DI->getDef()->isSubClassOf("Register"))
1222 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001223 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001224 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001225 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001226
1227 Record *Rec;
1228 if (Pat->isLeaf()) {
1229 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1230 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1231 Rec = DI->getDef();
1232 } else {
1233 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1234 Rec = Pat->getOperator();
1235 }
1236
Evan Cheng01f318b2005-12-14 02:21:57 +00001237 // SRCVALUE nodes are ignored.
1238 if (Rec->getName() == "srcvalue")
1239 return false;
1240
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001241 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1242 if (!Slot) {
1243 Slot = Pat;
1244 } else {
1245 Record *SlotRec;
1246 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001247 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001248 } else {
1249 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1250 SlotRec = Slot->getOperator();
1251 }
1252
1253 // Ensure that the inputs agree if we've already seen this input.
1254 if (Rec != SlotRec)
1255 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001256 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001257 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1258 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001259 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001260}
1261
1262/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1263/// part of "I", the instruction), computing the set of inputs and outputs of
1264/// the pattern. Report errors if we see anything naughty.
1265void DAGISelEmitter::
1266FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1267 std::map<std::string, TreePatternNode*> &InstInputs,
Chris Lattner947604b2006-03-24 21:52:20 +00001268 std::map<std::string, TreePatternNode*>&InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001269 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001270 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001271 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001272 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001273 if (!isUse && Pat->getTransformFn())
1274 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001275 return;
1276 } else if (Pat->getOperator()->getName() != "set") {
1277 // If this is not a set, verify that the children nodes are not void typed,
1278 // and recurse.
1279 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001280 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001281 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001282 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001283 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001284 }
1285
1286 // If this is a non-leaf node with no children, treat it basically as if
1287 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001288 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001289 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001290 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001291
Chris Lattnerf1311842005-09-14 23:05:13 +00001292 if (!isUse && Pat->getTransformFn())
1293 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001294 return;
1295 }
1296
1297 // Otherwise, this is a set, validate and collect instruction results.
1298 if (Pat->getNumChildren() == 0)
1299 I->error("set requires operands!");
1300 else if (Pat->getNumChildren() & 1)
1301 I->error("set requires an even number of operands");
1302
Chris Lattnerf1311842005-09-14 23:05:13 +00001303 if (Pat->getTransformFn())
1304 I->error("Cannot specify a transform function on a set node!");
1305
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001306 // Check the set destinations.
1307 unsigned NumValues = Pat->getNumChildren()/2;
1308 for (unsigned i = 0; i != NumValues; ++i) {
1309 TreePatternNode *Dest = Pat->getChild(i);
1310 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001311 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001312
1313 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1314 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001315 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001316
Evan Chengbcecf332005-12-17 01:19:28 +00001317 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1318 if (Dest->getName().empty())
1319 I->error("set destination must have a name!");
1320 if (InstResults.count(Dest->getName()))
1321 I->error("cannot set '" + Dest->getName() +"' multiple times");
Evan Cheng420132e2006-03-20 06:04:09 +00001322 InstResults[Dest->getName()] = Dest;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001323 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001324 InstImpResults.push_back(Val->getDef());
1325 } else {
1326 I->error("set destination should be a register!");
1327 }
1328
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001329 // Verify and collect info from the computation.
1330 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001331 InstInputs, InstResults,
1332 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001333 }
1334}
1335
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001336/// ParseInstructions - Parse all of the instructions, inlining and resolving
1337/// any fragments involved. This populates the Instructions list with fully
1338/// resolved instructions.
1339void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001340 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1341
1342 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001343 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001344
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001345 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1346 LI = Instrs[i]->getValueAsListInit("Pattern");
1347
1348 // If there is no pattern, only collect minimal information about the
1349 // instruction for its operand list. We have to assume that there is one
1350 // result, as we have no detailed info.
1351 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001352 std::vector<Record*> Results;
1353 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001354
1355 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001356
Evan Cheng3a217f32005-12-22 02:35:21 +00001357 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001358 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001359 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001360 // These produce no results
1361 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1362 Operands.push_back(InstInfo.OperandList[j].Rec);
1363 } else {
1364 // Assume the first operand is the result.
1365 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001366
Evan Cheng3a217f32005-12-22 02:35:21 +00001367 // The rest are inputs.
1368 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1369 Operands.push_back(InstInfo.OperandList[j].Rec);
1370 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001371 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001372
1373 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001374 std::vector<Record*> ImpResults;
1375 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001376 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001377 DAGInstruction(0, Results, Operands, ImpResults,
1378 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001379 continue; // no pattern.
1380 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001381
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001382 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001383 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001384 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001385 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001386
Chris Lattner95f6b762005-09-08 23:26:30 +00001387 // Infer as many types as possible. If we cannot infer all of them, we can
1388 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001389 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001390 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001391
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001392 // InstInputs - Keep track of all of the inputs of the instruction, along
1393 // with the record they are declared as.
1394 std::map<std::string, TreePatternNode*> InstInputs;
1395
1396 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001397 // in the instruction, including what reg class they are.
Evan Cheng420132e2006-03-20 06:04:09 +00001398 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001399
1400 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001401 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001402
Chris Lattner1f39e292005-09-14 00:09:24 +00001403 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001404 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001405 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1406 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001407 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001408 I->error("Top-level forms in instruction pattern should have"
1409 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001410
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001411 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001412 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001413 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001414 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001415
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001416 // Now that we have inputs and outputs of the pattern, inspect the operands
1417 // list for the instruction. This determines the order that operands are
1418 // added to the machine instruction the node corresponds to.
1419 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001420
1421 // Parse the operands list from the (ops) list, validating it.
1422 std::vector<std::string> &Args = I->getArgList();
1423 assert(Args.empty() && "Args list should still be empty here!");
1424 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1425
1426 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001427 std::vector<Record*> Results;
Evan Cheng420132e2006-03-20 06:04:09 +00001428 TreePatternNode *Res0Node = NULL;
Chris Lattner39e8af92005-09-14 18:19:25 +00001429 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001430 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001431 I->error("'" + InstResults.begin()->first +
1432 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001433 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001434
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001435 // Check that it exists in InstResults.
Evan Cheng420132e2006-03-20 06:04:09 +00001436 TreePatternNode *RNode = InstResults[OpName];
Chris Lattner5c4c7742006-03-25 22:12:44 +00001437 if (RNode == 0)
1438 I->error("Operand $" + OpName + " does not exist in operand list!");
1439
Evan Cheng420132e2006-03-20 06:04:09 +00001440 if (i == 0)
1441 Res0Node = RNode;
1442 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner39e8af92005-09-14 18:19:25 +00001443 if (R == 0)
1444 I->error("Operand $" + OpName + " should be a set destination: all "
1445 "outputs must occur before inputs in operand list!");
1446
1447 if (CGI.OperandList[i].Rec != R)
1448 I->error("Operand $" + OpName + " class mismatch!");
1449
Chris Lattnerae6d8282005-09-15 21:51:12 +00001450 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001451 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001452
Chris Lattner39e8af92005-09-14 18:19:25 +00001453 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001454 InstResults.erase(OpName);
1455 }
1456
Chris Lattner0b592252005-09-14 21:59:34 +00001457 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1458 // the copy while we're checking the inputs.
1459 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001460
1461 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001462 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001463 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1464 const std::string &OpName = CGI.OperandList[i].Name;
1465 if (OpName.empty())
1466 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1467
Chris Lattner0b592252005-09-14 21:59:34 +00001468 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001469 I->error("Operand $" + OpName +
1470 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001471 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001472 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001473
1474 if (InVal->isLeaf() &&
1475 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1476 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001477 if (CGI.OperandList[i].Rec != InRec &&
1478 !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001479 I->error("Operand $" + OpName + "'s register class disagrees"
1480 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001481 }
1482 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001483
Chris Lattner2175c182005-09-14 23:01:59 +00001484 // Construct the result for the dest-pattern operand list.
1485 TreePatternNode *OpNode = InVal->clone();
1486
1487 // No predicate is useful on the result.
1488 OpNode->setPredicateFn("");
1489
1490 // Promote the xform function to be an explicit node if set.
1491 if (Record *Xform = OpNode->getTransformFn()) {
1492 OpNode->setTransformFn(0);
1493 std::vector<TreePatternNode*> Children;
1494 Children.push_back(OpNode);
1495 OpNode = new TreePatternNode(Xform, Children);
1496 }
1497
1498 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001499 }
1500
Chris Lattner0b592252005-09-14 21:59:34 +00001501 if (!InstInputsCheck.empty())
1502 I->error("Input operand $" + InstInputsCheck.begin()->first +
1503 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001504
1505 TreePatternNode *ResultPattern =
1506 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Evan Cheng420132e2006-03-20 06:04:09 +00001507 // Copy fully inferred output node type to instruction result pattern.
1508 if (NumResults > 0)
1509 ResultPattern->setTypes(Res0Node->getExtTypes());
Chris Lattnera28aec12005-09-15 22:23:50 +00001510
1511 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001512 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001513 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1514
1515 // Use a temporary tree pattern to infer all types and make sure that the
1516 // constructed result is correct. This depends on the instruction already
1517 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001518 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001519 Temp.InferAllTypes();
1520
1521 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1522 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001523
Chris Lattner32707602005-09-08 23:22:48 +00001524 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001525 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001526
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001527 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001528 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1529 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001530 DAGInstruction &TheInst = II->second;
1531 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001532 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001533
Chris Lattner1f39e292005-09-14 00:09:24 +00001534 if (I->getNumTrees() != 1) {
1535 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1536 continue;
1537 }
1538 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001539 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001540 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001541 if (Pattern->getNumChildren() != 2)
1542 continue; // Not a set of a single value (not handled so far)
1543
1544 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001545 } else{
1546 // Not a set (store or something?)
1547 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001548 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001549
1550 std::string Reason;
1551 if (!SrcPattern->canPatternMatch(Reason, *this))
1552 I->error("Instruction can never match: " + Reason);
1553
Evan Cheng58e84a62005-12-14 22:02:59 +00001554 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001555 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001556 PatternsToMatch.
1557 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
Evan Cheng59413202006-04-19 18:07:24 +00001558 SrcPattern, DstPattern,
Evan Chengc81d2a02006-04-19 20:36:09 +00001559 Instr->getValueAsInt("AddedComplexity")));
Chris Lattner1f39e292005-09-14 00:09:24 +00001560 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001561}
1562
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001563void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001564 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001565
Chris Lattnerabbb6052005-09-15 21:42:00 +00001566 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001567 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001568 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001569
Chris Lattnerabbb6052005-09-15 21:42:00 +00001570 // Inline pattern fragments into it.
1571 Pattern->InlinePatternFragments();
1572
Chris Lattnera3548492006-06-20 00:18:02 +00001573 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1574 if (LI->getSize() == 0) continue; // no pattern.
1575
1576 // Parse the instruction.
1577 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1578
1579 // Inline pattern fragments into it.
1580 Result->InlinePatternFragments();
Chris Lattner09c03392005-11-17 17:43:52 +00001581
Chris Lattnera3548492006-06-20 00:18:02 +00001582 if (Result->getNumTrees() != 1)
1583 Result->error("Cannot handle instructions producing instructions "
1584 "with temporaries yet!");
1585
1586 bool IterateInference;
Chris Lattner186fb7d2006-06-20 00:31:27 +00001587 bool InferredAllPatternTypes, InferredAllResultTypes;
Chris Lattnera3548492006-06-20 00:18:02 +00001588 do {
1589 // Infer as many types as possible. If we cannot infer all of them, we
1590 // can never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001591 InferredAllPatternTypes = Pattern->InferAllTypes();
Chris Lattnera3548492006-06-20 00:18:02 +00001592
1593 // Infer as many types as possible. If we cannot infer all of them, we can
1594 // never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001595 InferredAllResultTypes = Result->InferAllTypes();
1596
Chris Lattnera3548492006-06-20 00:18:02 +00001597 // Apply the type of the result to the source pattern. This helps us
1598 // resolve cases where the input type is known to be a pointer type (which
1599 // is considered resolved), but the result knows it needs to be 32- or
1600 // 64-bits. Infer the other way for good measure.
1601 IterateInference = Pattern->getOnlyTree()->
1602 UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1603 IterateInference |= Result->getOnlyTree()->
1604 UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1605 } while (IterateInference);
Chris Lattner186fb7d2006-06-20 00:31:27 +00001606
1607 // Verify that we inferred enough types that we can do something with the
1608 // pattern and result. If these fire the user has to add type casts.
1609 if (!InferredAllPatternTypes)
1610 Pattern->error("Could not infer all types in pattern!");
1611 if (!InferredAllResultTypes)
1612 Result->error("Could not infer all types in pattern result!");
Chris Lattnera3548492006-06-20 00:18:02 +00001613
Chris Lattner09c03392005-11-17 17:43:52 +00001614 // Validate that the input pattern is correct.
1615 {
1616 std::map<std::string, TreePatternNode*> InstInputs;
Evan Cheng420132e2006-03-20 06:04:09 +00001617 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001618 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001619 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001620 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001621 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001622 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001623 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001624
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001625 // Promote the xform function to be an explicit node if set.
1626 std::vector<TreePatternNode*> ResultNodeOperands;
1627 TreePatternNode *DstPattern = Result->getOnlyTree();
1628 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1629 TreePatternNode *OpNode = DstPattern->getChild(ii);
1630 if (Record *Xform = OpNode->getTransformFn()) {
1631 OpNode->setTransformFn(0);
1632 std::vector<TreePatternNode*> Children;
1633 Children.push_back(OpNode);
1634 OpNode = new TreePatternNode(Xform, Children);
1635 }
1636 ResultNodeOperands.push_back(OpNode);
1637 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00001638 DstPattern = Result->getOnlyTree();
1639 if (!DstPattern->isLeaf())
1640 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1641 ResultNodeOperands);
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001642 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1643 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1644 Temp.InferAllTypes();
1645
Chris Lattnere97603f2005-09-28 19:27:25 +00001646 std::string Reason;
1647 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1648 Pattern->error("Pattern can never match: " + Reason);
1649
Evan Cheng58e84a62005-12-14 22:02:59 +00001650 PatternsToMatch.
1651 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1652 Pattern->getOnlyTree(),
Evan Cheng59413202006-04-19 18:07:24 +00001653 Temp.getOnlyTree(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001654 Patterns[i]->getValueAsInt("AddedComplexity")));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001655 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001656}
1657
Chris Lattnere46e17b2005-09-29 19:28:10 +00001658/// CombineChildVariants - Given a bunch of permutations of each child of the
1659/// 'operator' node, put them together in all possible ways.
1660static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001661 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001662 std::vector<TreePatternNode*> &OutVariants,
1663 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001664 // Make sure that each operand has at least one variant to choose from.
1665 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1666 if (ChildVariants[i].empty())
1667 return;
1668
Chris Lattnere46e17b2005-09-29 19:28:10 +00001669 // The end result is an all-pairs construction of the resultant pattern.
1670 std::vector<unsigned> Idxs;
1671 Idxs.resize(ChildVariants.size());
1672 bool NotDone = true;
1673 while (NotDone) {
1674 // Create the variant and add it to the output list.
1675 std::vector<TreePatternNode*> NewChildren;
1676 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1677 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1678 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1679
1680 // Copy over properties.
1681 R->setName(Orig->getName());
1682 R->setPredicateFn(Orig->getPredicateFn());
1683 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001684 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001685
1686 // If this pattern cannot every match, do not include it as a variant.
1687 std::string ErrString;
1688 if (!R->canPatternMatch(ErrString, ISE)) {
1689 delete R;
1690 } else {
1691 bool AlreadyExists = false;
1692
1693 // Scan to see if this pattern has already been emitted. We can get
1694 // duplication due to things like commuting:
1695 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1696 // which are the same pattern. Ignore the dups.
1697 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1698 if (R->isIsomorphicTo(OutVariants[i])) {
1699 AlreadyExists = true;
1700 break;
1701 }
1702
1703 if (AlreadyExists)
1704 delete R;
1705 else
1706 OutVariants.push_back(R);
1707 }
1708
1709 // Increment indices to the next permutation.
1710 NotDone = false;
1711 // Look for something we can increment without causing a wrap-around.
1712 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1713 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1714 NotDone = true; // Found something to increment.
1715 break;
1716 }
1717 Idxs[IdxsIdx] = 0;
1718 }
1719 }
1720}
1721
Chris Lattneraf302912005-09-29 22:36:54 +00001722/// CombineChildVariants - A helper function for binary operators.
1723///
1724static void CombineChildVariants(TreePatternNode *Orig,
1725 const std::vector<TreePatternNode*> &LHS,
1726 const std::vector<TreePatternNode*> &RHS,
1727 std::vector<TreePatternNode*> &OutVariants,
1728 DAGISelEmitter &ISE) {
1729 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1730 ChildVariants.push_back(LHS);
1731 ChildVariants.push_back(RHS);
1732 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1733}
1734
1735
1736static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1737 std::vector<TreePatternNode *> &Children) {
1738 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1739 Record *Operator = N->getOperator();
1740
1741 // Only permit raw nodes.
1742 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1743 N->getTransformFn()) {
1744 Children.push_back(N);
1745 return;
1746 }
1747
1748 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1749 Children.push_back(N->getChild(0));
1750 else
1751 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1752
1753 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1754 Children.push_back(N->getChild(1));
1755 else
1756 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1757}
1758
Chris Lattnere46e17b2005-09-29 19:28:10 +00001759/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1760/// the (potentially recursive) pattern by using algebraic laws.
1761///
1762static void GenerateVariantsOf(TreePatternNode *N,
1763 std::vector<TreePatternNode*> &OutVariants,
1764 DAGISelEmitter &ISE) {
1765 // We cannot permute leaves.
1766 if (N->isLeaf()) {
1767 OutVariants.push_back(N);
1768 return;
1769 }
1770
1771 // Look up interesting info about the node.
Chris Lattner5a1df382006-03-24 23:10:39 +00001772 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001773
1774 // If this node is associative, reassociate.
Chris Lattner5a1df382006-03-24 23:10:39 +00001775 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
Chris Lattneraf302912005-09-29 22:36:54 +00001776 // Reassociate by pulling together all of the linked operators
1777 std::vector<TreePatternNode*> MaximalChildren;
1778 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1779
1780 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1781 // permutations.
1782 if (MaximalChildren.size() == 3) {
1783 // Find the variants of all of our maximal children.
1784 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1785 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1786 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1787 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1788
1789 // There are only two ways we can permute the tree:
1790 // (A op B) op C and A op (B op C)
1791 // Within these forms, we can also permute A/B/C.
1792
1793 // Generate legal pair permutations of A/B/C.
1794 std::vector<TreePatternNode*> ABVariants;
1795 std::vector<TreePatternNode*> BAVariants;
1796 std::vector<TreePatternNode*> ACVariants;
1797 std::vector<TreePatternNode*> CAVariants;
1798 std::vector<TreePatternNode*> BCVariants;
1799 std::vector<TreePatternNode*> CBVariants;
1800 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1801 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1802 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1803 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1804 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1805 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1806
1807 // Combine those into the result: (x op x) op x
1808 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1809 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1810 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1811 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1812 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1813 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1814
1815 // Combine those into the result: x op (x op x)
1816 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1817 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1818 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1819 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1820 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1821 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1822 return;
1823 }
1824 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001825
1826 // Compute permutations of all children.
1827 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1828 ChildVariants.resize(N->getNumChildren());
1829 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1830 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1831
1832 // Build all permutations based on how the children were formed.
1833 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1834
1835 // If this node is commutative, consider the commuted order.
Chris Lattner5a1df382006-03-24 23:10:39 +00001836 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001837 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattner706d2d32006-08-09 16:44:44 +00001838 // Don't count children which are actually register references.
1839 unsigned NC = 0;
1840 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1841 TreePatternNode *Child = N->getChild(i);
1842 if (Child->isLeaf())
1843 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1844 Record *RR = DI->getDef();
1845 if (RR->isSubClassOf("Register"))
1846 continue;
1847 }
1848 NC++;
1849 }
Chris Lattneraf302912005-09-29 22:36:54 +00001850 // Consider the commuted order.
Chris Lattner706d2d32006-08-09 16:44:44 +00001851 if (NC == 2)
1852 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1853 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001854 }
1855}
1856
1857
Chris Lattnere97603f2005-09-28 19:27:25 +00001858// GenerateVariants - Generate variants. For example, commutative patterns can
1859// match multiple ways. Add them to PatternsToMatch as well.
1860void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001861
1862 DEBUG(std::cerr << "Generating instruction variants.\n");
1863
1864 // Loop over all of the patterns we've collected, checking to see if we can
1865 // generate variants of the instruction, through the exploitation of
1866 // identities. This permits the target to provide agressive matching without
1867 // the .td file having to contain tons of variants of instructions.
1868 //
1869 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1870 // intentionally do not reconsider these. Any variants of added patterns have
1871 // already been added.
1872 //
1873 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1874 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001875 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001876
1877 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001878 Variants.erase(Variants.begin()); // Remove the original pattern.
1879
1880 if (Variants.empty()) // No variants for this pattern.
1881 continue;
1882
1883 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001884 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001885 std::cerr << "\n");
1886
1887 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1888 TreePatternNode *Variant = Variants[v];
1889
1890 DEBUG(std::cerr << " VAR#" << v << ": ";
1891 Variant->dump();
1892 std::cerr << "\n");
1893
1894 // Scan to see if an instruction or explicit pattern already matches this.
1895 bool AlreadyExists = false;
1896 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1897 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001898 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001899 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1900 AlreadyExists = true;
1901 break;
1902 }
1903 }
1904 // If we already have it, ignore the variant.
1905 if (AlreadyExists) continue;
1906
1907 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001908 PatternsToMatch.
1909 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
Evan Cheng59413202006-04-19 18:07:24 +00001910 Variant, PatternsToMatch[i].getDstPattern(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001911 PatternsToMatch[i].getAddedComplexity()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001912 }
1913
1914 DEBUG(std::cerr << "\n");
1915 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001916}
1917
Evan Cheng0fc71982005-12-08 02:00:36 +00001918// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1919// ComplexPattern.
1920static bool NodeIsComplexPattern(TreePatternNode *N)
1921{
1922 return (N->isLeaf() &&
1923 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1924 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1925 isSubClassOf("ComplexPattern"));
1926}
1927
1928// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1929// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1930static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1931 DAGISelEmitter &ISE)
1932{
1933 if (N->isLeaf() &&
1934 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1935 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1936 isSubClassOf("ComplexPattern")) {
1937 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1938 ->getDef());
1939 }
1940 return NULL;
1941}
1942
Chris Lattner05814af2005-09-28 17:57:56 +00001943/// getPatternSize - Return the 'size' of this pattern. We want to match large
1944/// patterns before small ones. This is used to determine the size of a
1945/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001946static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng2618d072006-05-17 20:37:59 +00001947 assert((isExtIntegerInVTs(P->getExtTypes()) ||
1948 isExtFloatingPointInVTs(P->getExtTypes()) ||
1949 P->getExtTypeNum(0) == MVT::isVoid ||
1950 P->getExtTypeNum(0) == MVT::Flag ||
1951 P->getExtTypeNum(0) == MVT::iPTR) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +00001952 "Not a valid pattern node to size!");
Evan Cheng6cec34e2006-09-08 07:26:39 +00001953 unsigned Size = 3; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00001954 // If the root node is a ConstantSDNode, increases its size.
1955 // e.g. (set R32:$dst, 0).
1956 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +00001957 Size += 2;
Evan Cheng0fc71982005-12-08 02:00:36 +00001958
1959 // FIXME: This is a hack to statically increase the priority of patterns
1960 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1961 // Later we can allow complexity / cost for each pattern to be (optionally)
1962 // specified. To get best possible pattern match we'll need to dynamically
1963 // calculate the complexity of all patterns a dag can potentially map to.
1964 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1965 if (AM)
Evan Cheng6cec34e2006-09-08 07:26:39 +00001966 Size += AM->getNumOperands() * 3;
Chris Lattner3e179802006-02-03 18:06:02 +00001967
1968 // If this node has some predicate function that must match, it adds to the
1969 // complexity of this node.
1970 if (!P->getPredicateFn().empty())
1971 ++Size;
1972
Chris Lattner05814af2005-09-28 17:57:56 +00001973 // Count children in the count if they are also nodes.
1974 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1975 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001976 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001977 Size += getPatternSize(Child, ISE);
1978 else if (Child->isLeaf()) {
1979 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +00001980 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Evan Cheng4a7c2842006-01-06 22:19:44 +00001981 else if (NodeIsComplexPattern(Child))
1982 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00001983 else if (!Child->getPredicateFn().empty())
1984 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00001985 }
Chris Lattner05814af2005-09-28 17:57:56 +00001986 }
1987
1988 return Size;
1989}
1990
1991/// getResultPatternCost - Compute the number of instructions for this pattern.
1992/// This is a temporary hack. We should really include the instruction
1993/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00001994static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00001995 if (P->isLeaf()) return 0;
1996
Evan Chengfbad7082006-02-18 02:33:09 +00001997 unsigned Cost = 0;
1998 Record *Op = P->getOperator();
1999 if (Op->isSubClassOf("Instruction")) {
2000 Cost++;
2001 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
2002 if (II.usesCustomDAGSchedInserter)
2003 Cost += 10;
2004 }
Chris Lattner05814af2005-09-28 17:57:56 +00002005 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00002006 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00002007 return Cost;
2008}
2009
Evan Chenge6f32032006-07-19 00:24:41 +00002010/// getResultPatternCodeSize - Compute the code size of instructions for this
2011/// pattern.
2012static unsigned getResultPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
2013 if (P->isLeaf()) return 0;
2014
2015 unsigned Cost = 0;
2016 Record *Op = P->getOperator();
2017 if (Op->isSubClassOf("Instruction")) {
2018 Cost += Op->getValueAsInt("CodeSize");
2019 }
2020 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2021 Cost += getResultPatternSize(P->getChild(i), ISE);
2022 return Cost;
2023}
2024
Chris Lattner05814af2005-09-28 17:57:56 +00002025// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
2026// In particular, we want to match maximal patterns first and lowest cost within
2027// a particular complexity first.
2028struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00002029 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
2030 DAGISelEmitter &ISE;
2031
Evan Cheng58e84a62005-12-14 22:02:59 +00002032 bool operator()(PatternToMatch *LHS,
2033 PatternToMatch *RHS) {
2034 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
2035 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Evan Chengc81d2a02006-04-19 20:36:09 +00002036 LHSSize += LHS->getAddedComplexity();
2037 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +00002038 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
2039 if (LHSSize < RHSSize) return false;
2040
2041 // If the patterns have equal complexity, compare generated instruction cost
Evan Chenge6f32032006-07-19 00:24:41 +00002042 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), ISE);
2043 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), ISE);
2044 if (LHSCost < RHSCost) return true;
2045 if (LHSCost > RHSCost) return false;
2046
2047 return getResultPatternSize(LHS->getDstPattern(), ISE) <
2048 getResultPatternSize(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00002049 }
2050};
2051
Nate Begeman6510b222005-12-01 04:51:06 +00002052/// getRegisterValueType - Look up and return the first ValueType of specified
2053/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00002054static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00002055 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2056 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00002057 return MVT::Other;
2058}
2059
Chris Lattner72fe91c2005-09-24 00:40:24 +00002060
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002061/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2062/// type information from it.
2063static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00002064 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002065 if (!N->isLeaf())
2066 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2067 RemoveAllTypes(N->getChild(i));
2068}
Chris Lattner72fe91c2005-09-24 00:40:24 +00002069
Chris Lattner0614b622005-11-02 06:49:14 +00002070Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2071 Record *N = Records.getDef(Name);
Chris Lattner5a1df382006-03-24 23:10:39 +00002072 if (!N || !N->isSubClassOf("SDNode")) {
2073 std::cerr << "Error getting SDNode '" << Name << "'!\n";
2074 exit(1);
2075 }
Chris Lattner0614b622005-11-02 06:49:14 +00002076 return N;
2077}
2078
Evan Cheng51fecc82006-01-09 18:27:06 +00002079/// NodeHasProperty - return true if TreePatternNode has the specified
2080/// property.
2081static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2082 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002083{
2084 if (N->isLeaf()) return false;
2085 Record *Operator = N->getOperator();
2086 if (!Operator->isSubClassOf("SDNode")) return false;
2087
2088 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00002089 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002090}
2091
Evan Cheng51fecc82006-01-09 18:27:06 +00002092static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2093 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002094{
Evan Cheng51fecc82006-01-09 18:27:06 +00002095 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00002096 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00002097
2098 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2099 TreePatternNode *Child = N->getChild(i);
2100 if (PatternHasProperty(Child, Property, ISE))
2101 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002102 }
2103
2104 return false;
2105}
2106
Evan Chengb915f312005-12-09 22:45:35 +00002107class PatternCodeEmitter {
2108private:
2109 DAGISelEmitter &ISE;
2110
Evan Cheng58e84a62005-12-14 22:02:59 +00002111 // Predicates.
2112 ListInit *Predicates;
Evan Cheng59413202006-04-19 18:07:24 +00002113 // Pattern cost.
2114 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +00002115 // Instruction selector pattern.
2116 TreePatternNode *Pattern;
2117 // Matched instruction.
2118 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002119
Evan Chengb915f312005-12-09 22:45:35 +00002120 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00002121 std::map<std::string, std::string> VariableMap;
2122 // Node to operator mapping
2123 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00002124 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002125 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00002126 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +00002127
Evan Cheng676d7312006-08-26 00:59:04 +00002128 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +00002129 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +00002130 /// tested, and if true, the match fails) [when 1], or normal code to emit
2131 /// [when 0], or initialization code to emit [when 2].
2132 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002133 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2134 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +00002135 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +00002136 /// TargetOpcodes - The target specific opcodes used by the resulting
2137 /// instructions.
2138 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +00002139 std::vector<std::string> &TargetVTs;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002140
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002141 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002142 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +00002143 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +00002144 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002145
2146 void emitCheck(const std::string &S) {
2147 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +00002148 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002149 }
2150 void emitCode(const std::string &S) {
2151 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +00002152 GeneratedCode.push_back(std::make_pair(0, S));
2153 }
2154 void emitInit(const std::string &S) {
2155 if (!S.empty())
2156 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002157 }
Evan Chengf5493192006-08-26 01:02:19 +00002158 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002159 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +00002160 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +00002161 }
Evan Chengfceb57a2006-07-15 08:45:20 +00002162 void emitOpcode(const std::string &Opc) {
2163 TargetOpcodes.push_back(Opc);
2164 OpcNo++;
2165 }
Evan Chengf8729402006-07-16 06:12:52 +00002166 void emitVT(const std::string &VT) {
2167 TargetVTs.push_back(VT);
2168 VTNo++;
2169 }
Evan Chengb915f312005-12-09 22:45:35 +00002170public:
Evan Cheng58e84a62005-12-14 22:02:59 +00002171 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2172 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +00002173 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +00002174 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +00002175 std::vector<std::string> &to,
Chris Lattner706d2d32006-08-09 16:44:44 +00002176 std::vector<std::string> &tv)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002177 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +00002178 GeneratedCode(gc), GeneratedDecl(gd),
2179 TargetOpcodes(to), TargetVTs(tv),
Chris Lattner706d2d32006-08-09 16:44:44 +00002180 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00002181
2182 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2183 /// if the match fails. At this point, we already know that the opcode for N
2184 /// matches, and the SDNode for the result has the RootName specified name.
Evan Chenge41bf822006-02-05 06:43:12 +00002185 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2186 const std::string &RootName, const std::string &ParentName,
2187 const std::string &ChainSuffix, bool &FoundChain) {
2188 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00002189 // Emit instruction predicates. Each predicate is just a string for now.
2190 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002191 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00002192 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2193 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2194 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002195 if (!Def->isSubClassOf("Predicate")) {
Jim Laskey16d42c62006-07-11 18:25:13 +00002196#ifndef NDEBUG
2197 Def->dump();
2198#endif
Evan Cheng58e84a62005-12-14 22:02:59 +00002199 assert(0 && "Unknown predicate type!");
2200 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002201 if (!PredicateCheck.empty())
Chris Lattnerbc7fa522006-09-19 00:41:36 +00002202 PredicateCheck += " && ";
Chris Lattner67a202b2006-01-28 20:43:52 +00002203 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00002204 }
2205 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002206
2207 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00002208 }
2209
Evan Chengb915f312005-12-09 22:45:35 +00002210 if (N->isLeaf()) {
2211 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002212 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00002213 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002214 return;
2215 } else if (!NodeIsComplexPattern(N)) {
2216 assert(0 && "Cannot match this as a leaf value!");
2217 abort();
2218 }
2219 }
2220
Chris Lattner488580c2006-01-28 19:06:51 +00002221 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002222 // we already saw this in the pattern, emit code to verify dagness.
2223 if (!N->getName().empty()) {
2224 std::string &VarMapEntry = VariableMap[N->getName()];
2225 if (VarMapEntry.empty()) {
2226 VarMapEntry = RootName;
2227 } else {
2228 // If we get here, this is a second reference to a specific name. Since
2229 // we already have checked that the first reference is valid, we don't
2230 // have to recursively match it, just check that it's the same as the
2231 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002232 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00002233 return;
2234 }
Evan Chengf805c2e2006-01-12 19:35:54 +00002235
2236 if (!N->isLeaf())
2237 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00002238 }
2239
2240
2241 // Emit code to load the child nodes and match their contents recursively.
2242 unsigned OpNo = 0;
Evan Chenge41bf822006-02-05 06:43:12 +00002243 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2244 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2245 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00002246 bool EmittedUseCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00002247 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00002248 if (NodeHasChain)
2249 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00002250 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00002251 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattner8a0604b2006-01-28 20:31:24 +00002252 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002253 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00002254 EmittedUseCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00002255 if (NodeHasChain) {
Evan Chenge41bf822006-02-05 06:43:12 +00002256 // If the immediate use can somehow reach this node through another
2257 // path, then can't fold it either or it will create a cycle.
2258 // e.g. In the following diagram, XX can reach ld through YY. If
2259 // ld is folded into XX, then YY is both a predecessor and a successor
2260 // of XX.
2261 //
2262 // [ld]
2263 // ^ ^
2264 // | |
2265 // / \---
2266 // / [YY]
2267 // | ^
2268 // [XX]-------|
2269 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2270 if (PInfo.getNumOperands() > 1 ||
2271 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2272 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2273 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
Chris Lattner706d2d32006-08-09 16:44:44 +00002274 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
2275 ".Val)");
Evan Chenge41bf822006-02-05 06:43:12 +00002276 }
Evan Chengb915f312005-12-09 22:45:35 +00002277 }
Evan Chenge41bf822006-02-05 06:43:12 +00002278
Evan Chengc15d18c2006-01-27 22:13:45 +00002279 if (NodeHasChain) {
Evan Chenge6389932006-07-21 22:19:51 +00002280 if (FoundChain)
2281 emitCheck("Chain.Val == " + RootName + ".Val");
2282 else
2283 FoundChain = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002284 ChainName = "Chain" + ChainSuffix;
Evan Cheng676d7312006-08-26 00:59:04 +00002285 emitInit("SDOperand " + ChainName + " = " + RootName +
Evan Chenge6389932006-07-21 22:19:51 +00002286 ".getOperand(0);");
Evan Cheng1cf6db22006-01-06 00:41:12 +00002287 }
Evan Chengb915f312005-12-09 22:45:35 +00002288 }
2289
Evan Cheng54597732006-01-26 00:22:25 +00002290 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002291 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002292 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002293 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2294 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002295 if (!isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002296 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2297 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2298 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002299 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2300 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002301 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002302 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002303 }
2304 }
2305
Evan Cheng676d7312006-08-26 00:59:04 +00002306 const ComplexPattern *CP;
Evan Chengb915f312005-12-09 22:45:35 +00002307 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng676d7312006-08-26 00:59:04 +00002308 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002309 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002310
2311 TreePatternNode *Child = N->getChild(i);
Evan Chengb915f312005-12-09 22:45:35 +00002312 if (!Child->isLeaf()) {
2313 // If it's not a leaf, recursively match.
2314 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
Chris Lattner67a202b2006-01-28 20:43:52 +00002315 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002316 CInfo.getEnumName());
Evan Chenge41bf822006-02-05 06:43:12 +00002317 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2318 ChainSuffix + utostr(OpNo), FoundChain);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002319 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002320 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2321 CInfo.getNumResults()));
Evan Chengb915f312005-12-09 22:45:35 +00002322 } else {
Chris Lattner488580c2006-01-28 19:06:51 +00002323 // If this child has a name associated with it, capture it in VarMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002324 // we already saw this in the pattern, emit code to verify dagness.
2325 if (!Child->getName().empty()) {
2326 std::string &VarMapEntry = VariableMap[Child->getName()];
2327 if (VarMapEntry.empty()) {
2328 VarMapEntry = RootName + utostr(OpNo);
2329 } else {
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002330 // If we get here, this is a second reference to a specific name.
2331 // Since we already have checked that the first reference is valid,
2332 // we don't have to recursively match it, just check that it's the
2333 // same as the previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002334 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
Evan Chengb4ad33c2006-01-19 01:55:45 +00002335 Duplicates.insert(RootName + utostr(OpNo));
Evan Chengb915f312005-12-09 22:45:35 +00002336 continue;
2337 }
2338 }
2339
2340 // Handle leaves of various types.
2341 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2342 Record *LeafRec = DI->getDef();
2343 if (LeafRec->isSubClassOf("RegisterClass")) {
2344 // Handle register references. Nothing to do here.
2345 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00002346 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00002347 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
Evan Cheng676d7312006-08-26 00:59:04 +00002348 // Handle complex pattern.
2349 CP = NodeGetComplexPattern(Child, ISE);
2350 std::string Fn = CP->getSelectFunc();
2351 unsigned NumOps = CP->getNumOperands();
2352 for (unsigned i = 0; i < NumOps; ++i) {
2353 emitDecl("CPTmp" + utostr(i));
2354 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2355 }
2356
2357 std::string Code = Fn + "(" + RootName + utostr(OpNo);
2358 for (unsigned i = 0; i < NumOps; i++)
2359 Code += ", CPTmp" + utostr(i);
2360 emitCheck(Code + ")");
Evan Cheng01f318b2005-12-14 02:21:57 +00002361 } else if (LeafRec->getName() == "srcvalue") {
2362 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00002363 } else if (LeafRec->isSubClassOf("ValueType")) {
2364 // Make sure this is the specified value type.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002365 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002366 ")->getVT() == MVT::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002367 } else if (LeafRec->isSubClassOf("CondCode")) {
2368 // Make sure this is the specified cond code.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002369 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002370 ")->get() == ISD::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002371 } else {
Jim Laskey16d42c62006-07-11 18:25:13 +00002372#ifndef NDEBUG
2373 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00002374 std::cerr << " ";
Jim Laskey16d42c62006-07-11 18:25:13 +00002375#endif
Evan Chengb915f312005-12-09 22:45:35 +00002376 assert(0 && "Unknown leaf type!");
2377 }
Evan Chengd46bd602006-09-19 19:08:04 +00002378
2379 // If there is a node predicate for this, emit the call.
2380 if (!Child->getPredicateFn().empty())
2381 emitCheck(Child->getPredicateFn() + "(" + RootName + utostr(OpNo) +
2382 ".Val)");
Chris Lattner488580c2006-01-28 19:06:51 +00002383 } else if (IntInit *II =
2384 dynamic_cast<IntInit*>(Child->getLeafValue())) {
Chris Lattner8bc74722006-01-29 04:25:26 +00002385 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2386 unsigned CTmp = TmpNo++;
Andrew Lenharth8e517732006-01-29 05:22:37 +00002387 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
Chris Lattner8bc74722006-01-29 04:25:26 +00002388 RootName + utostr(OpNo) + ")->getSignExtended();");
2389
2390 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002391 } else {
Jim Laskey16d42c62006-07-11 18:25:13 +00002392#ifndef NDEBUG
2393 Child->dump();
2394#endif
Evan Chengb915f312005-12-09 22:45:35 +00002395 assert(0 && "Unknown leaf type!");
2396 }
2397 }
2398 }
2399
Evan Cheng676d7312006-08-26 00:59:04 +00002400 // Handle cases when root is a complex pattern.
2401 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2402 std::string Fn = CP->getSelectFunc();
2403 unsigned NumOps = CP->getNumOperands();
2404 for (unsigned i = 0; i < NumOps; ++i) {
2405 emitDecl("CPTmp" + utostr(i));
2406 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2407 }
2408
2409 std::string Code = Fn + "(" + RootName;
2410 for (unsigned i = 0; i < NumOps; i++)
2411 Code += ", CPTmp" + utostr(i);
2412 emitCheck(Code + ")");
2413 }
2414
Evan Chengb915f312005-12-09 22:45:35 +00002415 // If there is a node predicate for this, emit the call.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002416 if (!N->getPredicateFn().empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002417 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
Evan Chengb915f312005-12-09 22:45:35 +00002418 }
2419
2420 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2421 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +00002422 std::vector<std::string>
2423 EmitResultCode(TreePatternNode *N, bool RetSelected,
2424 bool InFlagDecled, bool ResNodeDecled,
2425 bool LikeLeaf = false, bool isRoot = false) {
2426 // List of arguments of getTargetNode() or SelectNodeTo().
2427 std::vector<std::string> NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002428 // This is something selected from the pattern we matched.
2429 if (!N->getName().empty()) {
Evan Chengb915f312005-12-09 22:45:35 +00002430 std::string &Val = VariableMap[N->getName()];
2431 assert(!Val.empty() &&
2432 "Variable referenced but not defined and not caught earlier!");
2433 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2434 // Already selected this operand, just return the tmpval.
Evan Cheng676d7312006-08-26 00:59:04 +00002435 NodeOps.push_back(Val);
2436 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002437 }
2438
2439 const ComplexPattern *CP;
2440 unsigned ResNo = TmpNo++;
Evan Chengb915f312005-12-09 22:45:35 +00002441 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002442 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002443 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002444 switch (N->getTypeNum(0)) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002445 default: assert(0 && "Unknown type for constant node!");
Chris Lattner78593132006-01-29 20:01:35 +00002446 case MVT::i1: CastType = "bool"; break;
2447 case MVT::i8: CastType = "unsigned char"; break;
2448 case MVT::i16: CastType = "unsigned short"; break;
2449 case MVT::i32: CastType = "unsigned"; break;
2450 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002451 }
Evan Cheng676d7312006-08-26 00:59:04 +00002452 emitCode("SDOperand Tmp" + utostr(ResNo) +
Evan Chengfceb57a2006-07-15 08:45:20 +00002453 " = CurDAG->getTargetConstant(((" + CastType +
2454 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2455 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002456 NodeOps.push_back("Tmp" + utostr(ResNo));
2457 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2458 // value if used multiple times by this pattern result.
2459 Val = "Tmp"+utostr(ResNo);
Evan Chengbb48e332006-01-12 07:54:57 +00002460 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002461 Record *Op = OperatorMap[N->getName()];
2462 // Transform ExternalSymbol to TargetExternalSymbol
2463 if (Op && Op->getName() == "externalsym") {
Evan Cheng676d7312006-08-26 00:59:04 +00002464 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002465 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002466 Val + ")->getSymbol(), " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002467 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002468 NodeOps.push_back("Tmp" + utostr(ResNo));
2469 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2470 // value if used multiple times by this pattern result.
2471 Val = "Tmp"+utostr(ResNo);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002472 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002473 NodeOps.push_back(Val);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002474 }
Evan Chengb915f312005-12-09 22:45:35 +00002475 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002476 Record *Op = OperatorMap[N->getName()];
2477 // Transform GlobalAddress to TargetGlobalAddress
2478 if (Op && Op->getName() == "globaladdr") {
Evan Cheng676d7312006-08-26 00:59:04 +00002479 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002480 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
Evan Cheng2618d072006-05-17 20:37:59 +00002481 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002482 ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002483 NodeOps.push_back("Tmp" + utostr(ResNo));
2484 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2485 // value if used multiple times by this pattern result.
2486 Val = "Tmp"+utostr(ResNo);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002487 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002488 NodeOps.push_back(Val);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002489 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002490 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng676d7312006-08-26 00:59:04 +00002491 NodeOps.push_back(Val);
2492 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2493 // value if used multiple times by this pattern result.
2494 Val = "Tmp"+utostr(ResNo);
Evan Chengbb48e332006-01-12 07:54:57 +00002495 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng676d7312006-08-26 00:59:04 +00002496 NodeOps.push_back(Val);
2497 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2498 // value if used multiple times by this pattern result.
2499 Val = "Tmp"+utostr(ResNo);
Evan Chengb915f312005-12-09 22:45:35 +00002500 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2501 std::string Fn = CP->getSelectFunc();
Evan Cheng676d7312006-08-26 00:59:04 +00002502 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
2503 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
2504 NodeOps.push_back("CPTmp" + utostr(i));
Evan Chengb0793f92006-05-25 00:21:44 +00002505 }
Evan Chengb915f312005-12-09 22:45:35 +00002506 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002507 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
Evan Cheng863bf5a2006-03-20 22:53:06 +00002508 // node even if it isn't one. Don't select it.
Evan Cheng676d7312006-08-26 00:59:04 +00002509 if (!LikeLeaf) {
2510 emitCode("AddToISelQueue(" + Val + ");");
Chris Lattner706d2d32006-08-09 16:44:44 +00002511 if (isRoot && N->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +00002512 emitCode("ReplaceUses(N, " + Val + ");");
Evan Cheng06d64702006-08-11 08:59:35 +00002513 emitCode("return NULL;");
Chris Lattner706d2d32006-08-09 16:44:44 +00002514 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00002515 }
Evan Cheng676d7312006-08-26 00:59:04 +00002516 NodeOps.push_back(Val);
Evan Chengb915f312005-12-09 22:45:35 +00002517 }
Evan Cheng676d7312006-08-26 00:59:04 +00002518 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002519 }
Evan Chengb915f312005-12-09 22:45:35 +00002520 if (N->isLeaf()) {
2521 // If this is an explicit register reference, handle it.
2522 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2523 unsigned ResNo = TmpNo++;
2524 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng676d7312006-08-26 00:59:04 +00002525 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002526 ISE.getQualifiedName(DI->getDef()) + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002527 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002528 NodeOps.push_back("Tmp" + utostr(ResNo));
2529 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002530 }
2531 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2532 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002533 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng676d7312006-08-26 00:59:04 +00002534 emitCode("SDOperand Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002535 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
Evan Cheng2618d072006-05-17 20:37:59 +00002536 ", " + getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002537 NodeOps.push_back("Tmp" + utostr(ResNo));
2538 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002539 }
2540
Jim Laskey16d42c62006-07-11 18:25:13 +00002541#ifndef NDEBUG
2542 N->dump();
2543#endif
Evan Chengb915f312005-12-09 22:45:35 +00002544 assert(0 && "Unknown leaf type!");
Evan Cheng676d7312006-08-26 00:59:04 +00002545 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002546 }
2547
2548 Record *Op = N->getOperator();
2549 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002550 const CodeGenTarget &CGT = ISE.getTargetInfo();
2551 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002552 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng045953c2006-05-10 00:05:46 +00002553 TreePattern *InstPat = Inst.getPattern();
2554 TreePatternNode *InstPatNode =
2555 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2556 : (InstPat ? InstPat->getOnlyTree() : NULL);
2557 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2558 InstPatNode = InstPatNode->getChild(1);
2559 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002560 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
Evan Cheng045953c2006-05-10 00:05:46 +00002561 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2562 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2563 bool NodeHasOptInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002564 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002565 bool NodeHasInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002566 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002567 bool NodeHasOutFlag = HasImpResults || (isRoot &&
2568 PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2569 bool NodeHasChain = InstPatNode &&
2570 PatternHasProperty(InstPatNode, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng3eff89b2006-05-10 02:47:57 +00002571 bool InputHasChain = isRoot &&
2572 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng4fba2812005-12-20 07:37:41 +00002573
Evan Chengfceb57a2006-07-15 08:45:20 +00002574 if (NodeHasOptInFlag) {
Evan Cheng676d7312006-08-26 00:59:04 +00002575 emitCode("bool HasInFlag = "
Evan Chengf8729402006-07-16 06:12:52 +00002576 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
Evan Chengfceb57a2006-07-15 08:45:20 +00002577 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002578 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +00002579 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
Evan Cheng4fba2812005-12-20 07:37:41 +00002580
Evan Cheng823b7522006-01-19 21:57:10 +00002581 // How many results is this pattern expected to produce?
Evan Chenged66e852006-03-09 08:19:11 +00002582 unsigned PatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +00002583 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2584 MVT::ValueType VT = Pattern->getTypeNum(i);
2585 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Chenged66e852006-03-09 08:19:11 +00002586 PatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +00002587 }
2588
Evan Cheng676d7312006-08-26 00:59:04 +00002589 std::vector<std::string> AllOps;
Evan Chengb915f312005-12-09 22:45:35 +00002590 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Evan Cheng676d7312006-08-26 00:59:04 +00002591 std::vector<std::string> Ops = EmitResultCode(N->getChild(i),
2592 RetSelected, InFlagDecled, ResNodeDecled);
2593 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
Evan Chengb915f312005-12-09 22:45:35 +00002594 }
2595
Evan Chengb915f312005-12-09 22:45:35 +00002596 // Emit all the chain and CopyToReg stuff.
Evan Cheng045953c2006-05-10 00:05:46 +00002597 bool ChainEmitted = NodeHasChain;
2598 if (NodeHasChain)
Evan Cheng676d7312006-08-26 00:59:04 +00002599 emitCode("AddToISelQueue(" + ChainName + ");");
Evan Chengbc6b86a2006-06-14 19:27:50 +00002600 if (NodeHasInFlag || HasImpInputs)
Evan Cheng676d7312006-08-26 00:59:04 +00002601 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
2602 InFlagDecled, ResNodeDecled, true);
Evan Chengf037ca62006-08-27 08:11:28 +00002603 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
Evan Cheng676d7312006-08-26 00:59:04 +00002604 if (!InFlagDecled) {
2605 emitCode("SDOperand InFlag(0, 0);");
2606 InFlagDecled = true;
2607 }
Evan Chengf037ca62006-08-27 08:11:28 +00002608 if (NodeHasOptInFlag) {
2609 emitCode("if (HasInFlag) {");
2610 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
2611 emitCode(" AddToISelQueue(InFlag);");
2612 emitCode("}");
2613 }
Evan Chengbc6b86a2006-06-14 19:27:50 +00002614 }
Evan Chengb915f312005-12-09 22:45:35 +00002615
Evan Chengb915f312005-12-09 22:45:35 +00002616 unsigned NumResults = Inst.getNumResults();
2617 unsigned ResNo = TmpNo++;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002618 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2619 NodeHasOptInFlag) {
Evan Chenge945f4d2006-06-14 22:22:20 +00002620 std::string Code;
2621 std::string Code2;
2622 std::string NodeName;
2623 if (!isRoot) {
2624 NodeName = "Tmp" + utostr(ResNo);
Evan Cheng676d7312006-08-26 00:59:04 +00002625 Code2 = "SDOperand " + NodeName + " = SDOperand(";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002626 } else {
Evan Chenge945f4d2006-06-14 22:22:20 +00002627 NodeName = "ResNode";
Evan Cheng676d7312006-08-26 00:59:04 +00002628 if (!ResNodeDecled)
2629 Code2 = "SDNode *" + NodeName + " = ";
2630 else
2631 Code2 = NodeName + " = ";
Evan Chengbcecf332005-12-17 01:19:28 +00002632 }
Evan Chengf037ca62006-08-27 08:11:28 +00002633
Evan Chengfceb57a2006-07-15 08:45:20 +00002634 Code = "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
Evan Chengf037ca62006-08-27 08:11:28 +00002635 unsigned OpsNo = OpcNo;
Evan Chengfceb57a2006-07-15 08:45:20 +00002636 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
Evan Chenge945f4d2006-06-14 22:22:20 +00002637
2638 // Output order: results, chain, flags
2639 // Result types.
Evan Chengf8729402006-07-16 06:12:52 +00002640 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
2641 Code += ", VT" + utostr(VTNo);
2642 emitVT(getEnumName(N->getTypeNum(0)));
2643 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002644 if (NodeHasChain)
2645 Code += ", MVT::Other";
2646 if (NodeHasOutFlag)
2647 Code += ", MVT::Flag";
2648
2649 // Inputs.
Evan Chengf037ca62006-08-27 08:11:28 +00002650 if (HasVarOps) {
2651 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
2652 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
2653 AllOps.clear();
Evan Chenge945f4d2006-06-14 22:22:20 +00002654 }
2655
2656 if (HasVarOps) {
2657 if (NodeHasInFlag || HasImpInputs)
2658 emitCode("for (unsigned i = 2, e = N.getNumOperands()-1; "
2659 "i != e; ++i) {");
2660 else if (NodeHasOptInFlag)
Evan Chengfceb57a2006-07-15 08:45:20 +00002661 emitCode("for (unsigned i = 2, e = N.getNumOperands()-"
2662 "(HasInFlag?1:0); i != e; ++i) {");
Evan Chenge945f4d2006-06-14 22:22:20 +00002663 else
2664 emitCode("for (unsigned i = 2, e = N.getNumOperands(); "
2665 "i != e; ++i) {");
Evan Cheng676d7312006-08-26 00:59:04 +00002666 emitCode(" AddToISelQueue(N.getOperand(i));");
Evan Chengf037ca62006-08-27 08:11:28 +00002667 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
Evan Chenge945f4d2006-06-14 22:22:20 +00002668 emitCode("}");
2669 }
2670
2671 if (NodeHasChain) {
2672 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +00002673 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
Evan Chenge945f4d2006-06-14 22:22:20 +00002674 else
Evan Chengf037ca62006-08-27 08:11:28 +00002675 AllOps.push_back(ChainName);
Evan Chenge945f4d2006-06-14 22:22:20 +00002676 }
2677
Evan Chengf037ca62006-08-27 08:11:28 +00002678 if (HasVarOps) {
2679 if (NodeHasInFlag || HasImpInputs)
2680 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2681 else if (NodeHasOptInFlag) {
2682 emitCode("if (HasInFlag)");
2683 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2684 }
2685 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
2686 ".size()";
2687 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2688 AllOps.push_back("InFlag");
Evan Chenge945f4d2006-06-14 22:22:20 +00002689
Evan Chengf037ca62006-08-27 08:11:28 +00002690 unsigned NumOps = AllOps.size();
2691 if (NumOps) {
2692 if (!NodeHasOptInFlag && NumOps < 4) {
2693 for (unsigned i = 0; i != NumOps; ++i)
2694 Code += ", " + AllOps[i];
2695 } else {
2696 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
2697 for (unsigned i = 0; i != NumOps; ++i) {
2698 OpsCode += AllOps[i];
2699 if (i != NumOps-1)
2700 OpsCode += ", ";
2701 }
2702 emitCode(OpsCode + " };");
2703 Code += ", Ops" + utostr(OpsNo) + ", ";
2704 if (NodeHasOptInFlag) {
2705 Code += "HasInFlag ? ";
2706 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
2707 } else
2708 Code += utostr(NumOps);
2709 }
2710 }
2711
Evan Chenge945f4d2006-06-14 22:22:20 +00002712 if (!isRoot)
2713 Code += "), 0";
2714 emitCode(Code2 + Code + ");");
2715
2716 if (NodeHasChain)
2717 // Remember which op produces the chain.
2718 if (!isRoot)
2719 emitCode(ChainName + " = SDOperand(" + NodeName +
2720 ".Val, " + utostr(PatResults) + ");");
2721 else
2722 emitCode(ChainName + " = SDOperand(" + NodeName +
2723 ", " + utostr(PatResults) + ");");
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002724
Evan Cheng676d7312006-08-26 00:59:04 +00002725 if (!isRoot) {
2726 NodeOps.push_back("Tmp" + utostr(ResNo));
2727 return NodeOps;
2728 }
Evan Cheng045953c2006-05-10 00:05:46 +00002729
Evan Cheng06d64702006-08-11 08:59:35 +00002730 bool NeedReplace = false;
Evan Cheng676d7312006-08-26 00:59:04 +00002731 if (NodeHasOutFlag) {
2732 if (!InFlagDecled) {
2733 emitCode("SDOperand InFlag = SDOperand(ResNode, " +
2734 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2735 InFlagDecled = true;
2736 } else
2737 emitCode("InFlag = SDOperand(ResNode, " +
2738 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2739 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002740
Evan Cheng676d7312006-08-26 00:59:04 +00002741 if (HasImpResults && EmitCopyFromRegs(N, ResNodeDecled, ChainEmitted)) {
Chris Lattner706d2d32006-08-09 16:44:44 +00002742 emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));");
Evan Chenged66e852006-03-09 08:19:11 +00002743 NumResults = 1;
Evan Cheng97938882005-12-22 02:24:50 +00002744 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002745
Evan Cheng97938882005-12-22 02:24:50 +00002746 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002747 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002748 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Chris Lattner706d2d32006-08-09 16:44:44 +00002749 emitCode("ReplaceUses(SDOperand(" +
Evan Cheng67212a02006-02-09 22:12:27 +00002750 FoldedChains[j].first + ".Val, " +
Chris Lattner706d2d32006-08-09 16:44:44 +00002751 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
2752 utostr(NumResults) + "));");
Evan Cheng06d64702006-08-11 08:59:35 +00002753 NeedReplace = true;
Evan Chengb915f312005-12-09 22:45:35 +00002754 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002755
Evan Cheng06d64702006-08-11 08:59:35 +00002756 if (NodeHasOutFlag) {
Chris Lattner706d2d32006-08-09 16:44:44 +00002757 emitCode("ReplaceUses(SDOperand(N.Val, " +
2758 utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);");
Evan Cheng06d64702006-08-11 08:59:35 +00002759 NeedReplace = true;
2760 }
2761
2762 if (NeedReplace) {
2763 for (unsigned i = 0; i < NumResults; i++)
2764 emitCode("ReplaceUses(SDOperand(N.Val, " +
2765 utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));");
2766 if (InputHasChain)
2767 emitCode("ReplaceUses(SDOperand(N.Val, " +
2768 utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, " +
2769 ChainName + ".ResNo" + "));");
Evan Chengf037ca62006-08-27 08:11:28 +00002770 } else
Evan Cheng06d64702006-08-11 08:59:35 +00002771 RetSelected = true;
Evan Cheng97938882005-12-22 02:24:50 +00002772
Evan Chenged66e852006-03-09 08:19:11 +00002773 // User does not expect the instruction would produce a chain!
Evan Cheng06d64702006-08-11 08:59:35 +00002774 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
Evan Cheng9ade2182006-08-26 05:34:46 +00002775 ;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002776 } else if (InputHasChain && !NodeHasChain) {
2777 // One of the inner node produces a chain.
Evan Cheng9ade2182006-08-26 05:34:46 +00002778 if (NodeHasOutFlag)
Evan Cheng06d64702006-08-11 08:59:35 +00002779 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults+1) +
2780 "), SDOperand(ResNode, N.ResNo-1));");
Evan Cheng06d64702006-08-11 08:59:35 +00002781 for (unsigned i = 0; i < PatResults; ++i)
2782 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(i) +
2783 "), SDOperand(ResNode, " + utostr(i) + "));");
2784 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults) +
2785 "), " + ChainName + ");");
2786 RetSelected = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002787 }
Evan Cheng06d64702006-08-11 08:59:35 +00002788
2789 if (RetSelected)
Evan Cheng9ade2182006-08-26 05:34:46 +00002790 emitCode("return ResNode;");
Evan Cheng06d64702006-08-11 08:59:35 +00002791 else
2792 emitCode("return NULL;");
Evan Chengb915f312005-12-09 22:45:35 +00002793 } else {
Evan Cheng9ade2182006-08-26 05:34:46 +00002794 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
Evan Chengfceb57a2006-07-15 08:45:20 +00002795 utostr(OpcNo);
Nate Begemanb73628b2005-12-30 00:12:56 +00002796 if (N->getTypeNum(0) != MVT::isVoid)
Evan Chengf8729402006-07-16 06:12:52 +00002797 Code += ", VT" + utostr(VTNo);
Evan Cheng54597732006-01-26 00:22:25 +00002798 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002799 Code += ", MVT::Flag";
Evan Chengf037ca62006-08-27 08:11:28 +00002800
2801 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2802 AllOps.push_back("InFlag");
2803
2804 unsigned NumOps = AllOps.size();
2805 if (NumOps) {
2806 if (!NodeHasOptInFlag && NumOps < 4) {
2807 for (unsigned i = 0; i != NumOps; ++i)
2808 Code += ", " + AllOps[i];
2809 } else {
2810 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
2811 for (unsigned i = 0; i != NumOps; ++i) {
2812 OpsCode += AllOps[i];
2813 if (i != NumOps-1)
2814 OpsCode += ", ";
2815 }
2816 emitCode(OpsCode + " };");
2817 Code += ", Ops" + utostr(OpcNo) + ", ";
2818 Code += utostr(NumOps);
2819 }
2820 }
Evan Cheng95514ba2006-08-26 08:00:10 +00002821 emitCode(Code + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002822 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2823 if (N->getTypeNum(0) != MVT::isVoid)
2824 emitVT(getEnumName(N->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002825 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002826
Evan Cheng676d7312006-08-26 00:59:04 +00002827 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002828 } else if (Op->isSubClassOf("SDNodeXForm")) {
2829 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng863bf5a2006-03-20 22:53:06 +00002830 // PatLeaf node - the operand may or may not be a leaf node. But it should
2831 // behave like one.
Evan Cheng676d7312006-08-26 00:59:04 +00002832 std::vector<std::string> Ops =
2833 EmitResultCode(N->getChild(0), RetSelected, InFlagDecled,
2834 ResNodeDecled, true);
Evan Chengb915f312005-12-09 22:45:35 +00002835 unsigned ResNo = TmpNo++;
Evan Cheng676d7312006-08-26 00:59:04 +00002836 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2837 + "(" + Ops.back() + ".Val);");
2838 NodeOps.push_back("Tmp" + utostr(ResNo));
Evan Cheng9ade2182006-08-26 05:34:46 +00002839 if (isRoot)
2840 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00002841 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002842 } else {
2843 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002844 std::cerr << "\n";
2845 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002846 }
2847 }
2848
Chris Lattner488580c2006-01-28 19:06:51 +00002849 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2850 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00002851 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2852 /// for, this returns true otherwise false if Pat has all types.
2853 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +00002854 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002855 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +00002856 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +00002857 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002858 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +00002859 // The top level node type is checked outside of the select function.
2860 if (!isRoot)
2861 emitCheck(Prefix + ".Val->getValueType(0) == " +
2862 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002863 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002864 }
2865
Evan Cheng51fecc82006-01-09 18:27:06 +00002866 unsigned OpNo =
2867 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002868 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2869 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2870 Prefix + utostr(OpNo)))
2871 return true;
2872 return false;
2873 }
2874
2875private:
Evan Cheng54597732006-01-26 00:22:25 +00002876 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002877 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00002878 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +00002879 bool &ChainEmitted, bool &InFlagDecled,
2880 bool &ResNodeDecled, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002881 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002882 unsigned OpNo =
2883 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng54597732006-01-26 00:22:25 +00002884 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002885 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2886 TreePatternNode *Child = N->getChild(i);
2887 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +00002888 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
2889 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +00002890 } else {
2891 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00002892 if (!Child->getName().empty()) {
2893 std::string Name = RootName + utostr(OpNo);
2894 if (Duplicates.find(Name) != Duplicates.end())
2895 // A duplicate! Do not emit a copy for this node.
2896 continue;
2897 }
2898
Evan Chengb915f312005-12-09 22:45:35 +00002899 Record *RR = DI->getDef();
2900 if (RR->isSubClassOf("Register")) {
2901 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002902 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +00002903 if (!InFlagDecled) {
2904 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
2905 InFlagDecled = true;
2906 } else
2907 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
2908 emitCode("AddToISelQueue(InFlag);");
Evan Chengb2c6d492006-01-11 22:16:13 +00002909 } else {
2910 if (!ChainEmitted) {
Evan Cheng676d7312006-08-26 00:59:04 +00002911 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002912 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00002913 ChainEmitted = true;
2914 }
Evan Cheng676d7312006-08-26 00:59:04 +00002915 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
2916 if (!InFlagDecled) {
2917 emitCode("SDOperand InFlag(0, 0);");
2918 InFlagDecled = true;
2919 }
2920 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
2921 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Cheng7a33db02006-08-26 07:39:28 +00002922 ", " + ISE.getQualifiedName(RR) +
2923 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00002924 ResNodeDecled = true;
Evan Cheng67212a02006-02-09 22:12:27 +00002925 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2926 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00002927 }
2928 }
2929 }
2930 }
2931 }
Evan Cheng54597732006-01-26 00:22:25 +00002932
Evan Cheng676d7312006-08-26 00:59:04 +00002933 if (HasInFlag) {
2934 if (!InFlagDecled) {
2935 emitCode("SDOperand InFlag = " + RootName +
2936 ".getOperand(" + utostr(OpNo) + ");");
2937 InFlagDecled = true;
2938 } else
2939 emitCode("InFlag = " + RootName +
2940 ".getOperand(" + utostr(OpNo) + ");");
2941 emitCode("AddToISelQueue(InFlag);");
2942 }
Evan Chengb915f312005-12-09 22:45:35 +00002943 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002944
2945 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002946 /// as specified by the instruction. It returns true if any copy is
2947 /// emitted.
Evan Cheng676d7312006-08-26 00:59:04 +00002948 bool EmitCopyFromRegs(TreePatternNode *N, bool &ResNodeDecled,
2949 bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002950 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002951 Record *Op = N->getOperator();
2952 if (Op->isSubClassOf("Instruction")) {
2953 const DAGInstruction &Inst = ISE.getInstruction(Op);
2954 const CodeGenTarget &CGT = ISE.getTargetInfo();
Evan Cheng4fba2812005-12-20 07:37:41 +00002955 unsigned NumImpResults = Inst.getNumImpResults();
2956 for (unsigned i = 0; i < NumImpResults; i++) {
2957 Record *RR = Inst.getImpResult(i);
2958 if (RR->isSubClassOf("Register")) {
2959 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2960 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002961 if (!ChainEmitted) {
Evan Cheng676d7312006-08-26 00:59:04 +00002962 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00002963 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002964 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00002965 }
Evan Cheng676d7312006-08-26 00:59:04 +00002966 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
2967 emitCode(Decl + "ResNode = CurDAG->getCopyFromReg(" + ChainName +
Evan Chengfceb57a2006-07-15 08:45:20 +00002968 ", " + ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
Evan Chengd7805a72006-02-09 07:16:09 +00002969 ", InFlag).Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00002970 ResNodeDecled = true;
Evan Chengd7805a72006-02-09 07:16:09 +00002971 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2972 emitCode("InFlag = SDOperand(ResNode, 2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002973 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002974 }
2975 }
2976 }
2977 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002978 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002979 }
Evan Chengb915f312005-12-09 22:45:35 +00002980};
2981
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002982/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2983/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00002984/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00002985void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00002986 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00002987 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00002988 std::vector<std::string> &TargetOpcodes,
Evan Chengf5493192006-08-26 01:02:19 +00002989 std::vector<std::string> &TargetVTs) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002990 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2991 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00002992 GeneratedCode, GeneratedDecl,
Chris Lattner706d2d32006-08-09 16:44:44 +00002993 TargetOpcodes, TargetVTs);
Evan Chengb915f312005-12-09 22:45:35 +00002994
Chris Lattner8fc35682005-09-23 23:16:51 +00002995 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002996 bool FoundChain = false;
Evan Cheng06d64702006-08-11 08:59:35 +00002997 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "",
2998 FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002999
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003000 // TP - Get *SOME* tree pattern, we don't care which.
3001 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00003002
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003003 // At this point, we know that we structurally match the pattern, but the
3004 // types of the nodes may not match. Figure out the fewest number of type
3005 // comparisons we need to emit. For example, if there is only one integer
3006 // type supported by a target, there should be no type comparisons at all for
3007 // integer patterns!
3008 //
3009 // To figure out the fewest number of type checks needed, clone the pattern,
3010 // remove the types, then perform type inference on the pattern as a whole.
3011 // If there are unresolved types, emit an explicit check for those types,
3012 // apply the type to the tree, then rerun type inference. Iterate until all
3013 // types are resolved.
3014 //
Evan Cheng58e84a62005-12-14 22:02:59 +00003015 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003016 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00003017
3018 do {
3019 // Resolve/propagate as many types as possible.
3020 try {
3021 bool MadeChange = true;
3022 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00003023 MadeChange = Pat->ApplyTypeConstraints(TP,
3024 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00003025 } catch (...) {
3026 assert(0 && "Error: could not find consistent types for something we"
3027 " already decided was ok!");
3028 abort();
3029 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003030
Chris Lattner7e82f132005-10-15 21:34:21 +00003031 // Insert a check for an unresolved type and add it to the tree. If we find
3032 // an unresolved type to add a check for, this returns true and we iterate,
3033 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00003034 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00003035
Evan Cheng676d7312006-08-26 00:59:04 +00003036 Emitter.EmitResultCode(Pattern.getDstPattern(),
3037 false, false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003038 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00003039}
3040
Chris Lattner24e00a42006-01-29 04:41:05 +00003041/// EraseCodeLine - Erase one code line from all of the patterns. If removing
3042/// a line causes any of them to be empty, remove them and return true when
3043/// done.
3044static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00003045 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00003046 &Patterns) {
3047 bool ErasedPatterns = false;
3048 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3049 Patterns[i].second.pop_back();
3050 if (Patterns[i].second.empty()) {
3051 Patterns.erase(Patterns.begin()+i);
3052 --i; --e;
3053 ErasedPatterns = true;
3054 }
3055 }
3056 return ErasedPatterns;
3057}
3058
Chris Lattner8bc74722006-01-29 04:25:26 +00003059/// EmitPatterns - Emit code for at least one pattern, but try to group common
3060/// code together between the patterns.
3061void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00003062 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00003063 &Patterns, unsigned Indent,
3064 std::ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00003065 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00003066 typedef std::vector<CodeLine> CodeList;
3067 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3068
3069 if (Patterns.empty()) return;
3070
Chris Lattner24e00a42006-01-29 04:41:05 +00003071 // Figure out how many patterns share the next code line. Explicitly copy
3072 // FirstCodeLine so that we don't invalidate a reference when changing
3073 // Patterns.
3074 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00003075 unsigned LastMatch = Patterns.size()-1;
3076 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3077 --LastMatch;
3078
3079 // If not all patterns share this line, split the list into two pieces. The
3080 // first chunk will use this line, the second chunk won't.
3081 if (LastMatch != 0) {
3082 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3083 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3084
3085 // FIXME: Emit braces?
3086 if (Shared.size() == 1) {
3087 PatternToMatch &Pattern = *Shared.back().first;
3088 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3089 Pattern.getSrcPattern()->print(OS);
3090 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3091 Pattern.getDstPattern()->print(OS);
3092 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003093 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003094 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003095 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003096 << " cost = "
Evan Chenge6f32032006-07-19 00:24:41 +00003097 << getResultPatternCost(Pattern.getDstPattern(), *this)
3098 << " size = "
3099 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003100 }
Evan Cheng676d7312006-08-26 00:59:04 +00003101 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00003102 OS << std::string(Indent, ' ') << "{\n";
3103 Indent += 2;
3104 }
3105 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00003106 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00003107 Indent -= 2;
3108 OS << std::string(Indent, ' ') << "}\n";
3109 }
3110
3111 if (Other.size() == 1) {
3112 PatternToMatch &Pattern = *Other.back().first;
3113 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3114 Pattern.getSrcPattern()->print(OS);
3115 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3116 Pattern.getDstPattern()->print(OS);
3117 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003118 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003119 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003120 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003121 << " cost = "
Chris Lattner706d2d32006-08-09 16:44:44 +00003122 << getResultPatternCost(Pattern.getDstPattern(), *this)
3123 << " size = "
3124 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003125 }
3126 EmitPatterns(Other, Indent, OS);
3127 return;
3128 }
3129
Chris Lattner24e00a42006-01-29 04:41:05 +00003130 // Remove this code from all of the patterns that share it.
3131 bool ErasedPatterns = EraseCodeLine(Patterns);
3132
Evan Cheng676d7312006-08-26 00:59:04 +00003133 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00003134
3135 // Otherwise, every pattern in the list has this line. Emit it.
3136 if (!isPredicate) {
3137 // Normal code.
3138 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3139 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00003140 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3141
3142 // If the next code line is another predicate, and if all of the pattern
3143 // in this group share the same next line, emit it inline now. Do this
3144 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00003145 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Chris Lattner24e00a42006-01-29 04:41:05 +00003146 // Check that all of fhe patterns in Patterns end with the same predicate.
3147 bool AllEndWithSamePredicate = true;
3148 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3149 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3150 AllEndWithSamePredicate = false;
3151 break;
3152 }
3153 // If all of the predicates aren't the same, we can't share them.
3154 if (!AllEndWithSamePredicate) break;
3155
3156 // Otherwise we can. Emit it shared now.
3157 OS << " &&\n" << std::string(Indent+4, ' ')
3158 << Patterns.back().second.back().second;
3159 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00003160 }
Chris Lattner24e00a42006-01-29 04:41:05 +00003161
3162 OS << ") {\n";
3163 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00003164 }
3165
3166 EmitPatterns(Patterns, Indent, OS);
3167
3168 if (isPredicate)
3169 OS << std::string(Indent-2, ' ') << "}\n";
3170}
3171
3172
Chris Lattner37481472005-09-26 21:59:35 +00003173
3174namespace {
3175 /// CompareByRecordName - An ordering predicate that implements less-than by
3176 /// comparing the names records.
3177 struct CompareByRecordName {
3178 bool operator()(const Record *LHS, const Record *RHS) const {
3179 // Sort by name first.
3180 if (LHS->getName() < RHS->getName()) return true;
3181 // If both names are equal, sort by pointer.
3182 return LHS->getName() == RHS->getName() && LHS < RHS;
3183 }
3184 };
3185}
3186
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003187void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003188 std::string InstNS = Target.inst_begin()->second.Namespace;
3189 if (!InstNS.empty()) InstNS += "::";
3190
Chris Lattner602f6922006-01-04 00:25:00 +00003191 // Group the patterns by their top-level opcodes.
3192 std::map<Record*, std::vector<PatternToMatch*>,
3193 CompareByRecordName> PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00003194 // All unique target node emission functions.
3195 std::map<std::string, unsigned> EmitFunctions;
Chris Lattner602f6922006-01-04 00:25:00 +00003196 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3197 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3198 if (!Node->isLeaf()) {
3199 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3200 } else {
3201 const ComplexPattern *CP;
3202 if (IntInit *II =
3203 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3204 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3205 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3206 std::vector<Record*> OpNodes = CP->getRootNodes();
3207 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner488580c2006-01-28 19:06:51 +00003208 PatternsByOpcode[OpNodes[j]]
3209 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003210 }
3211 } else {
3212 std::cerr << "Unrecognized opcode '";
3213 Node->dump();
3214 std::cerr << "' on tree pattern '";
Chris Lattner488580c2006-01-28 19:06:51 +00003215 std::cerr <<
3216 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00003217 std::cerr << "'!\n";
3218 exit(1);
3219 }
3220 }
3221 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003222
3223 // For each opcode, there might be multiple select functions, one per
3224 // ValueType of the node (or its first operand if it doesn't produce a
3225 // non-chain result.
3226 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
3227
Chris Lattner602f6922006-01-04 00:25:00 +00003228 // Emit one Select_* method for each top-level opcode. We do this instead of
3229 // emitting one giant switch statement to support compilers where this will
3230 // result in the recursive functions taking less stack space.
3231 for (std::map<Record*, std::vector<PatternToMatch*>,
3232 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3233 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Evan Chenge41bf822006-02-05 06:43:12 +00003234 const std::string &OpName = PBOI->first->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00003235 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner706d2d32006-08-09 16:44:44 +00003236 std::vector<PatternToMatch*> &PatternsOfOp = PBOI->second;
3237 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
3238
Chris Lattner602f6922006-01-04 00:25:00 +00003239 // We want to emit all of the matching code now. However, we want to emit
3240 // the matches in order of minimal cost. Sort the patterns so the least
3241 // cost one is at the start.
Chris Lattner706d2d32006-08-09 16:44:44 +00003242 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
Chris Lattner602f6922006-01-04 00:25:00 +00003243 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00003244
Chris Lattner706d2d32006-08-09 16:44:44 +00003245 // Split them into groups by type.
3246 std::map<MVT::ValueType, std::vector<PatternToMatch*> > PatternsByType;
3247 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
3248 PatternToMatch *Pat = PatternsOfOp[i];
3249 TreePatternNode *SrcPat = Pat->getSrcPattern();
3250 if (OpcodeInfo.getNumResults() == 0 && SrcPat->getNumChildren() > 0)
3251 SrcPat = SrcPat->getChild(0);
3252 MVT::ValueType VT = SrcPat->getTypeNum(0);
3253 std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator TI =
3254 PatternsByType.find(VT);
3255 if (TI != PatternsByType.end())
3256 TI->second.push_back(Pat);
3257 else {
3258 std::vector<PatternToMatch*> PVec;
3259 PVec.push_back(Pat);
3260 PatternsByType.insert(std::make_pair(VT, PVec));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003261 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003262 }
3263
3264 for (std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator
3265 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
3266 ++II) {
3267 MVT::ValueType OpVT = II->first;
3268 std::vector<PatternToMatch*> &Patterns = II->second;
Evan Cheng676d7312006-08-26 00:59:04 +00003269 typedef std::vector<std::pair<unsigned, std::string> > CodeList;
3270 typedef std::vector<std::pair<unsigned, std::string> >::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00003271
3272 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3273 std::vector<std::vector<std::string> > PatternOpcodes;
3274 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00003275 std::vector<std::set<std::string> > PatternDecls;
Chris Lattner706d2d32006-08-09 16:44:44 +00003276 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3277 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00003278 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00003279 std::vector<std::string> TargetOpcodes;
3280 std::vector<std::string> TargetVTs;
3281 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3282 TargetOpcodes, TargetVTs);
Chris Lattner706d2d32006-08-09 16:44:44 +00003283 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3284 PatternDecls.push_back(GeneratedDecl);
3285 PatternOpcodes.push_back(TargetOpcodes);
3286 PatternVTs.push_back(TargetVTs);
3287 }
3288
3289 // Scan the code to see if all of the patterns are reachable and if it is
3290 // possible that the last one might not match.
3291 bool mightNotMatch = true;
3292 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3293 CodeList &GeneratedCode = CodeForPatterns[i].second;
3294 mightNotMatch = false;
3295
3296 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
Evan Cheng676d7312006-08-26 00:59:04 +00003297 if (GeneratedCode[j].first == 1) { // predicate.
Chris Lattner706d2d32006-08-09 16:44:44 +00003298 mightNotMatch = true;
3299 break;
3300 }
3301 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003302
Chris Lattner706d2d32006-08-09 16:44:44 +00003303 // If this pattern definitely matches, and if it isn't the last one, the
3304 // patterns after it CANNOT ever match. Error out.
3305 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3306 std::cerr << "Pattern '";
Evan Cheng676d7312006-08-26 00:59:04 +00003307 CodeForPatterns[i].first->getSrcPattern()->print(std::cerr);
Chris Lattner706d2d32006-08-09 16:44:44 +00003308 std::cerr << "' is impossible to select!\n";
3309 exit(1);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003310 }
3311 }
3312
Chris Lattner706d2d32006-08-09 16:44:44 +00003313 // Factor target node emission code (emitted by EmitResultCode) into
3314 // separate functions. Uniquing and share them among all instruction
3315 // selection routines.
3316 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3317 CodeList &GeneratedCode = CodeForPatterns[i].second;
3318 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
3319 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00003320 std::set<std::string> Decls = PatternDecls[i];
Evan Cheng676d7312006-08-26 00:59:04 +00003321 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00003322 int CodeSize = (int)GeneratedCode.size();
3323 int LastPred = -1;
3324 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00003325 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00003326 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00003327 else if (LastPred != -1 && GeneratedCode[j].first == 2)
3328 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00003329 }
3330
Evan Cheng9ade2182006-08-26 05:34:46 +00003331 std::string CalleeCode = "(const SDOperand &N";
3332 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00003333 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3334 CalleeCode += ", unsigned Opc" + utostr(j);
3335 CallerCode += ", " + TargetOpcodes[j];
3336 }
3337 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
3338 CalleeCode += ", MVT::ValueType VT" + utostr(j);
3339 CallerCode += ", " + TargetVTs[j];
3340 }
Evan Chengf5493192006-08-26 01:02:19 +00003341 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00003342 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00003343 std::string Name = *I;
Evan Cheng676d7312006-08-26 00:59:04 +00003344 CalleeCode += ", SDOperand &" + Name;
3345 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00003346 }
3347 CallerCode += ");";
3348 CalleeCode += ") ";
3349 // Prevent emission routines from being inlined to reduce selection
3350 // routines stack frame sizes.
Chris Lattner8dc728e2006-08-27 13:16:24 +00003351 CalleeCode += "DISABLE_INLINE ";
Evan Cheng676d7312006-08-26 00:59:04 +00003352 CalleeCode += "{\n";
3353
3354 for (std::vector<std::string>::const_reverse_iterator
3355 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
3356 CalleeCode += " " + *I + "\n";
3357
Evan Chengf5493192006-08-26 01:02:19 +00003358 for (int j = LastPred+1; j < CodeSize; ++j)
3359 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003360 for (int j = LastPred+1; j < CodeSize; ++j)
3361 GeneratedCode.pop_back();
3362 CalleeCode += "}\n";
3363
3364 // Uniquing the emission routines.
3365 unsigned EmitFuncNum;
3366 std::map<std::string, unsigned>::iterator EFI =
3367 EmitFunctions.find(CalleeCode);
3368 if (EFI != EmitFunctions.end()) {
3369 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003370 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00003371 EmitFuncNum = EmitFunctions.size();
3372 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Evan Cheng06d64702006-08-11 08:59:35 +00003373 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003374 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003375
Chris Lattner706d2d32006-08-09 16:44:44 +00003376 // Replace the emission code within selection routines with calls to the
3377 // emission functions.
Evan Cheng06d64702006-08-11 08:59:35 +00003378 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
Chris Lattner706d2d32006-08-09 16:44:44 +00003379 GeneratedCode.push_back(std::make_pair(false, CallerCode));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003380 }
3381
Chris Lattner706d2d32006-08-09 16:44:44 +00003382 // Print function.
3383 std::string OpVTStr = (OpVT != MVT::isVoid && OpVT != MVT::iPTR)
3384 ? getEnumName(OpVT).substr(5) : "" ;
3385 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3386 OpcodeVTMap.find(OpName);
3387 if (OpVTI == OpcodeVTMap.end()) {
3388 std::vector<std::string> VTSet;
3389 VTSet.push_back(OpVTStr);
3390 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
3391 } else
3392 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003393
Evan Cheng06d64702006-08-11 08:59:35 +00003394 OS << "SDNode *Select_" << OpName << (OpVTStr != "" ? "_" : "")
Evan Cheng9ade2182006-08-26 05:34:46 +00003395 << OpVTStr << "(const SDOperand &N) {\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003396
Chris Lattner706d2d32006-08-09 16:44:44 +00003397 // Loop through and reverse all of the CodeList vectors, as we will be
3398 // accessing them from their logical front, but accessing the end of a
3399 // vector is more efficient.
3400 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3401 CodeList &GeneratedCode = CodeForPatterns[i].second;
3402 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003403 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003404
3405 // Next, reverse the list of patterns itself for the same reason.
3406 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3407
3408 // Emit all of the patterns now, grouped together to share code.
3409 EmitPatterns(CodeForPatterns, 2, OS);
3410
3411 // If the last pattern has predicates (which could fail) emit code to catch
3412 // the case where nothing handles a pattern.
3413 if (mightNotMatch) {
3414 OS << " std::cerr << \"Cannot yet select: \";\n";
3415 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3416 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3417 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3418 OS << " N.Val->dump(CurDAG);\n";
3419 } else {
3420 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3421 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3422 << " std::cerr << \"intrinsic %\"<< "
3423 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3424 }
3425 OS << " std::cerr << '\\n';\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003426 << " abort();\n"
3427 << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003428 }
3429 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003430 }
Chris Lattner602f6922006-01-04 00:25:00 +00003431 }
3432
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003433 // Emit boilerplate.
Evan Cheng9ade2182006-08-26 05:34:46 +00003434 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003435 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003436 << " AddToISelQueue(N.getOperand(0)); // Select the chain.\n\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003437 << " // Select the flag operand.\n"
3438 << " if (Ops.back().getValueType() == MVT::Flag)\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003439 << " AddToISelQueue(Ops.back());\n"
Chris Lattnerfd105d42006-02-24 02:13:31 +00003440 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003441 << " std::vector<MVT::ValueType> VTs;\n"
3442 << " VTs.push_back(MVT::Other);\n"
3443 << " VTs.push_back(MVT::Flag);\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00003444 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
3445 "Ops.size());\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00003446 << " return New.Val;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003447 << "}\n\n";
3448
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003449 OS << "// The main instruction selector code.\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00003450 << "SDNode *SelectCode(SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003451 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003452 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003453 << "INSTRUCTION_LIST_END)) {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003454 << " return NULL; // Already selected.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003455 << " }\n\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003456 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003457 << " default: break;\n"
3458 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003459 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003460 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003461 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003462 << " case ISD::TargetConstant:\n"
3463 << " case ISD::TargetConstantPool:\n"
3464 << " case ISD::TargetFrameIndex:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00003465 << " case ISD::TargetJumpTable:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003466 << " case ISD::TargetGlobalAddress: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003467 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003468 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003469 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003470 << " case ISD::AssertZext: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003471 << " AddToISelQueue(N.getOperand(0));\n"
3472 << " ReplaceUses(N, N.getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003473 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003474 << " }\n"
3475 << " case ISD::TokenFactor:\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00003476 << " case ISD::CopyFromReg:\n"
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003477 << " case ISD::CopyToReg: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003478 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
3479 << " AddToISelQueue(N.getOperand(i));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003480 << " return NULL;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003481 << " }\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00003482 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003483
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003484
Chris Lattner602f6922006-01-04 00:25:00 +00003485 // Loop over all of the case statements, emiting a call to each method we
3486 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00003487 for (std::map<Record*, std::vector<PatternToMatch*>,
3488 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3489 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00003490 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner706d2d32006-08-09 16:44:44 +00003491 const std::string &OpName = PBOI->first->getName();
3492 // Potentially multiple versions of select for this opcode. One for each
3493 // ValueType of the node (or its first true operand if it doesn't produce a
3494 // result.
3495 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3496 OpcodeVTMap.find(OpName);
3497 std::vector<std::string> &OpVTs = OpVTI->second;
3498 OS << " case " << OpcodeInfo.getEnumName() << ": {\n";
3499 if (OpVTs.size() == 1) {
3500 std::string &VTStr = OpVTs[0];
Evan Cheng06d64702006-08-11 08:59:35 +00003501 OS << " return Select_" << OpName
Evan Cheng9ade2182006-08-26 05:34:46 +00003502 << (VTStr != "" ? "_" : "") << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003503 } else {
3504 if (OpcodeInfo.getNumResults())
3505 OS << " MVT::ValueType NVT = N.Val->getValueType(0);\n";
3506 else if (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain))
3507 OS << " MVT::ValueType NVT = (N.getNumOperands() > 1) ?"
3508 << " N.getOperand(1).Val->getValueType(0) : MVT::isVoid;\n";
3509 else
3510 OS << " MVT::ValueType NVT = (N.getNumOperands() > 0) ?"
3511 << " N.getOperand(0).Val->getValueType(0) : MVT::isVoid;\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003512 int Default = -1;
3513 OS << " switch (NVT) {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003514 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
3515 std::string &VTStr = OpVTs[i];
3516 if (VTStr == "") {
Evan Cheng06d64702006-08-11 08:59:35 +00003517 Default = i;
Chris Lattner706d2d32006-08-09 16:44:44 +00003518 continue;
3519 }
Evan Cheng06d64702006-08-11 08:59:35 +00003520 OS << " case MVT::" << VTStr << ":\n"
3521 << " return Select_" << OpName
Evan Cheng9ade2182006-08-26 05:34:46 +00003522 << "_" << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003523 }
Evan Cheng06d64702006-08-11 08:59:35 +00003524 OS << " default:\n";
3525 if (Default != -1)
Evan Cheng9ade2182006-08-26 05:34:46 +00003526 OS << " return Select_" << OpName << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003527 else
Evan Cheng06d64702006-08-11 08:59:35 +00003528 OS << " break;\n";
3529 OS << " }\n";
3530 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003531 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003532 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00003533 }
Chris Lattner81303322005-09-23 19:36:15 +00003534
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003535 OS << " } // end of big switch.\n\n"
3536 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattnerb026e702006-03-28 00:41:33 +00003537 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3538 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3539 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003540 << " N.Val->dump(CurDAG);\n"
3541 << " } else {\n"
3542 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3543 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3544 << " std::cerr << \"intrinsic %\"<< "
3545 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3546 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003547 << " std::cerr << '\\n';\n"
3548 << " abort();\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003549 << " return NULL;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003550 << "}\n";
3551}
3552
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003553void DAGISelEmitter::run(std::ostream &OS) {
3554 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3555 " target", OS);
3556
Chris Lattner1f39e292005-09-14 00:09:24 +00003557 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3558 << "// *** instruction selector class. These functions are really "
3559 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003560
Chris Lattner8dc728e2006-08-27 13:16:24 +00003561 OS << "#include \"llvm/Support/Compiler.h\"\n";
Evan Cheng233baf12006-07-26 23:06:27 +00003562
Chris Lattner706d2d32006-08-09 16:44:44 +00003563 OS << "// Instruction selector priority queue:\n"
3564 << "std::vector<SDNode*> ISelQueue;\n";
3565 OS << "/// Keep track of nodes which have already been added to queue.\n"
3566 << "unsigned char *ISelQueued;\n";
3567 OS << "/// Keep track of nodes which have already been selected.\n"
3568 << "unsigned char *ISelSelected;\n";
3569 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
3570 << "std::vector<SDNode*> ISelKilled;\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003571
Chris Lattner706d2d32006-08-09 16:44:44 +00003572 OS << "/// Sorting functions for the selection queue.\n"
3573 << "struct isel_sort : public std::binary_function"
3574 << "<SDNode*, SDNode*, bool> {\n"
3575 << " bool operator()(const SDNode* left, const SDNode* right) "
3576 << "const {\n"
3577 << " return (left->getNodeId() > right->getNodeId());\n"
3578 << " }\n"
3579 << "};\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003580
Chris Lattner706d2d32006-08-09 16:44:44 +00003581 OS << "inline void setQueued(int Id) {\n";
3582 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003583 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003584 OS << "inline bool isQueued(int Id) {\n";
3585 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003586 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003587 OS << "inline void setSelected(int Id) {\n";
3588 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003589 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003590 OS << "inline bool isSelected(int Id) {\n";
3591 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
3592 OS << "}\n\n";
Evan Cheng9bdca032006-08-07 22:17:58 +00003593
Chris Lattner8dc728e2006-08-27 13:16:24 +00003594 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003595 OS << " int Id = N.Val->getNodeId();\n";
3596 OS << " if (Id != -1 && !isQueued(Id)) {\n";
3597 OS << " ISelQueue.push_back(N.Val);\n";
3598 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3599 OS << " setQueued(Id);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003600 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003601 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003602
Chris Lattner706d2d32006-08-09 16:44:44 +00003603 OS << "inline void RemoveKilled() {\n";
3604OS << " unsigned NumKilled = ISelKilled.size();\n";
3605 OS << " if (NumKilled) {\n";
3606 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
3607 OS << " SDNode *Temp = ISelKilled[i];\n";
3608 OS << " std::remove(ISelQueue.begin(), ISelQueue.end(), Temp);\n";
3609 OS << " };\n";
3610 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3611 OS << " ISelKilled.clear();\n";
3612 OS << " }\n";
3613 OS << "}\n\n";
3614
Chris Lattner8dc728e2006-08-27 13:16:24 +00003615 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003616 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n";
3617 OS << " setSelected(F.Val->getNodeId());\n";
3618 OS << " RemoveKilled();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003619 OS << "}\n";
3620 OS << "inline void ReplaceUses(SDNode *F, SDNode *T) {\n";
3621 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
3622 OS << " setSelected(F->getNodeId());\n";
3623 OS << " RemoveKilled();\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003624 OS << "}\n\n";
3625
Evan Cheng966fd372006-09-11 02:24:43 +00003626 OS << "void DeleteNode(SDNode *N) {\n";
3627 OS << " CurDAG->DeleteNode(N);\n";
3628 OS << " for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); "
3629 << "I != E; ++I) {\n";
3630 OS << " SDNode *Operand = I->Val;\n";
3631 OS << " if (Operand->use_empty())\n";
3632 OS << " DeleteNode(Operand);\n";
3633 OS << " }\n";
3634 OS << "}\n";
3635
Evan Chenge41bf822006-02-05 06:43:12 +00003636 OS << "// SelectRoot - Top level entry to DAG isel.\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003637 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
3638 OS << " SelectRootInit();\n";
3639 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
3640 OS << " ISelQueued = new unsigned char[NumBytes];\n";
3641 OS << " ISelSelected = new unsigned char[NumBytes];\n";
3642 OS << " memset(ISelQueued, 0, NumBytes);\n";
3643 OS << " memset(ISelSelected, 0, NumBytes);\n";
3644 OS << "\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00003645 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
3646 << " // a reference to the root node, preventing it from being deleted,\n"
3647 << " // and tracking any changes of the root.\n"
3648 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
3649 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003650 OS << " while (!ISelQueue.empty()) {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003651 OS << " SDNode *Node = ISelQueue.front();\n";
3652 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3653 OS << " ISelQueue.pop_back();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003654 OS << " if (!isSelected(Node->getNodeId())) {\n";
Evan Cheng9ade2182006-08-26 05:34:46 +00003655 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
Evan Cheng966fd372006-09-11 02:24:43 +00003656 OS << " if (ResNode != Node) {\n";
3657 OS << " if (ResNode)\n";
3658 OS << " ReplaceUses(Node, ResNode);\n";
3659 OS << " if (Node->use_empty()) // Don't delete EntryToken, etc.\n";
3660 OS << " DeleteNode(Node);\n";
3661 OS << " }\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003662 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003663 OS << " }\n";
3664 OS << "\n";
3665 OS << " delete[] ISelQueued;\n";
3666 OS << " ISelQueued = NULL;\n";
3667 OS << " delete[] ISelSelected;\n";
3668 OS << " ISelSelected = NULL;\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00003669 OS << " return Dummy.getValue();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003670 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003671
Chris Lattner550525e2006-03-24 21:48:51 +00003672 Intrinsics = LoadIntrinsics(Records);
Chris Lattnerca559d02005-09-08 21:03:01 +00003673 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003674 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003675 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003676 ParsePatternFragments(OS);
3677 ParseInstructions();
3678 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003679
Chris Lattnere97603f2005-09-28 19:27:25 +00003680 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003681 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003682 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003683
Chris Lattnere46e17b2005-09-29 19:28:10 +00003684
3685 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3686 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003687 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3688 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00003689 std::cerr << "\n";
3690 });
3691
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003692 // At this point, we have full information about the 'Patterns' we need to
3693 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003694 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003695 EmitInstructionSelector(OS);
3696
3697 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3698 E = PatternFragments.end(); I != E; ++I)
3699 delete I->second;
3700 PatternFragments.clear();
3701
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003702 Instructions.clear();
3703}