blob: c3db37e696e6089b56f357330c3d6ddc11b60024 [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"
Chris Lattnerbe8e7212006-10-11 03:35:34 +000018#include "llvm/Support/MathExtras.h"
Bill Wendlingf5da1332006-12-07 22:21:48 +000019#include "llvm/Support/Streams.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000020#include <algorithm>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000021#include <set>
22using namespace llvm;
23
Chris Lattnerca559d02005-09-08 21:03:01 +000024//===----------------------------------------------------------------------===//
Chris Lattner3c7e18d2005-10-14 06:12:03 +000025// Helpers for working with extended types.
26
27/// FilterVTs - Filter a list of VT's according to a predicate.
28///
29template<typename T>
30static std::vector<MVT::ValueType>
31FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
32 std::vector<MVT::ValueType> Result;
33 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
34 if (Filter(InVTs[i]))
35 Result.push_back(InVTs[i]);
36 return Result;
37}
38
Nate Begemanb73628b2005-12-30 00:12:56 +000039template<typename T>
40static std::vector<unsigned char>
41FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42 std::vector<unsigned char> Result;
43 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
44 if (Filter((MVT::ValueType)InVTs[i]))
45 Result.push_back(InVTs[i]);
46 return Result;
Chris Lattner3c7e18d2005-10-14 06:12:03 +000047}
48
Nate Begemanb73628b2005-12-30 00:12:56 +000049static std::vector<unsigned char>
50ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
51 std::vector<unsigned char> Result;
52 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53 Result.push_back(InVTs[i]);
54 return Result;
55}
56
57static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
58 const std::vector<unsigned char> &RHS) {
59 if (LHS.size() > RHS.size()) return false;
60 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
Duraid Madinad47ae092005-12-30 16:41:48 +000061 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
Nate Begemanb73628b2005-12-30 00:12:56 +000062 return false;
63 return true;
64}
65
66/// isExtIntegerVT - Return true if the specified extended value type vector
67/// contains isInt or an integer value type.
Chris Lattner697f8842006-03-20 05:39:48 +000068static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000069 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
70 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
71}
72
73/// isExtFloatingPointVT - Return true if the specified extended value type
74/// vector contains isFP or a FP value type.
Chris Lattner697f8842006-03-20 05:39:48 +000075static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000076 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
Chris Lattner488580c2006-01-28 19:06:51 +000077 return EVTs[0] == MVT::isFP ||
78 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
Chris Lattner3c7e18d2005-10-14 06:12:03 +000079}
80
81//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000082// SDTypeConstraint implementation
83//
84
85SDTypeConstraint::SDTypeConstraint(Record *R) {
86 OperandNo = R->getValueAsInt("OperandNum");
87
88 if (R->isSubClassOf("SDTCisVT")) {
89 ConstraintType = SDTCisVT;
90 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattner5b21be72005-12-09 22:57:42 +000091 } else if (R->isSubClassOf("SDTCisPtrTy")) {
92 ConstraintType = SDTCisPtrTy;
Chris Lattner33c92e92005-09-08 21:27:15 +000093 } else if (R->isSubClassOf("SDTCisInt")) {
94 ConstraintType = SDTCisInt;
95 } else if (R->isSubClassOf("SDTCisFP")) {
96 ConstraintType = SDTCisFP;
97 } else if (R->isSubClassOf("SDTCisSameAs")) {
98 ConstraintType = SDTCisSameAs;
99 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
100 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
101 ConstraintType = SDTCisVTSmallerThanOp;
102 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
103 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +0000104 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
105 ConstraintType = SDTCisOpSmallerThanOp;
106 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
107 R->getValueAsInt("BigOperandNum");
Chris Lattner697f8842006-03-20 05:39:48 +0000108 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
109 ConstraintType = SDTCisIntVectorOfSameSize;
110 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
111 R->getValueAsInt("OtherOpNum");
Chris Lattner33c92e92005-09-08 21:27:15 +0000112 } else {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000113 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner33c92e92005-09-08 21:27:15 +0000114 exit(1);
115 }
116}
117
Chris Lattner32707602005-09-08 23:22:48 +0000118/// getOperandNum - Return the node corresponding to operand #OpNo in tree
119/// N, which has NumResults results.
120TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
121 TreePatternNode *N,
122 unsigned NumResults) const {
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000123 assert(NumResults <= 1 &&
124 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000125
Evan Cheng50c997e2006-06-13 21:47:27 +0000126 if (OpNo >= (NumResults + N->getNumChildren())) {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000127 cerr << "Invalid operand number " << OpNo << " ";
Evan Cheng50c997e2006-06-13 21:47:27 +0000128 N->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +0000129 cerr << '\n';
Evan Cheng50c997e2006-06-13 21:47:27 +0000130 exit(1);
131 }
132
Chris Lattner32707602005-09-08 23:22:48 +0000133 if (OpNo < NumResults)
134 return N; // FIXME: need value #
135 else
136 return N->getChild(OpNo-NumResults);
137}
138
139/// ApplyTypeConstraint - Given a node in a pattern, apply this type
140/// constraint to the nodes operands. This returns true if it makes a
141/// change, false otherwise. If a type contradiction is found, throw an
142/// exception.
143bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
144 const SDNodeInfo &NodeInfo,
145 TreePattern &TP) const {
146 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000147 assert(NumResults <= 1 &&
148 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000149
Chris Lattner8f60d542006-06-16 18:25:06 +0000150 // Check that the number of operands is sane. Negative operands -> varargs.
Chris Lattner32707602005-09-08 23:22:48 +0000151 if (NodeInfo.getNumOperands() >= 0) {
152 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
153 TP.error(N->getOperator()->getName() + " node requires exactly " +
154 itostr(NodeInfo.getNumOperands()) + " operands!");
155 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000156
157 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000158
159 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
160
161 switch (ConstraintType) {
162 default: assert(0 && "Unknown constraint type!");
163 case SDTCisVT:
164 // Operand must be a particular type.
165 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000166 case SDTCisPtrTy: {
167 // Operand must be same as target pointer type.
Evan Cheng2618d072006-05-17 20:37:59 +0000168 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000169 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000170 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000171 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000172 std::vector<MVT::ValueType> IntVTs =
173 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000174
175 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000176 if (IntVTs.size() == 1)
177 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000178 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000179 }
180 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000181 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000182 std::vector<MVT::ValueType> FPVTs =
183 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000184
185 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000186 if (FPVTs.size() == 1)
187 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000188 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000189 }
Chris Lattner32707602005-09-08 23:22:48 +0000190 case SDTCisSameAs: {
191 TreePatternNode *OtherNode =
192 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Nate Begemanb73628b2005-12-30 00:12:56 +0000193 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
194 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000195 }
196 case SDTCisVTSmallerThanOp: {
197 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
198 // have an integer type that is smaller than the VT.
199 if (!NodeToApply->isLeaf() ||
200 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
201 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
202 ->isSubClassOf("ValueType"))
203 TP.error(N->getOperator()->getName() + " expects a VT operand!");
204 MVT::ValueType VT =
205 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
206 if (!MVT::isInteger(VT))
207 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
208
209 TreePatternNode *OtherNode =
210 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000211
212 // It must be integer.
213 bool MadeChange = false;
214 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
215
Nate Begemanb73628b2005-12-30 00:12:56 +0000216 // This code only handles nodes that have one type set. Assert here so
217 // that we can change this if we ever need to deal with multiple value
218 // types at this point.
219 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
220 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000221 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
222 return false;
223 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000224 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000225 TreePatternNode *BigOperand =
226 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
227
228 // Both operands must be integer or FP, but we don't care which.
229 bool MadeChange = false;
230
Nate Begemanb73628b2005-12-30 00:12:56 +0000231 // This code does not currently handle nodes which have multiple types,
232 // where some types are integer, and some are fp. Assert that this is not
233 // the case.
234 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
235 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
236 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
237 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
238 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
239 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000240 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000241 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000242 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000243 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000244 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000245 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000246 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
247
248 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
249
Nate Begemanb73628b2005-12-30 00:12:56 +0000250 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000251 VTs = FilterVTs(VTs, MVT::isInteger);
Nate Begemanb73628b2005-12-30 00:12:56 +0000252 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000253 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
254 } else {
255 VTs.clear();
256 }
257
258 switch (VTs.size()) {
259 default: // Too many VT's to pick from.
260 case 0: break; // No info yet.
261 case 1:
262 // Only one VT of this flavor. Cannot ever satisify the constraints.
263 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
264 case 2:
265 // If we have exactly two possible types, the little operand must be the
266 // small one, the big operand should be the big one. Common with
267 // float/double for example.
268 assert(VTs[0] < VTs[1] && "Should be sorted!");
269 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
270 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
271 break;
272 }
273 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000274 }
Chris Lattner697f8842006-03-20 05:39:48 +0000275 case SDTCisIntVectorOfSameSize: {
276 TreePatternNode *OtherOperand =
277 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
278 N, NumResults);
279 if (OtherOperand->hasTypeSet()) {
280 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
281 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
282 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
283 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
284 return NodeToApply->UpdateNodeType(IVT, TP);
285 }
286 return false;
287 }
Chris Lattner32707602005-09-08 23:22:48 +0000288 }
289 return false;
290}
291
292
Chris Lattner33c92e92005-09-08 21:27:15 +0000293//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000294// SDNodeInfo implementation
295//
296SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
297 EnumName = R->getValueAsString("Opcode");
298 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000299 Record *TypeProfile = R->getValueAsDef("TypeProfile");
300 NumResults = TypeProfile->getValueAsInt("NumResults");
301 NumOperands = TypeProfile->getValueAsInt("NumOperands");
302
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000303 // Parse the properties.
304 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000305 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000306 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
307 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000308 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000309 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000310 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000311 } else if (PropList[i]->getName() == "SDNPHasChain") {
312 Properties |= 1 << SDNPHasChain;
Evan Cheng51fecc82006-01-09 18:27:06 +0000313 } else if (PropList[i]->getName() == "SDNPOutFlag") {
314 Properties |= 1 << SDNPOutFlag;
315 } else if (PropList[i]->getName() == "SDNPInFlag") {
316 Properties |= 1 << SDNPInFlag;
317 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
318 Properties |= 1 << SDNPOptInFlag;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000319 } else {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000320 cerr << "Unknown SD Node property '" << PropList[i]->getName()
321 << "' on node '" << R->getName() << "'!\n";
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000322 exit(1);
323 }
324 }
325
326
Chris Lattner33c92e92005-09-08 21:27:15 +0000327 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000328 std::vector<Record*> ConstraintList =
329 TypeProfile->getValueAsListOfDefs("Constraints");
330 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000331}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000332
333//===----------------------------------------------------------------------===//
334// TreePatternNode implementation
335//
336
337TreePatternNode::~TreePatternNode() {
338#if 0 // FIXME: implement refcounted tree nodes!
339 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
340 delete getChild(i);
341#endif
342}
343
Chris Lattner32707602005-09-08 23:22:48 +0000344/// UpdateNodeType - Set the node type of N to VT if VT contains
345/// information. If N already contains a conflicting type, then throw an
346/// exception. This returns true if any information was updated.
347///
Nate Begemanb73628b2005-12-30 00:12:56 +0000348bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
349 TreePattern &TP) {
350 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
351
352 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
353 return false;
354 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
355 setTypes(ExtVTs);
Chris Lattner32707602005-09-08 23:22:48 +0000356 return true;
357 }
Evan Cheng2618d072006-05-17 20:37:59 +0000358
359 if (getExtTypeNum(0) == MVT::iPTR) {
360 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
361 return false;
362 if (isExtIntegerInVTs(ExtVTs)) {
363 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
364 if (FVTs.size()) {
365 setTypes(ExtVTs);
366 return true;
367 }
368 }
369 }
Chris Lattner32707602005-09-08 23:22:48 +0000370
Nate Begemanb73628b2005-12-30 00:12:56 +0000371 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
372 assert(hasTypeSet() && "should be handled above!");
373 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
374 if (getExtTypes() == FVTs)
375 return false;
376 setTypes(FVTs);
377 return true;
378 }
Evan Cheng2618d072006-05-17 20:37:59 +0000379 if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
380 //assert(hasTypeSet() && "should be handled above!");
381 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
382 if (getExtTypes() == FVTs)
383 return false;
384 if (FVTs.size()) {
385 setTypes(FVTs);
386 return true;
387 }
388 }
Nate Begemanb73628b2005-12-30 00:12:56 +0000389 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
390 assert(hasTypeSet() && "should be handled above!");
Chris Lattner488580c2006-01-28 19:06:51 +0000391 std::vector<unsigned char> FVTs =
392 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
Nate Begemanb73628b2005-12-30 00:12:56 +0000393 if (getExtTypes() == FVTs)
394 return false;
395 setTypes(FVTs);
396 return true;
397 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000398
399 // If we know this is an int or fp type, and we are told it is a specific one,
400 // take the advice.
Nate Begemanb73628b2005-12-30 00:12:56 +0000401 //
402 // Similarly, we should probably set the type here to the intersection of
403 // {isInt|isFP} and ExtVTs
404 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
405 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
406 setTypes(ExtVTs);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000407 return true;
Evan Cheng2618d072006-05-17 20:37:59 +0000408 }
409 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
410 setTypes(ExtVTs);
411 return true;
412 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000413
Chris Lattner1531f202005-10-26 16:59:37 +0000414 if (isLeaf()) {
415 dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +0000416 cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000417 TP.error("Type inference contradiction found in node!");
418 } else {
419 TP.error("Type inference contradiction found in node " +
420 getOperator()->getName() + "!");
421 }
Chris Lattner32707602005-09-08 23:22:48 +0000422 return true; // unreachable
423}
424
425
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000426void TreePatternNode::print(std::ostream &OS) const {
427 if (isLeaf()) {
428 OS << *getLeafValue();
429 } else {
430 OS << "(" << getOperator()->getName();
431 }
432
Nate Begemanb73628b2005-12-30 00:12:56 +0000433 // FIXME: At some point we should handle printing all the value types for
434 // nodes that are multiply typed.
435 switch (getExtTypeNum(0)) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000436 case MVT::Other: OS << ":Other"; break;
437 case MVT::isInt: OS << ":isInt"; break;
438 case MVT::isFP : OS << ":isFP"; break;
439 case MVT::isUnknown: ; /*OS << ":?";*/ break;
Evan Cheng2618d072006-05-17 20:37:59 +0000440 case MVT::iPTR: OS << ":iPTR"; break;
Chris Lattner02cdb372006-06-20 00:56:37 +0000441 default: {
442 std::string VTName = llvm::getName(getTypeNum(0));
443 // Strip off MVT:: prefix if present.
444 if (VTName.substr(0,5) == "MVT::")
445 VTName = VTName.substr(5);
446 OS << ":" << VTName;
447 break;
448 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000449 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000450
451 if (!isLeaf()) {
452 if (getNumChildren() != 0) {
453 OS << " ";
454 getChild(0)->print(OS);
455 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
456 OS << ", ";
457 getChild(i)->print(OS);
458 }
459 }
460 OS << ")";
461 }
462
463 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000464 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000465 if (TransformFn)
466 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000467 if (!getName().empty())
468 OS << ":$" << getName();
469
470}
471void TreePatternNode::dump() const {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000472 print(*cerr.stream());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000473}
474
Chris Lattnere46e17b2005-09-29 19:28:10 +0000475/// isIsomorphicTo - Return true if this node is recursively isomorphic to
476/// the specified node. For this comparison, all of the state of the node
477/// is considered, except for the assigned name. Nodes with differing names
478/// that are otherwise identical are considered isomorphic.
479bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
480 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000481 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000482 getPredicateFn() != N->getPredicateFn() ||
483 getTransformFn() != N->getTransformFn())
484 return false;
485
486 if (isLeaf()) {
487 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
488 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
489 return DI->getDef() == NDI->getDef();
490 return getLeafValue() == N->getLeafValue();
491 }
492
493 if (N->getOperator() != getOperator() ||
494 N->getNumChildren() != getNumChildren()) return false;
495 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
496 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
497 return false;
498 return true;
499}
500
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000501/// clone - Make a copy of this tree and all of its children.
502///
503TreePatternNode *TreePatternNode::clone() const {
504 TreePatternNode *New;
505 if (isLeaf()) {
506 New = new TreePatternNode(getLeafValue());
507 } else {
508 std::vector<TreePatternNode*> CChildren;
509 CChildren.reserve(Children.size());
510 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
511 CChildren.push_back(getChild(i)->clone());
512 New = new TreePatternNode(getOperator(), CChildren);
513 }
514 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000515 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000516 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000517 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000518 return New;
519}
520
Chris Lattner32707602005-09-08 23:22:48 +0000521/// SubstituteFormalArguments - Replace the formal arguments in this tree
522/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000523void TreePatternNode::
524SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
525 if (isLeaf()) return;
526
527 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
528 TreePatternNode *Child = getChild(i);
529 if (Child->isLeaf()) {
530 Init *Val = Child->getLeafValue();
531 if (dynamic_cast<DefInit*>(Val) &&
532 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
533 // We found a use of a formal argument, replace it with its value.
534 Child = ArgMap[Child->getName()];
535 assert(Child && "Couldn't find formal argument!");
536 setChild(i, Child);
537 }
538 } else {
539 getChild(i)->SubstituteFormalArguments(ArgMap);
540 }
541 }
542}
543
544
545/// InlinePatternFragments - If this pattern refers to any pattern
546/// fragments, inline them into place, giving us a pattern without any
547/// PatFrag references.
548TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
549 if (isLeaf()) return this; // nothing to do.
550 Record *Op = getOperator();
551
552 if (!Op->isSubClassOf("PatFrag")) {
553 // Just recursively inline children nodes.
554 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
555 setChild(i, getChild(i)->InlinePatternFragments(TP));
556 return this;
557 }
558
559 // Otherwise, we found a reference to a fragment. First, look up its
560 // TreePattern record.
561 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
562
563 // Verify that we are passing the right number of operands.
564 if (Frag->getNumArgs() != Children.size())
565 TP.error("'" + Op->getName() + "' fragment requires " +
566 utostr(Frag->getNumArgs()) + " operands!");
567
Chris Lattner37937092005-09-09 01:15:01 +0000568 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000569
570 // Resolve formal arguments to their actual value.
571 if (Frag->getNumArgs()) {
572 // Compute the map of formal to actual arguments.
573 std::map<std::string, TreePatternNode*> ArgMap;
574 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
575 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
576
577 FragTree->SubstituteFormalArguments(ArgMap);
578 }
579
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000580 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000581 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000582
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000583 // Get a new copy of this fragment to stitch into here.
584 //delete this; // FIXME: implement refcounting!
585 return FragTree;
586}
587
Chris Lattner52793e22006-04-06 20:19:52 +0000588/// getImplicitType - Check to see if the specified record has an implicit
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000589/// type which should be applied to it. This infer the type of register
590/// references from the register file information, for example.
591///
Chris Lattner52793e22006-04-06 20:19:52 +0000592static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000593 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000594 // Some common return values
595 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
596 std::vector<unsigned char> Other(1, MVT::Other);
597
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000598 // Check to see if this is a register or a register class...
599 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000600 if (NotRegisters)
601 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000602 const CodeGenRegisterClass &RC =
603 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000604 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000605 } else if (R->isSubClassOf("PatFrag")) {
606 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000607 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000608 } else if (R->isSubClassOf("Register")) {
Evan Cheng37e90052006-01-15 10:04:45 +0000609 if (NotRegisters)
610 return Unknown;
Chris Lattner22faeab2005-12-05 02:36:37 +0000611 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
Evan Cheng44a65fa2006-05-16 07:05:30 +0000612 return T.getRegisterVTs(R);
Chris Lattner1531f202005-10-26 16:59:37 +0000613 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
614 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000615 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000616 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng57c517d2006-01-17 07:36:41 +0000617 if (NotRegisters)
618 return Unknown;
Nate Begemanb73628b2005-12-30 00:12:56 +0000619 std::vector<unsigned char>
620 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
621 return ComplexPat;
Chris Lattner646085d2006-11-14 21:18:40 +0000622 } else if (R->getName() == "ptr_rc") {
623 Other[0] = MVT::iPTR;
624 return Other;
Evan Cheng01f318b2005-12-14 02:21:57 +0000625 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000626 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000627 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000628 }
629
630 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000631 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000632}
633
Chris Lattner32707602005-09-08 23:22:48 +0000634/// ApplyTypeConstraints - Apply all of the type constraints relevent to
635/// this node and its children in the tree. This returns true if it makes a
636/// change, false otherwise. If a type contradiction is found, throw an
637/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000638bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000639 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000640 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000641 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000642 // If it's a regclass or something else known, include the type.
Chris Lattner52793e22006-04-06 20:19:52 +0000643 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000644 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
645 // Int inits are always integers. :)
646 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
647
648 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000649 // At some point, it may make sense for this tree pattern to have
650 // multiple types. Assert here that it does not, so we revisit this
651 // code when appropriate.
Evan Cheng2618d072006-05-17 20:37:59 +0000652 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Evan Cheng44a65fa2006-05-16 07:05:30 +0000653 MVT::ValueType VT = getTypeNum(0);
654 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
655 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
Nate Begemanb73628b2005-12-30 00:12:56 +0000656
Evan Cheng2618d072006-05-17 20:37:59 +0000657 VT = getTypeNum(0);
658 if (VT != MVT::iPTR) {
659 unsigned Size = MVT::getSizeInBits(VT);
660 // Make sure that the value is representable for this type.
661 if (Size < 32) {
662 int Val = (II->getValue() << (32-Size)) >> (32-Size);
663 if (Val != II->getValue())
664 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
665 "' is out of range for type '" +
666 getEnumName(getTypeNum(0)) + "'!");
667 }
Chris Lattner465c7372005-11-03 05:46:11 +0000668 }
669 }
670
671 return MadeChange;
672 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000673 return false;
674 }
Chris Lattner32707602005-09-08 23:22:48 +0000675
676 // special handling for set, which isn't really an SDNode.
677 if (getOperator()->getName() == "set") {
678 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000679 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
680 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000681
682 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000683 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
684 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000685 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
686 return MadeChange;
Chris Lattner5a1df382006-03-24 23:10:39 +0000687 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
688 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
689 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
690 unsigned IID =
691 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
692 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
693 bool MadeChange = false;
694
695 // Apply the result type to the node.
696 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
697
698 if (getNumChildren() != Int.ArgVTs.size())
Chris Lattner2c4e65d2006-03-27 22:21:18 +0000699 TP.error("Intrinsic '" + Int.Name + "' expects " +
Chris Lattner5a1df382006-03-24 23:10:39 +0000700 utostr(Int.ArgVTs.size()-1) + " operands, not " +
701 utostr(getNumChildren()-1) + " operands!");
702
703 // Apply type info to the intrinsic ID.
Evan Cheng2618d072006-05-17 20:37:59 +0000704 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5a1df382006-03-24 23:10:39 +0000705
706 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
707 MVT::ValueType OpVT = Int.ArgVTs[i];
708 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
709 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
710 }
711 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000712 } else if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000713 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
Chris Lattnerabbb6052005-09-15 21:42:00 +0000714
715 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
716 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000717 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000718 // Branch, etc. do not produce results and top-level forms in instr pattern
719 // must have void types.
720 if (NI.getNumResults() == 0)
721 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner91ded082006-04-06 20:36:51 +0000722
723 // If this is a vector_shuffle operation, apply types to the build_vector
724 // operation. The types of the integers don't matter, but this ensures they
725 // won't get checked.
726 if (getOperator()->getName() == "vector_shuffle" &&
727 getChild(2)->getOperator()->getName() == "build_vector") {
728 TreePatternNode *BV = getChild(2);
729 const std::vector<MVT::ValueType> &LegalVTs
730 = ISE.getTargetInfo().getLegalValueTypes();
731 MVT::ValueType LegalIntVT = MVT::Other;
732 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
733 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
734 LegalIntVT = LegalVTs[i];
735 break;
736 }
737 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
738
739 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
740 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
741 }
Chris Lattnerabbb6052005-09-15 21:42:00 +0000742 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000743 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000744 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000745 bool MadeChange = false;
746 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000747
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000748 assert(NumResults <= 1 &&
749 "Only supports zero or one result instrs!");
Evan Chengeb1f40d2006-07-20 23:36:20 +0000750
751 CodeGenInstruction &InstInfo =
752 ISE.getTargetInfo().getInstruction(getOperator()->getName());
Chris Lattnera28aec12005-09-15 22:23:50 +0000753 // Apply the result type to the node
Chris Lattner646085d2006-11-14 21:18:40 +0000754 if (NumResults == 0 || InstInfo.noResults) { // FIXME: temporary hack.
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000755 MadeChange = UpdateNodeType(MVT::isVoid, TP);
756 } else {
757 Record *ResultNode = Inst.getResult(0);
Chris Lattner646085d2006-11-14 21:18:40 +0000758
759 if (ResultNode->getName() == "ptr_rc") {
760 std::vector<unsigned char> VT;
761 VT.push_back(MVT::iPTR);
762 MadeChange = UpdateNodeType(VT, TP);
763 } else {
764 assert(ResultNode->isSubClassOf("RegisterClass") &&
765 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000766
Chris Lattner646085d2006-11-14 21:18:40 +0000767 const CodeGenRegisterClass &RC =
768 ISE.getTargetInfo().getRegisterClass(ResultNode);
769 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
770 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000771 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000772
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000773 unsigned ChildNo = 0;
774 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000775 Record *OperandNode = Inst.getOperand(i);
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000776
777 // If the instruction expects a predicate operand, we codegen this by
Evan Cheng59039632007-05-08 21:04:07 +0000778 // setting the predicate to it's "execute always" value if it has a
779 // non-empty ExecuteAlways field.
780 if (OperandNode->isSubClassOf("PredicateOperand") &&
781 !ISE.getPredicateOperand(OperandNode).AlwaysOps.empty())
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000782 continue;
783
784 // Verify that we didn't run out of provided operands.
785 if (ChildNo >= getNumChildren())
786 TP.error("Instruction '" + getOperator()->getName() +
787 "' expects more operands than were provided.");
788
Nate Begemanddb39542005-12-01 00:06:14 +0000789 MVT::ValueType VT;
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000790 TreePatternNode *Child = getChild(ChildNo++);
Nate Begemanddb39542005-12-01 00:06:14 +0000791 if (OperandNode->isSubClassOf("RegisterClass")) {
792 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000793 ISE.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000794 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000795 } else if (OperandNode->isSubClassOf("Operand")) {
796 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000797 MadeChange |= Child->UpdateNodeType(VT, TP);
Chris Lattner646085d2006-11-14 21:18:40 +0000798 } else if (OperandNode->getName() == "ptr_rc") {
799 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000800 } else {
801 assert(0 && "Unknown operand type!");
802 abort();
803 }
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000804 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000805 }
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000806
807 if (ChildNo != getNumChildren())
808 TP.error("Instruction '" + getOperator()->getName() +
809 "' was provided too many operands!");
810
Chris Lattnera28aec12005-09-15 22:23:50 +0000811 return MadeChange;
812 } else {
813 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
814
Evan Chengf26ba692006-03-20 08:09:17 +0000815 // Node transforms always take one operand.
Chris Lattnera28aec12005-09-15 22:23:50 +0000816 if (getNumChildren() != 1)
817 TP.error("Node transform '" + getOperator()->getName() +
818 "' requires one operand!");
Chris Lattner4e2f54d2006-03-21 06:42:58 +0000819
820 // If either the output or input of the xform does not have exact
821 // type info. We assume they must be the same. Otherwise, it is perfectly
822 // legal to transform from one type to a completely different type.
823 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Evan Chengf26ba692006-03-20 08:09:17 +0000824 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
825 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
826 return MadeChange;
827 }
828 return false;
Chris Lattner32707602005-09-08 23:22:48 +0000829 }
Chris Lattner32707602005-09-08 23:22:48 +0000830}
831
Chris Lattnerce6e84c2006-09-21 20:46:13 +0000832/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
833/// RHS of a commutative operation, not the on LHS.
834static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
835 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
836 return true;
837 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
838 return true;
839 return false;
840}
841
842
Chris Lattnere97603f2005-09-28 19:27:25 +0000843/// canPatternMatch - If it is impossible for this pattern to match on this
844/// target, fill in Reason and return false. Otherwise, return true. This is
845/// used as a santity check for .td files (to prevent people from writing stuff
846/// that can never possibly work), and to prevent the pattern permuter from
847/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000848bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000849 if (isLeaf()) return true;
850
851 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
852 if (!getChild(i)->canPatternMatch(Reason, ISE))
853 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000854
Chris Lattner550525e2006-03-24 21:48:51 +0000855 // If this is an intrinsic, handle cases that would make it not match. For
856 // example, if an operand is required to be an immediate.
857 if (getOperator()->isSubClassOf("Intrinsic")) {
858 // TODO:
859 return true;
860 }
861
Chris Lattnere97603f2005-09-28 19:27:25 +0000862 // If this node is a commutative operator, check that the LHS isn't an
863 // immediate.
864 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
Evan Cheng94b30402006-10-11 21:02:01 +0000865 if (NodeInfo.hasProperty(SDNPCommutative)) {
Chris Lattnere97603f2005-09-28 19:27:25 +0000866 // Scan all of the operands of the node and make sure that only the last one
Chris Lattner7905c552006-09-14 23:54:24 +0000867 // is a constant node, unless the RHS also is.
Chris Lattnerce6e84c2006-09-21 20:46:13 +0000868 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Chris Lattner7905c552006-09-14 23:54:24 +0000869 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
Chris Lattnerce6e84c2006-09-21 20:46:13 +0000870 if (OnlyOnRHSOfCommutative(getChild(i))) {
Chris Lattner64906972006-09-21 18:28:27 +0000871 Reason="Immediate value must be on the RHS of commutative operators!";
Chris Lattner7905c552006-09-14 23:54:24 +0000872 return false;
873 }
874 }
Chris Lattnere97603f2005-09-28 19:27:25 +0000875 }
876
877 return true;
878}
Chris Lattner32707602005-09-08 23:22:48 +0000879
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000880//===----------------------------------------------------------------------===//
881// TreePattern implementation
882//
883
Chris Lattneredbd8712005-10-21 01:19:59 +0000884TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000885 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000886 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000887 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
888 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000889}
890
Chris Lattneredbd8712005-10-21 01:19:59 +0000891TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000892 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000893 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000894 Trees.push_back(ParseTreePattern(Pat));
895}
896
Chris Lattneredbd8712005-10-21 01:19:59 +0000897TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000898 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000899 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000900 Trees.push_back(Pat);
901}
902
903
904
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000905void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000906 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000907 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000908}
909
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000910TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
Chris Lattner8c063182006-03-30 22:50:40 +0000911 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
912 if (!OpDef) error("Pattern has unexpected operator type!");
913 Record *Operator = OpDef->getDef();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000914
915 if (Operator->isSubClassOf("ValueType")) {
916 // If the operator is a ValueType, then this must be "type cast" of a leaf
917 // node.
918 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000919 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000920
921 Init *Arg = Dag->getArg(0);
922 TreePatternNode *New;
923 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000924 Record *R = DI->getDef();
925 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000926 Dag->setArg(0, new DagInit(DI,
Chris Lattner72fe91c2005-09-24 00:40:24 +0000927 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000928 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000929 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000930 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000931 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
932 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000933 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
934 New = new TreePatternNode(II);
935 if (!Dag->getArgName(0).empty())
936 error("Constant int argument should not have a name!");
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000937 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
938 // Turn this into an IntInit.
939 Init *II = BI->convertInitializerTo(new IntRecTy());
940 if (II == 0 || !dynamic_cast<IntInit*>(II))
941 error("Bits value must be constants!");
942
943 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
944 if (!Dag->getArgName(0).empty())
945 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000946 } else {
947 Arg->dump();
948 error("Unknown leaf value for tree pattern!");
949 return 0;
950 }
951
Chris Lattner32707602005-09-08 23:22:48 +0000952 // Apply the type cast.
953 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000954 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000955 return New;
956 }
957
958 // Verify that this is something that makes sense for an operator.
959 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000960 !Operator->isSubClassOf("Instruction") &&
961 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner550525e2006-03-24 21:48:51 +0000962 !Operator->isSubClassOf("Intrinsic") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000963 Operator->getName() != "set")
964 error("Unrecognized node '" + Operator->getName() + "'!");
965
Chris Lattneredbd8712005-10-21 01:19:59 +0000966 // Check to see if this is something that is illegal in an input pattern.
967 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
Chris Lattner5a1df382006-03-24 23:10:39 +0000968 Operator->isSubClassOf("SDNodeXForm")))
Chris Lattneredbd8712005-10-21 01:19:59 +0000969 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
970
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000971 std::vector<TreePatternNode*> Children;
972
973 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
974 Init *Arg = Dag->getArg(i);
975 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
976 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000977 if (Children.back()->getName().empty())
978 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000979 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
980 Record *R = DefI->getDef();
981 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
982 // TreePatternNode if its own.
983 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000984 Dag->setArg(i, new DagInit(DefI,
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000985 std::vector<std::pair<Init*, std::string> >()));
986 --i; // Revisit this node...
987 } else {
988 TreePatternNode *Node = new TreePatternNode(DefI);
989 Node->setName(Dag->getArgName(i));
990 Children.push_back(Node);
991
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000992 // Input argument?
993 if (R->getName() == "node") {
994 if (Dag->getArgName(i).empty())
995 error("'node' argument requires a name to match with operand list");
996 Args.push_back(Dag->getArgName(i));
997 }
998 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000999 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1000 TreePatternNode *Node = new TreePatternNode(II);
1001 if (!Dag->getArgName(i).empty())
1002 error("Constant int argument should not have a name!");
1003 Children.push_back(Node);
Chris Lattnerffa4fdc2006-03-31 05:25:56 +00001004 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1005 // Turn this into an IntInit.
1006 Init *II = BI->convertInitializerTo(new IntRecTy());
1007 if (II == 0 || !dynamic_cast<IntInit*>(II))
1008 error("Bits value must be constants!");
1009
1010 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1011 if (!Dag->getArgName(i).empty())
1012 error("Constant int argument should not have a name!");
1013 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001014 } else {
Bill Wendlingf5da1332006-12-07 22:21:48 +00001015 cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001016 Arg->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00001017 cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001018 error("Unknown leaf value for tree pattern!");
1019 }
1020 }
1021
Chris Lattner5a1df382006-03-24 23:10:39 +00001022 // If the operator is an intrinsic, then this is just syntactic sugar for for
1023 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1024 // convert the intrinsic name to a number.
1025 if (Operator->isSubClassOf("Intrinsic")) {
1026 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
1027 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
1028
1029 // If this intrinsic returns void, it must have side-effects and thus a
1030 // chain.
1031 if (Int.ArgVTs[0] == MVT::isVoid) {
1032 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
1033 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1034 // Has side-effects, requires chain.
1035 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
1036 } else {
1037 // Otherwise, no chain.
1038 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
1039 }
1040
1041 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1042 Children.insert(Children.begin(), IIDNode);
1043 }
1044
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001045 return new TreePatternNode(Operator, Children);
1046}
1047
Chris Lattner32707602005-09-08 23:22:48 +00001048/// InferAllTypes - Infer/propagate as many types throughout the expression
1049/// patterns as possible. Return true if all types are infered, false
1050/// otherwise. Throw an exception if a type contradiction is found.
1051bool TreePattern::InferAllTypes() {
1052 bool MadeChange = true;
1053 while (MadeChange) {
1054 MadeChange = false;
1055 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001056 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +00001057 }
1058
1059 bool HasUnresolvedTypes = false;
1060 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1061 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1062 return !HasUnresolvedTypes;
1063}
1064
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001065void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001066 OS << getRecord()->getName();
1067 if (!Args.empty()) {
1068 OS << "(" << Args[0];
1069 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1070 OS << ", " << Args[i];
1071 OS << ")";
1072 }
1073 OS << ": ";
1074
1075 if (Trees.size() > 1)
1076 OS << "[\n";
1077 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1078 OS << "\t";
1079 Trees[i]->print(OS);
1080 OS << "\n";
1081 }
1082
1083 if (Trees.size() > 1)
1084 OS << "]\n";
1085}
1086
Bill Wendlingf5da1332006-12-07 22:21:48 +00001087void TreePattern::dump() const { print(*cerr.stream()); }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001088
1089
1090
1091//===----------------------------------------------------------------------===//
1092// DAGISelEmitter implementation
1093//
1094
Chris Lattnerca559d02005-09-08 21:03:01 +00001095// Parse all of the SDNode definitions for the target, populating SDNodes.
1096void DAGISelEmitter::ParseNodeInfo() {
1097 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1098 while (!Nodes.empty()) {
1099 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1100 Nodes.pop_back();
1101 }
Chris Lattner5a1df382006-03-24 23:10:39 +00001102
1103 // Get the buildin intrinsic nodes.
1104 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1105 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1106 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
Chris Lattnerca559d02005-09-08 21:03:01 +00001107}
1108
Chris Lattner24eeeb82005-09-13 21:51:00 +00001109/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1110/// map, and emit them to the file as functions.
1111void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1112 OS << "\n// Node transformations.\n";
1113 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1114 while (!Xforms.empty()) {
1115 Record *XFormNode = Xforms.back();
1116 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1117 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1118 SDNodeXForms.insert(std::make_pair(XFormNode,
1119 std::make_pair(SDNode, Code)));
1120
Chris Lattner1048b7a2005-09-13 22:03:37 +00001121 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +00001122 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1123 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1124
Chris Lattner1048b7a2005-09-13 22:03:37 +00001125 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +00001126 << "(SDNode *" << C2 << ") {\n";
1127 if (ClassName != "SDNode")
1128 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1129 OS << Code << "\n}\n";
1130 }
1131
1132 Xforms.pop_back();
1133 }
1134}
1135
Evan Cheng0fc71982005-12-08 02:00:36 +00001136void DAGISelEmitter::ParseComplexPatterns() {
1137 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1138 while (!AMs.empty()) {
1139 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1140 AMs.pop_back();
1141 }
1142}
Chris Lattner24eeeb82005-09-13 21:51:00 +00001143
1144
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001145/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1146/// file, building up the PatternFragments map. After we've collected them all,
1147/// inline fragments together as necessary, so that there are no references left
1148/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001149///
1150/// This also emits all of the predicate functions to the output file.
1151///
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001152void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001153 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1154
1155 // First step, parse all of the fragments and emit predicate functions.
1156 OS << "\n// Predicate functions.\n";
1157 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001158 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +00001159 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001160 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +00001161
1162 // Validate the argument list, converting it to map, to discard duplicates.
1163 std::vector<std::string> &Args = P->getArgList();
1164 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1165
1166 if (OperandsMap.count(""))
1167 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1168
1169 // Parse the operands list.
1170 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Chris Lattner8c063182006-03-30 22:50:40 +00001171 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1172 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
Chris Lattneree9f0c32005-09-13 21:20:49 +00001173 P->error("Operands list should start with '(ops ... '!");
1174
1175 // Copy over the arguments.
1176 Args.clear();
1177 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1178 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1179 static_cast<DefInit*>(OpsList->getArg(j))->
1180 getDef()->getName() != "node")
1181 P->error("Operands list should all be 'node' values.");
1182 if (OpsList->getArgName(j).empty())
1183 P->error("Operands list should have names for each operand!");
1184 if (!OperandsMap.count(OpsList->getArgName(j)))
1185 P->error("'" + OpsList->getArgName(j) +
1186 "' does not occur in pattern or was multiply specified!");
1187 OperandsMap.erase(OpsList->getArgName(j));
1188 Args.push_back(OpsList->getArgName(j));
1189 }
1190
1191 if (!OperandsMap.empty())
1192 P->error("Operands list does not contain an entry for operand '" +
1193 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001194
1195 // If there is a code init for this fragment, emit the predicate code and
1196 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +00001197 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1198 if (!Code.empty()) {
Evan Chengd46bd602006-09-19 19:08:04 +00001199 if (P->getOnlyTree()->isLeaf())
1200 OS << "inline bool Predicate_" << Fragments[i]->getName()
1201 << "(SDNode *N) {\n";
1202 else {
1203 std::string ClassName =
1204 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1205 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001206
Evan Chengd46bd602006-09-19 19:08:04 +00001207 OS << "inline bool Predicate_" << Fragments[i]->getName()
1208 << "(SDNode *" << C2 << ") {\n";
1209 if (ClassName != "SDNode")
1210 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1211 }
Chris Lattner24eeeb82005-09-13 21:51:00 +00001212 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +00001213 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001214 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001215
1216 // If there is a node transformation corresponding to this, keep track of
1217 // it.
1218 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1219 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001220 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001221 }
1222
1223 OS << "\n\n";
1224
1225 // Now that we've parsed all of the tree fragments, do a closure on them so
1226 // that there are not references to PatFrags left inside of them.
1227 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1228 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001229 TreePattern *ThePat = I->second;
1230 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001231
Chris Lattner32707602005-09-08 23:22:48 +00001232 // Infer as many types as possible. Don't worry about it if we don't infer
1233 // all of them, some may depend on the inputs of the pattern.
1234 try {
1235 ThePat->InferAllTypes();
1236 } catch (...) {
1237 // If this pattern fragment is not supported by this target (no types can
1238 // satisfy its constraints), just ignore it. If the bogus pattern is
1239 // actually used by instructions, the type consistency error will be
1240 // reported there.
1241 }
1242
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001243 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001244 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001245 }
1246}
1247
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001248void DAGISelEmitter::ParsePredicateOperands() {
1249 std::vector<Record*> PredOps =
1250 Records.getAllDerivedDefinitions("PredicateOperand");
1251
1252 // Find some SDNode.
1253 assert(!SDNodes.empty() && "No SDNodes parsed?");
1254 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1255
1256 for (unsigned i = 0, e = PredOps.size(); i != e; ++i) {
1257 DagInit *AlwaysInfo = PredOps[i]->getValueAsDag("ExecuteAlways");
1258
1259 // Clone the AlwaysInfo dag node, changing the operator from 'ops' to
1260 // SomeSDnode so that we can parse this.
1261 std::vector<std::pair<Init*, std::string> > Ops;
1262 for (unsigned op = 0, e = AlwaysInfo->getNumArgs(); op != e; ++op)
1263 Ops.push_back(std::make_pair(AlwaysInfo->getArg(op),
1264 AlwaysInfo->getArgName(op)));
1265 DagInit *DI = new DagInit(SomeSDNode, Ops);
1266
1267 // Create a TreePattern to parse this.
1268 TreePattern P(PredOps[i], DI, false, *this);
1269 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1270
1271 // Copy the operands over into a DAGPredicateOperand.
1272 DAGPredicateOperand PredOpInfo;
1273
1274 TreePatternNode *T = P.getTree(0);
1275 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1276 TreePatternNode *TPN = T->getChild(op);
1277 while (TPN->ApplyTypeConstraints(P, false))
1278 /* Resolve all types */;
1279
1280 if (TPN->ContainsUnresolvedType())
1281 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1282 PredOps[i]->getName() + "' doesn't have a concrete type!";
1283
1284 PredOpInfo.AlwaysOps.push_back(TPN);
1285 }
1286
1287 // Insert it into the PredicateOperands map so we can find it later.
1288 PredicateOperands[PredOps[i]] = PredOpInfo;
1289 }
1290}
1291
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001292/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001293/// instruction input. Return true if this is a real use.
1294static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001295 std::map<std::string, TreePatternNode*> &InstInputs,
1296 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001297 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001298 if (Pat->getName().empty()) {
1299 if (Pat->isLeaf()) {
1300 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1301 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1302 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001303 else if (DI && DI->getDef()->isSubClassOf("Register"))
1304 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001305 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001306 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001307 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001308
1309 Record *Rec;
1310 if (Pat->isLeaf()) {
1311 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1312 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1313 Rec = DI->getDef();
1314 } else {
1315 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1316 Rec = Pat->getOperator();
1317 }
1318
Evan Cheng01f318b2005-12-14 02:21:57 +00001319 // SRCVALUE nodes are ignored.
1320 if (Rec->getName() == "srcvalue")
1321 return false;
1322
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001323 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1324 if (!Slot) {
1325 Slot = Pat;
1326 } else {
1327 Record *SlotRec;
1328 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001329 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001330 } else {
1331 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1332 SlotRec = Slot->getOperator();
1333 }
1334
1335 // Ensure that the inputs agree if we've already seen this input.
1336 if (Rec != SlotRec)
1337 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001338 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001339 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1340 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001341 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001342}
1343
1344/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1345/// part of "I", the instruction), computing the set of inputs and outputs of
1346/// the pattern. Report errors if we see anything naughty.
1347void DAGISelEmitter::
1348FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1349 std::map<std::string, TreePatternNode*> &InstInputs,
Chris Lattner947604b2006-03-24 21:52:20 +00001350 std::map<std::string, TreePatternNode*>&InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001351 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001352 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001353 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001354 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001355 if (!isUse && Pat->getTransformFn())
1356 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001357 return;
1358 } else if (Pat->getOperator()->getName() != "set") {
1359 // If this is not a set, verify that the children nodes are not void typed,
1360 // and recurse.
1361 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001362 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001363 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001364 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001365 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001366 }
1367
1368 // If this is a non-leaf node with no children, treat it basically as if
1369 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001370 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001371 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001372 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001373
Chris Lattnerf1311842005-09-14 23:05:13 +00001374 if (!isUse && Pat->getTransformFn())
1375 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001376 return;
1377 }
1378
1379 // Otherwise, this is a set, validate and collect instruction results.
1380 if (Pat->getNumChildren() == 0)
1381 I->error("set requires operands!");
1382 else if (Pat->getNumChildren() & 1)
1383 I->error("set requires an even number of operands");
1384
Chris Lattnerf1311842005-09-14 23:05:13 +00001385 if (Pat->getTransformFn())
1386 I->error("Cannot specify a transform function on a set node!");
1387
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001388 // Check the set destinations.
1389 unsigned NumValues = Pat->getNumChildren()/2;
1390 for (unsigned i = 0; i != NumValues; ++i) {
1391 TreePatternNode *Dest = Pat->getChild(i);
1392 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001393 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001394
1395 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1396 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001397 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001398
Chris Lattner646085d2006-11-14 21:18:40 +00001399 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1400 Val->getDef()->getName() == "ptr_rc") {
Evan Chengbcecf332005-12-17 01:19:28 +00001401 if (Dest->getName().empty())
1402 I->error("set destination must have a name!");
1403 if (InstResults.count(Dest->getName()))
1404 I->error("cannot set '" + Dest->getName() +"' multiple times");
Evan Cheng420132e2006-03-20 06:04:09 +00001405 InstResults[Dest->getName()] = Dest;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001406 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001407 InstImpResults.push_back(Val->getDef());
1408 } else {
1409 I->error("set destination should be a register!");
1410 }
1411
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001412 // Verify and collect info from the computation.
1413 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001414 InstInputs, InstResults,
1415 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001416 }
1417}
1418
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001419/// ParseInstructions - Parse all of the instructions, inlining and resolving
1420/// any fragments involved. This populates the Instructions list with fully
1421/// resolved instructions.
1422void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001423 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1424
1425 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001426 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001427
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001428 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1429 LI = Instrs[i]->getValueAsListInit("Pattern");
1430
1431 // If there is no pattern, only collect minimal information about the
1432 // instruction for its operand list. We have to assume that there is one
1433 // result, as we have no detailed info.
1434 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001435 std::vector<Record*> Results;
1436 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001437
1438 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001439
Evan Cheng3a217f32005-12-22 02:35:21 +00001440 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001441 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001442 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001443 // These produce no results
1444 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1445 Operands.push_back(InstInfo.OperandList[j].Rec);
1446 } else {
1447 // Assume the first operand is the result.
1448 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001449
Evan Cheng3a217f32005-12-22 02:35:21 +00001450 // The rest are inputs.
1451 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1452 Operands.push_back(InstInfo.OperandList[j].Rec);
1453 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001454 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001455
1456 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001457 std::vector<Record*> ImpResults;
1458 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001459 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001460 DAGInstruction(0, Results, Operands, ImpResults,
1461 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001462 continue; // no pattern.
1463 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001464
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001465 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001466 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001467 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001468 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001469
Chris Lattner95f6b762005-09-08 23:26:30 +00001470 // Infer as many types as possible. If we cannot infer all of them, we can
1471 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001472 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001473 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001474
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001475 // InstInputs - Keep track of all of the inputs of the instruction, along
1476 // with the record they are declared as.
1477 std::map<std::string, TreePatternNode*> InstInputs;
1478
1479 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001480 // in the instruction, including what reg class they are.
Evan Cheng420132e2006-03-20 06:04:09 +00001481 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001482
1483 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001484 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001485
Chris Lattner1f39e292005-09-14 00:09:24 +00001486 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001487 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001488 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1489 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001490 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001491 I->error("Top-level forms in instruction pattern should have"
1492 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001493
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001494 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001495 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001496 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001497 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001498
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001499 // Now that we have inputs and outputs of the pattern, inspect the operands
1500 // list for the instruction. This determines the order that operands are
1501 // added to the machine instruction the node corresponds to.
1502 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001503
1504 // Parse the operands list from the (ops) list, validating it.
1505 std::vector<std::string> &Args = I->getArgList();
1506 assert(Args.empty() && "Args list should still be empty here!");
1507 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1508
1509 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001510 std::vector<Record*> Results;
Evan Cheng420132e2006-03-20 06:04:09 +00001511 TreePatternNode *Res0Node = NULL;
Chris Lattner39e8af92005-09-14 18:19:25 +00001512 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001513 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001514 I->error("'" + InstResults.begin()->first +
1515 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001516 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001517
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001518 // Check that it exists in InstResults.
Evan Cheng420132e2006-03-20 06:04:09 +00001519 TreePatternNode *RNode = InstResults[OpName];
Chris Lattner5c4c7742006-03-25 22:12:44 +00001520 if (RNode == 0)
1521 I->error("Operand $" + OpName + " does not exist in operand list!");
1522
Evan Cheng420132e2006-03-20 06:04:09 +00001523 if (i == 0)
1524 Res0Node = RNode;
1525 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner39e8af92005-09-14 18:19:25 +00001526 if (R == 0)
1527 I->error("Operand $" + OpName + " should be a set destination: all "
1528 "outputs must occur before inputs in operand list!");
1529
1530 if (CGI.OperandList[i].Rec != R)
1531 I->error("Operand $" + OpName + " class mismatch!");
1532
Chris Lattnerae6d8282005-09-15 21:51:12 +00001533 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001534 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001535
Chris Lattner39e8af92005-09-14 18:19:25 +00001536 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001537 InstResults.erase(OpName);
1538 }
1539
Chris Lattner0b592252005-09-14 21:59:34 +00001540 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1541 // the copy while we're checking the inputs.
1542 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001543
1544 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001545 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001546 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001547 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1548 const std::string &OpName = Op.Name;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001549 if (OpName.empty())
1550 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1551
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001552 if (!InstInputsCheck.count(OpName)) {
1553 // If this is an predicate operand with an ExecuteAlways set filled in,
1554 // we can ignore this. When we codegen it, we will do so as always
1555 // executed.
1556 if (Op.Rec->isSubClassOf("PredicateOperand")) {
1557 // Does it have a non-empty ExecuteAlways field? If so, ignore this
1558 // operand.
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001559 if (!getPredicateOperand(Op.Rec).AlwaysOps.empty())
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001560 continue;
1561 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001562 I->error("Operand $" + OpName +
1563 " does not appear in the instruction pattern");
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001564 }
Chris Lattner0b592252005-09-14 21:59:34 +00001565 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001566 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001567
1568 if (InVal->isLeaf() &&
1569 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1570 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001571 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001572 I->error("Operand $" + OpName + "'s register class disagrees"
1573 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001574 }
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001575 Operands.push_back(Op.Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001576
Chris Lattner2175c182005-09-14 23:01:59 +00001577 // Construct the result for the dest-pattern operand list.
1578 TreePatternNode *OpNode = InVal->clone();
1579
1580 // No predicate is useful on the result.
1581 OpNode->setPredicateFn("");
1582
1583 // Promote the xform function to be an explicit node if set.
1584 if (Record *Xform = OpNode->getTransformFn()) {
1585 OpNode->setTransformFn(0);
1586 std::vector<TreePatternNode*> Children;
1587 Children.push_back(OpNode);
1588 OpNode = new TreePatternNode(Xform, Children);
1589 }
1590
1591 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001592 }
1593
Chris Lattner0b592252005-09-14 21:59:34 +00001594 if (!InstInputsCheck.empty())
1595 I->error("Input operand $" + InstInputsCheck.begin()->first +
1596 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001597
1598 TreePatternNode *ResultPattern =
1599 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Evan Cheng420132e2006-03-20 06:04:09 +00001600 // Copy fully inferred output node type to instruction result pattern.
1601 if (NumResults > 0)
1602 ResultPattern->setTypes(Res0Node->getExtTypes());
Chris Lattnera28aec12005-09-15 22:23:50 +00001603
1604 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001605 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001606 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1607
1608 // Use a temporary tree pattern to infer all types and make sure that the
1609 // constructed result is correct. This depends on the instruction already
1610 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001611 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001612 Temp.InferAllTypes();
1613
1614 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1615 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001616
Chris Lattner32707602005-09-08 23:22:48 +00001617 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001618 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001619
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001620 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001621 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1622 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001623 DAGInstruction &TheInst = II->second;
1624 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001625 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001626
Chris Lattner1f39e292005-09-14 00:09:24 +00001627 if (I->getNumTrees() != 1) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00001628 cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
Chris Lattner1f39e292005-09-14 00:09:24 +00001629 continue;
1630 }
1631 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001632 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001633 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001634 if (Pattern->getNumChildren() != 2)
1635 continue; // Not a set of a single value (not handled so far)
1636
1637 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001638 } else{
1639 // Not a set (store or something?)
1640 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001641 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001642
1643 std::string Reason;
1644 if (!SrcPattern->canPatternMatch(Reason, *this))
1645 I->error("Instruction can never match: " + Reason);
1646
Evan Cheng58e84a62005-12-14 22:02:59 +00001647 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001648 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001649 PatternsToMatch.
1650 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
Evan Cheng59413202006-04-19 18:07:24 +00001651 SrcPattern, DstPattern,
Evan Chengc81d2a02006-04-19 20:36:09 +00001652 Instr->getValueAsInt("AddedComplexity")));
Chris Lattner1f39e292005-09-14 00:09:24 +00001653 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001654}
1655
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001656void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001657 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001658
Chris Lattnerabbb6052005-09-15 21:42:00 +00001659 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001660 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001661 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001662
Chris Lattnerabbb6052005-09-15 21:42:00 +00001663 // Inline pattern fragments into it.
1664 Pattern->InlinePatternFragments();
1665
Chris Lattnera3548492006-06-20 00:18:02 +00001666 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1667 if (LI->getSize() == 0) continue; // no pattern.
1668
1669 // Parse the instruction.
1670 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1671
1672 // Inline pattern fragments into it.
1673 Result->InlinePatternFragments();
Chris Lattner09c03392005-11-17 17:43:52 +00001674
Chris Lattnera3548492006-06-20 00:18:02 +00001675 if (Result->getNumTrees() != 1)
1676 Result->error("Cannot handle instructions producing instructions "
1677 "with temporaries yet!");
1678
1679 bool IterateInference;
Chris Lattner186fb7d2006-06-20 00:31:27 +00001680 bool InferredAllPatternTypes, InferredAllResultTypes;
Chris Lattnera3548492006-06-20 00:18:02 +00001681 do {
1682 // Infer as many types as possible. If we cannot infer all of them, we
1683 // can never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001684 InferredAllPatternTypes = Pattern->InferAllTypes();
Chris Lattnera3548492006-06-20 00:18:02 +00001685
Chris Lattner64906972006-09-21 18:28:27 +00001686 // Infer as many types as possible. If we cannot infer all of them, we
1687 // can never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001688 InferredAllResultTypes = Result->InferAllTypes();
1689
Chris Lattnera3548492006-06-20 00:18:02 +00001690 // Apply the type of the result to the source pattern. This helps us
1691 // resolve cases where the input type is known to be a pointer type (which
1692 // is considered resolved), but the result knows it needs to be 32- or
1693 // 64-bits. Infer the other way for good measure.
1694 IterateInference = Pattern->getOnlyTree()->
1695 UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1696 IterateInference |= Result->getOnlyTree()->
1697 UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1698 } while (IterateInference);
Chris Lattner186fb7d2006-06-20 00:31:27 +00001699
1700 // Verify that we inferred enough types that we can do something with the
1701 // pattern and result. If these fire the user has to add type casts.
1702 if (!InferredAllPatternTypes)
1703 Pattern->error("Could not infer all types in pattern!");
1704 if (!InferredAllResultTypes)
1705 Result->error("Could not infer all types in pattern result!");
Chris Lattnera3548492006-06-20 00:18:02 +00001706
Chris Lattner09c03392005-11-17 17:43:52 +00001707 // Validate that the input pattern is correct.
1708 {
1709 std::map<std::string, TreePatternNode*> InstInputs;
Evan Cheng420132e2006-03-20 06:04:09 +00001710 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001711 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001712 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001713 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001714 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001715 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001716 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001717
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001718 // Promote the xform function to be an explicit node if set.
1719 std::vector<TreePatternNode*> ResultNodeOperands;
1720 TreePatternNode *DstPattern = Result->getOnlyTree();
1721 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1722 TreePatternNode *OpNode = DstPattern->getChild(ii);
1723 if (Record *Xform = OpNode->getTransformFn()) {
1724 OpNode->setTransformFn(0);
1725 std::vector<TreePatternNode*> Children;
1726 Children.push_back(OpNode);
1727 OpNode = new TreePatternNode(Xform, Children);
1728 }
1729 ResultNodeOperands.push_back(OpNode);
1730 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00001731 DstPattern = Result->getOnlyTree();
1732 if (!DstPattern->isLeaf())
1733 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1734 ResultNodeOperands);
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001735 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1736 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1737 Temp.InferAllTypes();
1738
Chris Lattnere97603f2005-09-28 19:27:25 +00001739 std::string Reason;
1740 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1741 Pattern->error("Pattern can never match: " + Reason);
1742
Evan Cheng58e84a62005-12-14 22:02:59 +00001743 PatternsToMatch.
1744 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1745 Pattern->getOnlyTree(),
Evan Cheng59413202006-04-19 18:07:24 +00001746 Temp.getOnlyTree(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001747 Patterns[i]->getValueAsInt("AddedComplexity")));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001748 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001749}
1750
Chris Lattnere46e17b2005-09-29 19:28:10 +00001751/// CombineChildVariants - Given a bunch of permutations of each child of the
1752/// 'operator' node, put them together in all possible ways.
1753static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001754 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001755 std::vector<TreePatternNode*> &OutVariants,
1756 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001757 // Make sure that each operand has at least one variant to choose from.
1758 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1759 if (ChildVariants[i].empty())
1760 return;
1761
Chris Lattnere46e17b2005-09-29 19:28:10 +00001762 // The end result is an all-pairs construction of the resultant pattern.
1763 std::vector<unsigned> Idxs;
1764 Idxs.resize(ChildVariants.size());
1765 bool NotDone = true;
1766 while (NotDone) {
1767 // Create the variant and add it to the output list.
1768 std::vector<TreePatternNode*> NewChildren;
1769 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1770 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1771 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1772
1773 // Copy over properties.
1774 R->setName(Orig->getName());
1775 R->setPredicateFn(Orig->getPredicateFn());
1776 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001777 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001778
1779 // If this pattern cannot every match, do not include it as a variant.
1780 std::string ErrString;
1781 if (!R->canPatternMatch(ErrString, ISE)) {
1782 delete R;
1783 } else {
1784 bool AlreadyExists = false;
1785
1786 // Scan to see if this pattern has already been emitted. We can get
1787 // duplication due to things like commuting:
1788 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1789 // which are the same pattern. Ignore the dups.
1790 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1791 if (R->isIsomorphicTo(OutVariants[i])) {
1792 AlreadyExists = true;
1793 break;
1794 }
1795
1796 if (AlreadyExists)
1797 delete R;
1798 else
1799 OutVariants.push_back(R);
1800 }
1801
1802 // Increment indices to the next permutation.
1803 NotDone = false;
1804 // Look for something we can increment without causing a wrap-around.
1805 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1806 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1807 NotDone = true; // Found something to increment.
1808 break;
1809 }
1810 Idxs[IdxsIdx] = 0;
1811 }
1812 }
1813}
1814
Chris Lattneraf302912005-09-29 22:36:54 +00001815/// CombineChildVariants - A helper function for binary operators.
1816///
1817static void CombineChildVariants(TreePatternNode *Orig,
1818 const std::vector<TreePatternNode*> &LHS,
1819 const std::vector<TreePatternNode*> &RHS,
1820 std::vector<TreePatternNode*> &OutVariants,
1821 DAGISelEmitter &ISE) {
1822 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1823 ChildVariants.push_back(LHS);
1824 ChildVariants.push_back(RHS);
1825 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1826}
1827
1828
1829static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1830 std::vector<TreePatternNode *> &Children) {
1831 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1832 Record *Operator = N->getOperator();
1833
1834 // Only permit raw nodes.
1835 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1836 N->getTransformFn()) {
1837 Children.push_back(N);
1838 return;
1839 }
1840
1841 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1842 Children.push_back(N->getChild(0));
1843 else
1844 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1845
1846 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1847 Children.push_back(N->getChild(1));
1848 else
1849 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1850}
1851
Chris Lattnere46e17b2005-09-29 19:28:10 +00001852/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1853/// the (potentially recursive) pattern by using algebraic laws.
1854///
1855static void GenerateVariantsOf(TreePatternNode *N,
1856 std::vector<TreePatternNode*> &OutVariants,
1857 DAGISelEmitter &ISE) {
1858 // We cannot permute leaves.
1859 if (N->isLeaf()) {
1860 OutVariants.push_back(N);
1861 return;
1862 }
1863
1864 // Look up interesting info about the node.
Chris Lattner5a1df382006-03-24 23:10:39 +00001865 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001866
1867 // If this node is associative, reassociate.
Evan Cheng94b30402006-10-11 21:02:01 +00001868 if (NodeInfo.hasProperty(SDNPAssociative)) {
Chris Lattneraf302912005-09-29 22:36:54 +00001869 // Reassociate by pulling together all of the linked operators
1870 std::vector<TreePatternNode*> MaximalChildren;
1871 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1872
1873 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1874 // permutations.
1875 if (MaximalChildren.size() == 3) {
1876 // Find the variants of all of our maximal children.
1877 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1878 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1879 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1880 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1881
1882 // There are only two ways we can permute the tree:
1883 // (A op B) op C and A op (B op C)
1884 // Within these forms, we can also permute A/B/C.
1885
1886 // Generate legal pair permutations of A/B/C.
1887 std::vector<TreePatternNode*> ABVariants;
1888 std::vector<TreePatternNode*> BAVariants;
1889 std::vector<TreePatternNode*> ACVariants;
1890 std::vector<TreePatternNode*> CAVariants;
1891 std::vector<TreePatternNode*> BCVariants;
1892 std::vector<TreePatternNode*> CBVariants;
1893 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1894 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1895 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1896 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1897 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1898 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1899
1900 // Combine those into the result: (x op x) op x
1901 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1902 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1903 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1904 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1905 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1906 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1907
1908 // Combine those into the result: x op (x op x)
1909 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1910 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1911 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1912 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1913 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1914 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1915 return;
1916 }
1917 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001918
1919 // Compute permutations of all children.
1920 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1921 ChildVariants.resize(N->getNumChildren());
1922 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1923 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1924
1925 // Build all permutations based on how the children were formed.
1926 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1927
1928 // If this node is commutative, consider the commuted order.
Evan Cheng94b30402006-10-11 21:02:01 +00001929 if (NodeInfo.hasProperty(SDNPCommutative)) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001930 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattner706d2d32006-08-09 16:44:44 +00001931 // Don't count children which are actually register references.
1932 unsigned NC = 0;
1933 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1934 TreePatternNode *Child = N->getChild(i);
1935 if (Child->isLeaf())
1936 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1937 Record *RR = DI->getDef();
1938 if (RR->isSubClassOf("Register"))
1939 continue;
1940 }
1941 NC++;
1942 }
Chris Lattneraf302912005-09-29 22:36:54 +00001943 // Consider the commuted order.
Chris Lattner706d2d32006-08-09 16:44:44 +00001944 if (NC == 2)
1945 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1946 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001947 }
1948}
1949
1950
Chris Lattnere97603f2005-09-28 19:27:25 +00001951// GenerateVariants - Generate variants. For example, commutative patterns can
1952// match multiple ways. Add them to PatternsToMatch as well.
1953void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001954
Bill Wendlingf5da1332006-12-07 22:21:48 +00001955 DOUT << "Generating instruction variants.\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00001956
1957 // Loop over all of the patterns we've collected, checking to see if we can
1958 // generate variants of the instruction, through the exploitation of
1959 // identities. This permits the target to provide agressive matching without
1960 // the .td file having to contain tons of variants of instructions.
1961 //
1962 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1963 // intentionally do not reconsider these. Any variants of added patterns have
1964 // already been added.
1965 //
1966 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1967 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001968 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001969
1970 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001971 Variants.erase(Variants.begin()); // Remove the original pattern.
1972
1973 if (Variants.empty()) // No variants for this pattern.
1974 continue;
1975
Bill Wendlingf5da1332006-12-07 22:21:48 +00001976 DOUT << "FOUND VARIANTS OF: ";
1977 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
1978 DOUT << "\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00001979
1980 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1981 TreePatternNode *Variant = Variants[v];
1982
Bill Wendlingf5da1332006-12-07 22:21:48 +00001983 DOUT << " VAR#" << v << ": ";
1984 DEBUG(Variant->dump());
1985 DOUT << "\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00001986
1987 // Scan to see if an instruction or explicit pattern already matches this.
1988 bool AlreadyExists = false;
1989 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1990 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001991 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00001992 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00001993 AlreadyExists = true;
1994 break;
1995 }
1996 }
1997 // If we already have it, ignore the variant.
1998 if (AlreadyExists) continue;
1999
2000 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00002001 PatternsToMatch.
2002 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
Evan Cheng59413202006-04-19 18:07:24 +00002003 Variant, PatternsToMatch[i].getDstPattern(),
Evan Chengc81d2a02006-04-19 20:36:09 +00002004 PatternsToMatch[i].getAddedComplexity()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00002005 }
2006
Bill Wendlingf5da1332006-12-07 22:21:48 +00002007 DOUT << "\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00002008 }
Chris Lattnere97603f2005-09-28 19:27:25 +00002009}
2010
Evan Cheng0fc71982005-12-08 02:00:36 +00002011// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
2012// ComplexPattern.
2013static bool NodeIsComplexPattern(TreePatternNode *N)
2014{
2015 return (N->isLeaf() &&
2016 dynamic_cast<DefInit*>(N->getLeafValue()) &&
2017 static_cast<DefInit*>(N->getLeafValue())->getDef()->
2018 isSubClassOf("ComplexPattern"));
2019}
2020
2021// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
2022// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
2023static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
2024 DAGISelEmitter &ISE)
2025{
2026 if (N->isLeaf() &&
2027 dynamic_cast<DefInit*>(N->getLeafValue()) &&
2028 static_cast<DefInit*>(N->getLeafValue())->getDef()->
2029 isSubClassOf("ComplexPattern")) {
2030 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
2031 ->getDef());
2032 }
2033 return NULL;
2034}
2035
Chris Lattner05814af2005-09-28 17:57:56 +00002036/// getPatternSize - Return the 'size' of this pattern. We want to match large
2037/// patterns before small ones. This is used to determine the size of a
2038/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00002039static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng2618d072006-05-17 20:37:59 +00002040 assert((isExtIntegerInVTs(P->getExtTypes()) ||
2041 isExtFloatingPointInVTs(P->getExtTypes()) ||
2042 P->getExtTypeNum(0) == MVT::isVoid ||
2043 P->getExtTypeNum(0) == MVT::Flag ||
2044 P->getExtTypeNum(0) == MVT::iPTR) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +00002045 "Not a valid pattern node to size!");
Evan Cheng6cec34e2006-09-08 07:26:39 +00002046 unsigned Size = 3; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00002047 // If the root node is a ConstantSDNode, increases its size.
2048 // e.g. (set R32:$dst, 0).
2049 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +00002050 Size += 2;
Evan Cheng0fc71982005-12-08 02:00:36 +00002051
2052 // FIXME: This is a hack to statically increase the priority of patterns
2053 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
2054 // Later we can allow complexity / cost for each pattern to be (optionally)
2055 // specified. To get best possible pattern match we'll need to dynamically
2056 // calculate the complexity of all patterns a dag can potentially map to.
2057 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
2058 if (AM)
Evan Cheng6cec34e2006-09-08 07:26:39 +00002059 Size += AM->getNumOperands() * 3;
Chris Lattner3e179802006-02-03 18:06:02 +00002060
2061 // If this node has some predicate function that must match, it adds to the
2062 // complexity of this node.
2063 if (!P->getPredicateFn().empty())
2064 ++Size;
2065
Chris Lattner05814af2005-09-28 17:57:56 +00002066 // Count children in the count if they are also nodes.
2067 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
2068 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00002069 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00002070 Size += getPatternSize(Child, ISE);
2071 else if (Child->isLeaf()) {
2072 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +00002073 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Evan Cheng4a7c2842006-01-06 22:19:44 +00002074 else if (NodeIsComplexPattern(Child))
2075 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00002076 else if (!Child->getPredicateFn().empty())
2077 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00002078 }
Chris Lattner05814af2005-09-28 17:57:56 +00002079 }
2080
2081 return Size;
2082}
2083
2084/// getResultPatternCost - Compute the number of instructions for this pattern.
2085/// This is a temporary hack. We should really include the instruction
2086/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00002087static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00002088 if (P->isLeaf()) return 0;
2089
Evan Chengfbad7082006-02-18 02:33:09 +00002090 unsigned Cost = 0;
2091 Record *Op = P->getOperator();
2092 if (Op->isSubClassOf("Instruction")) {
2093 Cost++;
2094 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
2095 if (II.usesCustomDAGSchedInserter)
2096 Cost += 10;
2097 }
Chris Lattner05814af2005-09-28 17:57:56 +00002098 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00002099 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00002100 return Cost;
2101}
2102
Evan Chenge6f32032006-07-19 00:24:41 +00002103/// getResultPatternCodeSize - Compute the code size of instructions for this
2104/// pattern.
2105static unsigned getResultPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
2106 if (P->isLeaf()) return 0;
2107
2108 unsigned Cost = 0;
2109 Record *Op = P->getOperator();
2110 if (Op->isSubClassOf("Instruction")) {
2111 Cost += Op->getValueAsInt("CodeSize");
2112 }
2113 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2114 Cost += getResultPatternSize(P->getChild(i), ISE);
2115 return Cost;
2116}
2117
Chris Lattner05814af2005-09-28 17:57:56 +00002118// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
2119// In particular, we want to match maximal patterns first and lowest cost within
2120// a particular complexity first.
2121struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00002122 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
2123 DAGISelEmitter &ISE;
2124
Evan Cheng58e84a62005-12-14 22:02:59 +00002125 bool operator()(PatternToMatch *LHS,
2126 PatternToMatch *RHS) {
2127 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
2128 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Evan Chengc81d2a02006-04-19 20:36:09 +00002129 LHSSize += LHS->getAddedComplexity();
2130 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +00002131 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
2132 if (LHSSize < RHSSize) return false;
2133
2134 // If the patterns have equal complexity, compare generated instruction cost
Evan Chenge6f32032006-07-19 00:24:41 +00002135 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), ISE);
2136 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), ISE);
2137 if (LHSCost < RHSCost) return true;
2138 if (LHSCost > RHSCost) return false;
2139
2140 return getResultPatternSize(LHS->getDstPattern(), ISE) <
2141 getResultPatternSize(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00002142 }
2143};
2144
Nate Begeman6510b222005-12-01 04:51:06 +00002145/// getRegisterValueType - Look up and return the first ValueType of specified
2146/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00002147static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00002148 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2149 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00002150 return MVT::Other;
2151}
2152
Chris Lattner72fe91c2005-09-24 00:40:24 +00002153
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002154/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2155/// type information from it.
2156static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00002157 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002158 if (!N->isLeaf())
2159 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2160 RemoveAllTypes(N->getChild(i));
2161}
Chris Lattner72fe91c2005-09-24 00:40:24 +00002162
Chris Lattner0614b622005-11-02 06:49:14 +00002163Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2164 Record *N = Records.getDef(Name);
Chris Lattner5a1df382006-03-24 23:10:39 +00002165 if (!N || !N->isSubClassOf("SDNode")) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00002166 cerr << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner5a1df382006-03-24 23:10:39 +00002167 exit(1);
2168 }
Chris Lattner0614b622005-11-02 06:49:14 +00002169 return N;
2170}
2171
Evan Cheng51fecc82006-01-09 18:27:06 +00002172/// NodeHasProperty - return true if TreePatternNode has the specified
2173/// property.
Evan Cheng94b30402006-10-11 21:02:01 +00002174static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
Evan Cheng51fecc82006-01-09 18:27:06 +00002175 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002176{
Evan Cheng94b30402006-10-11 21:02:01 +00002177 if (N->isLeaf()) {
2178 const ComplexPattern *CP = NodeGetComplexPattern(N, ISE);
2179 if (CP)
2180 return CP->hasProperty(Property);
2181 return false;
2182 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002183 Record *Operator = N->getOperator();
2184 if (!Operator->isSubClassOf("SDNode")) return false;
2185
2186 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00002187 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002188}
2189
Evan Cheng94b30402006-10-11 21:02:01 +00002190static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
Evan Cheng51fecc82006-01-09 18:27:06 +00002191 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002192{
Evan Cheng51fecc82006-01-09 18:27:06 +00002193 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00002194 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00002195
2196 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2197 TreePatternNode *Child = N->getChild(i);
2198 if (PatternHasProperty(Child, Property, ISE))
2199 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002200 }
2201
2202 return false;
2203}
2204
Evan Chengb915f312005-12-09 22:45:35 +00002205class PatternCodeEmitter {
2206private:
2207 DAGISelEmitter &ISE;
2208
Evan Cheng58e84a62005-12-14 22:02:59 +00002209 // Predicates.
2210 ListInit *Predicates;
Evan Cheng59413202006-04-19 18:07:24 +00002211 // Pattern cost.
2212 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +00002213 // Instruction selector pattern.
2214 TreePatternNode *Pattern;
2215 // Matched instruction.
2216 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002217
Evan Chengb915f312005-12-09 22:45:35 +00002218 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00002219 std::map<std::string, std::string> VariableMap;
2220 // Node to operator mapping
2221 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00002222 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002223 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Cheng4326ef52006-10-12 02:08:53 +00002224 // Original input chain(s).
2225 std::vector<std::pair<std::string, std::string> > OrigChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00002226 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +00002227
Evan Cheng676d7312006-08-26 00:59:04 +00002228 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +00002229 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +00002230 /// tested, and if true, the match fails) [when 1], or normal code to emit
2231 /// [when 0], or initialization code to emit [when 2].
2232 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002233 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2234 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +00002235 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +00002236 /// TargetOpcodes - The target specific opcodes used by the resulting
2237 /// instructions.
2238 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +00002239 std::vector<std::string> &TargetVTs;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002240
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002241 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002242 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +00002243 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +00002244 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002245
2246 void emitCheck(const std::string &S) {
2247 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +00002248 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002249 }
2250 void emitCode(const std::string &S) {
2251 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +00002252 GeneratedCode.push_back(std::make_pair(0, S));
2253 }
2254 void emitInit(const std::string &S) {
2255 if (!S.empty())
2256 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002257 }
Evan Chengf5493192006-08-26 01:02:19 +00002258 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002259 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +00002260 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +00002261 }
Evan Chengfceb57a2006-07-15 08:45:20 +00002262 void emitOpcode(const std::string &Opc) {
2263 TargetOpcodes.push_back(Opc);
2264 OpcNo++;
2265 }
Evan Chengf8729402006-07-16 06:12:52 +00002266 void emitVT(const std::string &VT) {
2267 TargetVTs.push_back(VT);
2268 VTNo++;
2269 }
Evan Chengb915f312005-12-09 22:45:35 +00002270public:
Evan Cheng58e84a62005-12-14 22:02:59 +00002271 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2272 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +00002273 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +00002274 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +00002275 std::vector<std::string> &to,
Chris Lattner706d2d32006-08-09 16:44:44 +00002276 std::vector<std::string> &tv)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002277 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +00002278 GeneratedCode(gc), GeneratedDecl(gd),
2279 TargetOpcodes(to), TargetVTs(tv),
Chris Lattner706d2d32006-08-09 16:44:44 +00002280 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00002281
2282 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2283 /// if the match fails. At this point, we already know that the opcode for N
2284 /// matches, and the SDNode for the result has the RootName specified name.
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002285 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2286 const std::string &RootName, const std::string &ChainSuffix,
2287 bool &FoundChain) {
Evan Chenge41bf822006-02-05 06:43:12 +00002288 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00002289 // Emit instruction predicates. Each predicate is just a string for now.
2290 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002291 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00002292 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2293 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2294 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002295 if (!Def->isSubClassOf("Predicate")) {
Jim Laskey16d42c62006-07-11 18:25:13 +00002296#ifndef NDEBUG
2297 Def->dump();
2298#endif
Evan Cheng58e84a62005-12-14 22:02:59 +00002299 assert(0 && "Unknown predicate type!");
2300 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002301 if (!PredicateCheck.empty())
Chris Lattnerbc7fa522006-09-19 00:41:36 +00002302 PredicateCheck += " && ";
Chris Lattner67a202b2006-01-28 20:43:52 +00002303 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00002304 }
2305 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002306
2307 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00002308 }
2309
Evan Chengb915f312005-12-09 22:45:35 +00002310 if (N->isLeaf()) {
2311 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002312 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00002313 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002314 return;
2315 } else if (!NodeIsComplexPattern(N)) {
2316 assert(0 && "Cannot match this as a leaf value!");
2317 abort();
2318 }
2319 }
2320
Chris Lattner488580c2006-01-28 19:06:51 +00002321 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002322 // we already saw this in the pattern, emit code to verify dagness.
2323 if (!N->getName().empty()) {
2324 std::string &VarMapEntry = VariableMap[N->getName()];
2325 if (VarMapEntry.empty()) {
2326 VarMapEntry = RootName;
2327 } else {
2328 // If we get here, this is a second reference to a specific name. Since
2329 // we already have checked that the first reference is valid, we don't
2330 // have to recursively match it, just check that it's the same as the
2331 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002332 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00002333 return;
2334 }
Evan Chengf805c2e2006-01-12 19:35:54 +00002335
2336 if (!N->isLeaf())
2337 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00002338 }
2339
2340
2341 // Emit code to load the child nodes and match their contents recursively.
2342 unsigned OpNo = 0;
Evan Cheng94b30402006-10-11 21:02:01 +00002343 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, ISE);
2344 bool HasChain = PatternHasProperty(N, SDNPHasChain, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00002345 bool EmittedUseCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00002346 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00002347 if (NodeHasChain)
2348 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00002349 if (!isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002350 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002351 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00002352 EmittedUseCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00002353 if (NodeHasChain) {
Evan Chenge41bf822006-02-05 06:43:12 +00002354 // If the immediate use can somehow reach this node through another
2355 // path, then can't fold it either or it will create a cycle.
2356 // e.g. In the following diagram, XX can reach ld through YY. If
2357 // ld is folded into XX, then YY is both a predecessor and a successor
2358 // of XX.
2359 //
2360 // [ld]
2361 // ^ ^
2362 // | |
2363 // / \---
2364 // / [YY]
2365 // | ^
2366 // [XX]-------|
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002367 bool NeedCheck = false;
2368 if (P != Pattern)
2369 NeedCheck = true;
2370 else {
2371 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2372 NeedCheck =
2373 P->getOperator() == ISE.get_intrinsic_void_sdnode() ||
2374 P->getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
2375 P->getOperator() == ISE.get_intrinsic_wo_chain_sdnode() ||
Evan Chengce1381a2006-10-14 08:30:15 +00002376 PInfo.getNumOperands() > 1 ||
Evan Cheng94b30402006-10-11 21:02:01 +00002377 PInfo.hasProperty(SDNPHasChain) ||
2378 PInfo.hasProperty(SDNPInFlag) ||
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002379 PInfo.hasProperty(SDNPOptInFlag);
2380 }
2381
2382 if (NeedCheck) {
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002383 std::string ParentName(RootName.begin(), RootName.end()-1);
Chris Lattner706d2d32006-08-09 16:44:44 +00002384 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
Evan Chengce1381a2006-10-14 08:30:15 +00002385 ".Val, N.Val)");
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002386 }
Evan Chenge41bf822006-02-05 06:43:12 +00002387 }
Evan Chengb915f312005-12-09 22:45:35 +00002388 }
Evan Chenge41bf822006-02-05 06:43:12 +00002389
Evan Chengc15d18c2006-01-27 22:13:45 +00002390 if (NodeHasChain) {
Evan Cheng4326ef52006-10-12 02:08:53 +00002391 if (FoundChain) {
2392 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
2393 "IsChainCompatible(" + ChainName + ".Val, " +
2394 RootName + ".Val))");
2395 OrigChains.push_back(std::make_pair(ChainName, RootName));
2396 } else
Evan Chenge6389932006-07-21 22:19:51 +00002397 FoundChain = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002398 ChainName = "Chain" + ChainSuffix;
Evan Cheng676d7312006-08-26 00:59:04 +00002399 emitInit("SDOperand " + ChainName + " = " + RootName +
Evan Chenge6389932006-07-21 22:19:51 +00002400 ".getOperand(0);");
Evan Cheng1cf6db22006-01-06 00:41:12 +00002401 }
Evan Chengb915f312005-12-09 22:45:35 +00002402 }
2403
Evan Cheng54597732006-01-26 00:22:25 +00002404 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002405 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002406 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002407 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2408 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002409 if (!isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002410 (PatternHasProperty(N, SDNPInFlag, ISE) ||
2411 PatternHasProperty(N, SDNPOptInFlag, ISE) ||
2412 PatternHasProperty(N, SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002413 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002414 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002415 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002416 }
2417 }
2418
Evan Chengd3eea902006-10-09 21:02:17 +00002419 // If there is a node predicate for this, emit the call.
2420 if (!N->getPredicateFn().empty())
2421 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2422
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002423
Chris Lattner39e73f72006-10-11 04:05:55 +00002424 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
2425 // a constant without a predicate fn that has more that one bit set, handle
2426 // this as a special case. This is usually for targets that have special
2427 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
2428 // handling stuff). Using these instructions is often far more efficient
2429 // than materializing the constant. Unfortunately, both the instcombiner
2430 // and the dag combiner can often infer that bits are dead, and thus drop
2431 // them from the mask in the dag. For example, it might turn 'AND X, 255'
2432 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
2433 // to handle this.
2434 if (!N->isLeaf() &&
2435 (N->getOperator()->getName() == "and" ||
2436 N->getOperator()->getName() == "or") &&
2437 N->getChild(1)->isLeaf() &&
2438 N->getChild(1)->getPredicateFn().empty()) {
2439 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
2440 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
2441 emitInit("SDOperand " + RootName + "0" + " = " +
2442 RootName + ".getOperand(" + utostr(0) + ");");
2443 emitInit("SDOperand " + RootName + "1" + " = " +
2444 RootName + ".getOperand(" + utostr(1) + ");");
2445
2446 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
2447 const char *MaskPredicate = N->getOperator()->getName() == "or"
2448 ? "CheckOrMask(" : "CheckAndMask(";
2449 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
2450 RootName + "1), " + itostr(II->getValue()) + ")");
2451
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002452 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
Chris Lattner39e73f72006-10-11 04:05:55 +00002453 ChainSuffix + utostr(0), FoundChain);
2454 return;
2455 }
2456 }
2457 }
2458
Evan Chengb915f312005-12-09 22:45:35 +00002459 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng676d7312006-08-26 00:59:04 +00002460 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002461 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002462
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002463 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002464 ChainSuffix + utostr(OpNo), FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002465 }
2466
Evan Cheng676d7312006-08-26 00:59:04 +00002467 // Handle cases when root is a complex pattern.
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002468 const ComplexPattern *CP;
Evan Cheng676d7312006-08-26 00:59:04 +00002469 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2470 std::string Fn = CP->getSelectFunc();
2471 unsigned NumOps = CP->getNumOperands();
2472 for (unsigned i = 0; i < NumOps; ++i) {
2473 emitDecl("CPTmp" + utostr(i));
2474 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2475 }
Evan Cheng94b30402006-10-11 21:02:01 +00002476 if (CP->hasProperty(SDNPHasChain)) {
2477 emitDecl("CPInChain");
2478 emitDecl("Chain" + ChainSuffix);
2479 emitCode("SDOperand CPInChain;");
2480 emitCode("SDOperand Chain" + ChainSuffix + ";");
2481 }
Evan Cheng676d7312006-08-26 00:59:04 +00002482
Evan Cheng811731e2006-11-08 20:31:10 +00002483 std::string Code = Fn + "(" + RootName + ", " + RootName;
Evan Cheng676d7312006-08-26 00:59:04 +00002484 for (unsigned i = 0; i < NumOps; i++)
2485 Code += ", CPTmp" + utostr(i);
Evan Cheng94b30402006-10-11 21:02:01 +00002486 if (CP->hasProperty(SDNPHasChain)) {
2487 ChainName = "Chain" + ChainSuffix;
2488 Code += ", CPInChain, Chain" + ChainSuffix;
2489 }
Evan Cheng676d7312006-08-26 00:59:04 +00002490 emitCheck(Code + ")");
2491 }
Evan Chengb915f312005-12-09 22:45:35 +00002492 }
Chris Lattner39e73f72006-10-11 04:05:55 +00002493
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002494 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
2495 const std::string &RootName,
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002496 const std::string &ChainSuffix, bool &FoundChain) {
2497 if (!Child->isLeaf()) {
2498 // If it's not a leaf, recursively match.
2499 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2500 emitCheck(RootName + ".getOpcode() == " +
2501 CInfo.getEnumName());
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002502 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
Evan Cheng94b30402006-10-11 21:02:01 +00002503 if (NodeHasProperty(Child, SDNPHasChain, ISE))
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002504 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
2505 } else {
2506 // If this child has a name associated with it, capture it in VarMap. If
2507 // we already saw this in the pattern, emit code to verify dagness.
2508 if (!Child->getName().empty()) {
2509 std::string &VarMapEntry = VariableMap[Child->getName()];
2510 if (VarMapEntry.empty()) {
2511 VarMapEntry = RootName;
2512 } else {
2513 // If we get here, this is a second reference to a specific name.
2514 // Since we already have checked that the first reference is valid,
2515 // we don't have to recursively match it, just check that it's the
2516 // same as the previously named thing.
2517 emitCheck(VarMapEntry + " == " + RootName);
2518 Duplicates.insert(RootName);
2519 return;
2520 }
2521 }
2522
2523 // Handle leaves of various types.
2524 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2525 Record *LeafRec = DI->getDef();
Chris Lattner646085d2006-11-14 21:18:40 +00002526 if (LeafRec->isSubClassOf("RegisterClass") ||
2527 LeafRec->getName() == "ptr_rc") {
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002528 // Handle register references. Nothing to do here.
2529 } else if (LeafRec->isSubClassOf("Register")) {
2530 // Handle register references.
2531 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2532 // Handle complex pattern.
2533 const ComplexPattern *CP = NodeGetComplexPattern(Child, ISE);
2534 std::string Fn = CP->getSelectFunc();
2535 unsigned NumOps = CP->getNumOperands();
2536 for (unsigned i = 0; i < NumOps; ++i) {
2537 emitDecl("CPTmp" + utostr(i));
2538 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2539 }
Evan Cheng94b30402006-10-11 21:02:01 +00002540 if (CP->hasProperty(SDNPHasChain)) {
2541 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(Parent->getOperator());
2542 FoldedChains.push_back(std::make_pair("CPInChain",
2543 PInfo.getNumResults()));
2544 ChainName = "Chain" + ChainSuffix;
2545 emitDecl("CPInChain");
2546 emitDecl(ChainName);
2547 emitCode("SDOperand CPInChain;");
2548 emitCode("SDOperand " + ChainName + ";");
2549 }
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002550
Evan Cheng811731e2006-11-08 20:31:10 +00002551 std::string Code = Fn + "(N, ";
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002552 if (CP->hasProperty(SDNPHasChain)) {
2553 std::string ParentName(RootName.begin(), RootName.end()-1);
Evan Cheng811731e2006-11-08 20:31:10 +00002554 Code += ParentName + ", ";
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002555 }
2556 Code += RootName;
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002557 for (unsigned i = 0; i < NumOps; i++)
2558 Code += ", CPTmp" + utostr(i);
Evan Cheng94b30402006-10-11 21:02:01 +00002559 if (CP->hasProperty(SDNPHasChain))
2560 Code += ", CPInChain, Chain" + ChainSuffix;
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002561 emitCheck(Code + ")");
2562 } else if (LeafRec->getName() == "srcvalue") {
2563 // Place holder for SRCVALUE nodes. Nothing to do here.
2564 } else if (LeafRec->isSubClassOf("ValueType")) {
2565 // Make sure this is the specified value type.
2566 emitCheck("cast<VTSDNode>(" + RootName +
2567 ")->getVT() == MVT::" + LeafRec->getName());
2568 } else if (LeafRec->isSubClassOf("CondCode")) {
2569 // Make sure this is the specified cond code.
2570 emitCheck("cast<CondCodeSDNode>(" + RootName +
2571 ")->get() == ISD::" + LeafRec->getName());
2572 } else {
2573#ifndef NDEBUG
2574 Child->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00002575 cerr << " ";
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002576#endif
2577 assert(0 && "Unknown leaf type!");
2578 }
2579
2580 // If there is a node predicate for this, emit the call.
2581 if (!Child->getPredicateFn().empty())
2582 emitCheck(Child->getPredicateFn() + "(" + RootName +
2583 ".Val)");
2584 } else if (IntInit *II =
2585 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2586 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
2587 unsigned CTmp = TmpNo++;
2588 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2589 RootName + ")->getSignExtended();");
2590
2591 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2592 } else {
2593#ifndef NDEBUG
2594 Child->dump();
2595#endif
2596 assert(0 && "Unknown leaf type!");
2597 }
2598 }
2599 }
Evan Chengb915f312005-12-09 22:45:35 +00002600
2601 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2602 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +00002603 std::vector<std::string>
2604 EmitResultCode(TreePatternNode *N, bool RetSelected,
2605 bool InFlagDecled, bool ResNodeDecled,
2606 bool LikeLeaf = false, bool isRoot = false) {
2607 // List of arguments of getTargetNode() or SelectNodeTo().
2608 std::vector<std::string> NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002609 // This is something selected from the pattern we matched.
2610 if (!N->getName().empty()) {
Evan Chengb915f312005-12-09 22:45:35 +00002611 std::string &Val = VariableMap[N->getName()];
2612 assert(!Val.empty() &&
2613 "Variable referenced but not defined and not caught earlier!");
2614 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2615 // Already selected this operand, just return the tmpval.
Evan Cheng676d7312006-08-26 00:59:04 +00002616 NodeOps.push_back(Val);
2617 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002618 }
2619
2620 const ComplexPattern *CP;
2621 unsigned ResNo = TmpNo++;
Evan Chengb915f312005-12-09 22:45:35 +00002622 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002623 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002624 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002625 switch (N->getTypeNum(0)) {
Chris Lattnerd8a17282007-01-17 07:45:12 +00002626 default:
2627 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
2628 << " type as an immediate constant. Aborting\n";
2629 abort();
Chris Lattner78593132006-01-29 20:01:35 +00002630 case MVT::i1: CastType = "bool"; break;
2631 case MVT::i8: CastType = "unsigned char"; break;
2632 case MVT::i16: CastType = "unsigned short"; break;
2633 case MVT::i32: CastType = "unsigned"; break;
2634 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002635 }
Evan Cheng676d7312006-08-26 00:59:04 +00002636 emitCode("SDOperand Tmp" + utostr(ResNo) +
Evan Chengfceb57a2006-07-15 08:45:20 +00002637 " = CurDAG->getTargetConstant(((" + CastType +
2638 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2639 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002640 NodeOps.push_back("Tmp" + utostr(ResNo));
2641 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2642 // value if used multiple times by this pattern result.
2643 Val = "Tmp"+utostr(ResNo);
Evan Chengbb48e332006-01-12 07:54:57 +00002644 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002645 Record *Op = OperatorMap[N->getName()];
2646 // Transform ExternalSymbol to TargetExternalSymbol
2647 if (Op && Op->getName() == "externalsym") {
Evan Cheng676d7312006-08-26 00:59:04 +00002648 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002649 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002650 Val + ")->getSymbol(), " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002651 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002652 NodeOps.push_back("Tmp" + utostr(ResNo));
Chris Lattner64906972006-09-21 18:28:27 +00002653 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2654 // this value if used multiple times by this pattern result.
Evan Cheng676d7312006-08-26 00:59:04 +00002655 Val = "Tmp"+utostr(ResNo);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002656 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002657 NodeOps.push_back(Val);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002658 }
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00002659 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
2660 || N->getOperator()->getName() == "tglobaltlsaddr")) {
Evan Chengf805c2e2006-01-12 19:35:54 +00002661 Record *Op = OperatorMap[N->getName()];
2662 // Transform GlobalAddress to TargetGlobalAddress
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00002663 if (Op && (Op->getName() == "globaladdr" ||
2664 Op->getName() == "globaltlsaddr")) {
Evan Cheng676d7312006-08-26 00:59:04 +00002665 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002666 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
Evan Cheng2618d072006-05-17 20:37:59 +00002667 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002668 ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002669 NodeOps.push_back("Tmp" + utostr(ResNo));
Chris Lattner64906972006-09-21 18:28:27 +00002670 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2671 // this value if used multiple times by this pattern result.
Evan Cheng676d7312006-08-26 00:59:04 +00002672 Val = "Tmp"+utostr(ResNo);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002673 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002674 NodeOps.push_back(Val);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002675 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002676 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng676d7312006-08-26 00:59:04 +00002677 NodeOps.push_back(Val);
2678 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2679 // value if used multiple times by this pattern result.
2680 Val = "Tmp"+utostr(ResNo);
Evan Chengbb48e332006-01-12 07:54:57 +00002681 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng676d7312006-08-26 00:59:04 +00002682 NodeOps.push_back(Val);
2683 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2684 // value if used multiple times by this pattern result.
2685 Val = "Tmp"+utostr(ResNo);
Evan Chengb915f312005-12-09 22:45:35 +00002686 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
Evan Cheng676d7312006-08-26 00:59:04 +00002687 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
2688 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
2689 NodeOps.push_back("CPTmp" + utostr(i));
Evan Chengb0793f92006-05-25 00:21:44 +00002690 }
Evan Chengb915f312005-12-09 22:45:35 +00002691 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002692 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
Evan Cheng863bf5a2006-03-20 22:53:06 +00002693 // node even if it isn't one. Don't select it.
Evan Cheng676d7312006-08-26 00:59:04 +00002694 if (!LikeLeaf) {
2695 emitCode("AddToISelQueue(" + Val + ");");
Chris Lattner706d2d32006-08-09 16:44:44 +00002696 if (isRoot && N->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +00002697 emitCode("ReplaceUses(N, " + Val + ");");
Evan Cheng06d64702006-08-11 08:59:35 +00002698 emitCode("return NULL;");
Chris Lattner706d2d32006-08-09 16:44:44 +00002699 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00002700 }
Evan Cheng676d7312006-08-26 00:59:04 +00002701 NodeOps.push_back(Val);
Evan Chengb915f312005-12-09 22:45:35 +00002702 }
Evan Cheng676d7312006-08-26 00:59:04 +00002703 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002704 }
Evan Chengb915f312005-12-09 22:45:35 +00002705 if (N->isLeaf()) {
2706 // If this is an explicit register reference, handle it.
2707 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2708 unsigned ResNo = TmpNo++;
2709 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng676d7312006-08-26 00:59:04 +00002710 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002711 ISE.getQualifiedName(DI->getDef()) + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002712 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002713 NodeOps.push_back("Tmp" + utostr(ResNo));
2714 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002715 }
2716 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2717 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002718 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng676d7312006-08-26 00:59:04 +00002719 emitCode("SDOperand Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002720 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
Evan Cheng2618d072006-05-17 20:37:59 +00002721 ", " + getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002722 NodeOps.push_back("Tmp" + utostr(ResNo));
2723 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002724 }
2725
Jim Laskey16d42c62006-07-11 18:25:13 +00002726#ifndef NDEBUG
2727 N->dump();
2728#endif
Evan Chengb915f312005-12-09 22:45:35 +00002729 assert(0 && "Unknown leaf type!");
Evan Cheng676d7312006-08-26 00:59:04 +00002730 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002731 }
2732
2733 Record *Op = N->getOperator();
2734 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002735 const CodeGenTarget &CGT = ISE.getTargetInfo();
2736 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002737 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng045953c2006-05-10 00:05:46 +00002738 TreePattern *InstPat = Inst.getPattern();
2739 TreePatternNode *InstPatNode =
2740 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2741 : (InstPat ? InstPat->getOnlyTree() : NULL);
2742 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2743 InstPatNode = InstPatNode->getChild(1);
2744 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002745 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
Evan Cheng045953c2006-05-10 00:05:46 +00002746 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2747 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2748 bool NodeHasOptInFlag = isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002749 PatternHasProperty(Pattern, SDNPOptInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002750 bool NodeHasInFlag = isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002751 PatternHasProperty(Pattern, SDNPInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002752 bool NodeHasOutFlag = HasImpResults || (isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002753 PatternHasProperty(Pattern, SDNPOutFlag, ISE));
Evan Cheng045953c2006-05-10 00:05:46 +00002754 bool NodeHasChain = InstPatNode &&
Evan Cheng94b30402006-10-11 21:02:01 +00002755 PatternHasProperty(InstPatNode, SDNPHasChain, ISE);
Evan Cheng3eff89b2006-05-10 02:47:57 +00002756 bool InputHasChain = isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002757 NodeHasProperty(Pattern, SDNPHasChain, ISE);
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002758 unsigned NumResults = Inst.getNumResults();
Evan Cheng4fba2812005-12-20 07:37:41 +00002759
Evan Chengfceb57a2006-07-15 08:45:20 +00002760 if (NodeHasOptInFlag) {
Evan Cheng676d7312006-08-26 00:59:04 +00002761 emitCode("bool HasInFlag = "
Evan Chengf8729402006-07-16 06:12:52 +00002762 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
Evan Chengfceb57a2006-07-15 08:45:20 +00002763 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002764 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +00002765 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
Evan Cheng4fba2812005-12-20 07:37:41 +00002766
Evan Cheng823b7522006-01-19 21:57:10 +00002767 // How many results is this pattern expected to produce?
Evan Chenged66e852006-03-09 08:19:11 +00002768 unsigned PatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +00002769 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2770 MVT::ValueType VT = Pattern->getTypeNum(i);
2771 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Chenged66e852006-03-09 08:19:11 +00002772 PatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +00002773 }
2774
Evan Cheng4326ef52006-10-12 02:08:53 +00002775 if (OrigChains.size() > 0) {
2776 // The original input chain is being ignored. If it is not just
2777 // pointing to the op that's being folded, we should create a
2778 // TokenFactor with it and the chain of the folded op as the new chain.
2779 // We could potentially be doing multiple levels of folding, in that
2780 // case, the TokenFactor can have more operands.
2781 emitCode("SmallVector<SDOperand, 8> InChains;");
2782 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
2783 emitCode("if (" + OrigChains[i].first + ".Val != " +
2784 OrigChains[i].second + ".Val) {");
2785 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
2786 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
2787 emitCode("}");
2788 }
2789 emitCode("AddToISelQueue(" + ChainName + ");");
2790 emitCode("InChains.push_back(" + ChainName + ");");
2791 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
2792 "&InChains[0], InChains.size());");
2793 }
2794
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002795 // Loop over all of the operands of the instruction pattern, emitting code
2796 // to fill them all in. The node 'N' usually has number children equal to
2797 // the number of input operands of the instruction. However, in cases
2798 // where there are predicate operands for an instruction, we need to fill
2799 // in the 'execute always' values. Match up the node operands to the
2800 // instruction operands to do this.
Evan Cheng676d7312006-08-26 00:59:04 +00002801 std::vector<std::string> AllOps;
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002802 for (unsigned ChildNo = 0, InstOpNo = NumResults;
2803 InstOpNo != II.OperandList.size(); ++InstOpNo) {
2804 std::vector<std::string> Ops;
2805
Evan Cheng59039632007-05-08 21:04:07 +00002806 // If this is a normal operand or a predicate operand without
2807 // 'execute always', emit it.
2808 Record *OperandNode = II.OperandList[InstOpNo].Rec;
2809 if (!OperandNode->isSubClassOf("PredicateOperand") ||
2810 ISE.getPredicateOperand(OperandNode).AlwaysOps.empty()) {
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002811 Ops = EmitResultCode(N->getChild(ChildNo), RetSelected,
2812 InFlagDecled, ResNodeDecled);
2813 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
2814 ++ChildNo;
2815 } else {
2816 // Otherwise, this is a predicate operand, emit the 'execute always'
2817 // operands.
2818 const DAGPredicateOperand &Pred =
2819 ISE.getPredicateOperand(II.OperandList[InstOpNo].Rec);
2820 for (unsigned i = 0, e = Pred.AlwaysOps.size(); i != e; ++i) {
2821 Ops = EmitResultCode(Pred.AlwaysOps[i], RetSelected,
2822 InFlagDecled, ResNodeDecled);
2823 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
2824 }
2825 }
Evan Chengb915f312005-12-09 22:45:35 +00002826 }
2827
Evan Chengb915f312005-12-09 22:45:35 +00002828 // Emit all the chain and CopyToReg stuff.
Evan Cheng045953c2006-05-10 00:05:46 +00002829 bool ChainEmitted = NodeHasChain;
2830 if (NodeHasChain)
Evan Cheng676d7312006-08-26 00:59:04 +00002831 emitCode("AddToISelQueue(" + ChainName + ");");
Evan Chengbc6b86a2006-06-14 19:27:50 +00002832 if (NodeHasInFlag || HasImpInputs)
Evan Cheng676d7312006-08-26 00:59:04 +00002833 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
2834 InFlagDecled, ResNodeDecled, true);
Evan Chengf037ca62006-08-27 08:11:28 +00002835 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
Evan Cheng676d7312006-08-26 00:59:04 +00002836 if (!InFlagDecled) {
2837 emitCode("SDOperand InFlag(0, 0);");
2838 InFlagDecled = true;
2839 }
Evan Chengf037ca62006-08-27 08:11:28 +00002840 if (NodeHasOptInFlag) {
2841 emitCode("if (HasInFlag) {");
2842 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
2843 emitCode(" AddToISelQueue(InFlag);");
2844 emitCode("}");
2845 }
Evan Chengbc6b86a2006-06-14 19:27:50 +00002846 }
Evan Chengb915f312005-12-09 22:45:35 +00002847
Evan Chengb915f312005-12-09 22:45:35 +00002848 unsigned ResNo = TmpNo++;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002849 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2850 NodeHasOptInFlag) {
Evan Chenge945f4d2006-06-14 22:22:20 +00002851 std::string Code;
2852 std::string Code2;
2853 std::string NodeName;
2854 if (!isRoot) {
2855 NodeName = "Tmp" + utostr(ResNo);
Evan Cheng676d7312006-08-26 00:59:04 +00002856 Code2 = "SDOperand " + NodeName + " = SDOperand(";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002857 } else {
Evan Chenge945f4d2006-06-14 22:22:20 +00002858 NodeName = "ResNode";
Lauro Ramos Venancio195c6c22007-04-26 17:03:22 +00002859 if (!ResNodeDecled) {
Evan Cheng676d7312006-08-26 00:59:04 +00002860 Code2 = "SDNode *" + NodeName + " = ";
Lauro Ramos Venancio195c6c22007-04-26 17:03:22 +00002861 ResNodeDecled = true;
2862 } else
Evan Cheng676d7312006-08-26 00:59:04 +00002863 Code2 = NodeName + " = ";
Evan Chengbcecf332005-12-17 01:19:28 +00002864 }
Evan Chengf037ca62006-08-27 08:11:28 +00002865
Evan Chengfceb57a2006-07-15 08:45:20 +00002866 Code = "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
Evan Chengf037ca62006-08-27 08:11:28 +00002867 unsigned OpsNo = OpcNo;
Evan Chengfceb57a2006-07-15 08:45:20 +00002868 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
Evan Chenge945f4d2006-06-14 22:22:20 +00002869
2870 // Output order: results, chain, flags
2871 // Result types.
Evan Chengf8729402006-07-16 06:12:52 +00002872 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
2873 Code += ", VT" + utostr(VTNo);
2874 emitVT(getEnumName(N->getTypeNum(0)));
2875 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002876 if (NodeHasChain)
2877 Code += ", MVT::Other";
2878 if (NodeHasOutFlag)
2879 Code += ", MVT::Flag";
2880
Chris Lattner7c3a96b2006-11-14 18:41:38 +00002881 // Figure out how many fixed inputs the node has. This is important to
2882 // know which inputs are the variable ones if present.
2883 unsigned NumInputs = AllOps.size();
2884 NumInputs += NodeHasChain;
2885
Evan Chenge945f4d2006-06-14 22:22:20 +00002886 // Inputs.
Evan Chengf037ca62006-08-27 08:11:28 +00002887 if (HasVarOps) {
2888 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
2889 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
2890 AllOps.clear();
Evan Chenge945f4d2006-06-14 22:22:20 +00002891 }
2892
2893 if (HasVarOps) {
Chris Lattner7c3a96b2006-11-14 18:41:38 +00002894 // Figure out whether any operands at the end of the op list are not
2895 // part of the variable section.
2896 std::string EndAdjust;
Evan Chenge945f4d2006-06-14 22:22:20 +00002897 if (NodeHasInFlag || HasImpInputs)
Chris Lattner7c3a96b2006-11-14 18:41:38 +00002898 EndAdjust = "-1"; // Always has one flag.
2899 else if (NodeHasOptInFlag)
2900 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
2901
2902 emitCode("for (unsigned i = " + utostr(NumInputs) +
2903 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
2904
Evan Cheng676d7312006-08-26 00:59:04 +00002905 emitCode(" AddToISelQueue(N.getOperand(i));");
Evan Chengf037ca62006-08-27 08:11:28 +00002906 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
Evan Chenge945f4d2006-06-14 22:22:20 +00002907 emitCode("}");
2908 }
2909
2910 if (NodeHasChain) {
2911 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +00002912 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
Evan Chenge945f4d2006-06-14 22:22:20 +00002913 else
Evan Chengf037ca62006-08-27 08:11:28 +00002914 AllOps.push_back(ChainName);
Evan Chenge945f4d2006-06-14 22:22:20 +00002915 }
2916
Evan Chengf037ca62006-08-27 08:11:28 +00002917 if (HasVarOps) {
2918 if (NodeHasInFlag || HasImpInputs)
2919 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2920 else if (NodeHasOptInFlag) {
2921 emitCode("if (HasInFlag)");
2922 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2923 }
2924 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
2925 ".size()";
2926 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2927 AllOps.push_back("InFlag");
Evan Chenge945f4d2006-06-14 22:22:20 +00002928
Evan Chengf037ca62006-08-27 08:11:28 +00002929 unsigned NumOps = AllOps.size();
2930 if (NumOps) {
2931 if (!NodeHasOptInFlag && NumOps < 4) {
2932 for (unsigned i = 0; i != NumOps; ++i)
2933 Code += ", " + AllOps[i];
2934 } else {
2935 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
2936 for (unsigned i = 0; i != NumOps; ++i) {
2937 OpsCode += AllOps[i];
2938 if (i != NumOps-1)
2939 OpsCode += ", ";
2940 }
2941 emitCode(OpsCode + " };");
2942 Code += ", Ops" + utostr(OpsNo) + ", ";
2943 if (NodeHasOptInFlag) {
2944 Code += "HasInFlag ? ";
2945 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
2946 } else
2947 Code += utostr(NumOps);
2948 }
2949 }
2950
Evan Chenge945f4d2006-06-14 22:22:20 +00002951 if (!isRoot)
2952 Code += "), 0";
2953 emitCode(Code2 + Code + ");");
2954
2955 if (NodeHasChain)
2956 // Remember which op produces the chain.
2957 if (!isRoot)
2958 emitCode(ChainName + " = SDOperand(" + NodeName +
2959 ".Val, " + utostr(PatResults) + ");");
2960 else
2961 emitCode(ChainName + " = SDOperand(" + NodeName +
2962 ", " + utostr(PatResults) + ");");
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002963
Evan Cheng676d7312006-08-26 00:59:04 +00002964 if (!isRoot) {
2965 NodeOps.push_back("Tmp" + utostr(ResNo));
2966 return NodeOps;
2967 }
Evan Cheng045953c2006-05-10 00:05:46 +00002968
Evan Cheng06d64702006-08-11 08:59:35 +00002969 bool NeedReplace = false;
Evan Cheng676d7312006-08-26 00:59:04 +00002970 if (NodeHasOutFlag) {
2971 if (!InFlagDecled) {
2972 emitCode("SDOperand InFlag = SDOperand(ResNode, " +
2973 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2974 InFlagDecled = true;
2975 } else
2976 emitCode("InFlag = SDOperand(ResNode, " +
2977 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2978 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002979
Evan Cheng676d7312006-08-26 00:59:04 +00002980 if (HasImpResults && EmitCopyFromRegs(N, ResNodeDecled, ChainEmitted)) {
Chris Lattner706d2d32006-08-09 16:44:44 +00002981 emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));");
Evan Chenged66e852006-03-09 08:19:11 +00002982 NumResults = 1;
Evan Cheng97938882005-12-22 02:24:50 +00002983 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002984
Evan Cheng97938882005-12-22 02:24:50 +00002985 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002986 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002987 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Chris Lattner706d2d32006-08-09 16:44:44 +00002988 emitCode("ReplaceUses(SDOperand(" +
Evan Cheng67212a02006-02-09 22:12:27 +00002989 FoldedChains[j].first + ".Val, " +
Chris Lattner706d2d32006-08-09 16:44:44 +00002990 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
2991 utostr(NumResults) + "));");
Evan Cheng06d64702006-08-11 08:59:35 +00002992 NeedReplace = true;
Evan Chengb915f312005-12-09 22:45:35 +00002993 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002994
Evan Cheng06d64702006-08-11 08:59:35 +00002995 if (NodeHasOutFlag) {
Chris Lattner706d2d32006-08-09 16:44:44 +00002996 emitCode("ReplaceUses(SDOperand(N.Val, " +
2997 utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);");
Evan Cheng06d64702006-08-11 08:59:35 +00002998 NeedReplace = true;
2999 }
3000
3001 if (NeedReplace) {
3002 for (unsigned i = 0; i < NumResults; i++)
3003 emitCode("ReplaceUses(SDOperand(N.Val, " +
3004 utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));");
3005 if (InputHasChain)
3006 emitCode("ReplaceUses(SDOperand(N.Val, " +
Chris Lattner64906972006-09-21 18:28:27 +00003007 utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, "
3008 + ChainName + ".ResNo" + "));");
Evan Chengf037ca62006-08-27 08:11:28 +00003009 } else
Evan Cheng06d64702006-08-11 08:59:35 +00003010 RetSelected = true;
Evan Cheng97938882005-12-22 02:24:50 +00003011
Evan Chenged66e852006-03-09 08:19:11 +00003012 // User does not expect the instruction would produce a chain!
Evan Cheng06d64702006-08-11 08:59:35 +00003013 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
Evan Cheng9ade2182006-08-26 05:34:46 +00003014 ;
Evan Cheng3eff89b2006-05-10 02:47:57 +00003015 } else if (InputHasChain && !NodeHasChain) {
3016 // One of the inner node produces a chain.
Evan Cheng9ade2182006-08-26 05:34:46 +00003017 if (NodeHasOutFlag)
Evan Cheng06d64702006-08-11 08:59:35 +00003018 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults+1) +
3019 "), SDOperand(ResNode, N.ResNo-1));");
Evan Cheng06d64702006-08-11 08:59:35 +00003020 for (unsigned i = 0; i < PatResults; ++i)
3021 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(i) +
3022 "), SDOperand(ResNode, " + utostr(i) + "));");
3023 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults) +
3024 "), " + ChainName + ");");
3025 RetSelected = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00003026 }
Evan Cheng06d64702006-08-11 08:59:35 +00003027
3028 if (RetSelected)
Evan Cheng9ade2182006-08-26 05:34:46 +00003029 emitCode("return ResNode;");
Evan Cheng06d64702006-08-11 08:59:35 +00003030 else
3031 emitCode("return NULL;");
Evan Chengb915f312005-12-09 22:45:35 +00003032 } else {
Evan Cheng9ade2182006-08-26 05:34:46 +00003033 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
Evan Chengfceb57a2006-07-15 08:45:20 +00003034 utostr(OpcNo);
Nate Begemanb73628b2005-12-30 00:12:56 +00003035 if (N->getTypeNum(0) != MVT::isVoid)
Evan Chengf8729402006-07-16 06:12:52 +00003036 Code += ", VT" + utostr(VTNo);
Evan Cheng54597732006-01-26 00:22:25 +00003037 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00003038 Code += ", MVT::Flag";
Evan Chengf037ca62006-08-27 08:11:28 +00003039
3040 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
3041 AllOps.push_back("InFlag");
3042
3043 unsigned NumOps = AllOps.size();
3044 if (NumOps) {
3045 if (!NodeHasOptInFlag && NumOps < 4) {
3046 for (unsigned i = 0; i != NumOps; ++i)
3047 Code += ", " + AllOps[i];
3048 } else {
3049 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
3050 for (unsigned i = 0; i != NumOps; ++i) {
3051 OpsCode += AllOps[i];
3052 if (i != NumOps-1)
3053 OpsCode += ", ";
3054 }
3055 emitCode(OpsCode + " };");
3056 Code += ", Ops" + utostr(OpcNo) + ", ";
3057 Code += utostr(NumOps);
3058 }
3059 }
Evan Cheng95514ba2006-08-26 08:00:10 +00003060 emitCode(Code + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00003061 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
3062 if (N->getTypeNum(0) != MVT::isVoid)
3063 emitVT(getEnumName(N->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00003064 }
Evan Cheng4fba2812005-12-20 07:37:41 +00003065
Evan Cheng676d7312006-08-26 00:59:04 +00003066 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00003067 } else if (Op->isSubClassOf("SDNodeXForm")) {
3068 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng863bf5a2006-03-20 22:53:06 +00003069 // PatLeaf node - the operand may or may not be a leaf node. But it should
3070 // behave like one.
Evan Cheng676d7312006-08-26 00:59:04 +00003071 std::vector<std::string> Ops =
3072 EmitResultCode(N->getChild(0), RetSelected, InFlagDecled,
3073 ResNodeDecled, true);
Evan Chengb915f312005-12-09 22:45:35 +00003074 unsigned ResNo = TmpNo++;
Evan Cheng676d7312006-08-26 00:59:04 +00003075 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
3076 + "(" + Ops.back() + ".Val);");
3077 NodeOps.push_back("Tmp" + utostr(ResNo));
Evan Cheng9ade2182006-08-26 05:34:46 +00003078 if (isRoot)
3079 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00003080 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00003081 } else {
3082 N->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00003083 cerr << "\n";
Chris Lattner7893f132006-01-11 01:33:49 +00003084 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00003085 }
3086 }
3087
Chris Lattner488580c2006-01-28 19:06:51 +00003088 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
3089 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00003090 /// 'Pat' may be missing types. If we find an unresolved type to add a check
3091 /// for, this returns true otherwise false if Pat has all types.
3092 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +00003093 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00003094 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +00003095 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +00003096 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00003097 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +00003098 // The top level node type is checked outside of the select function.
3099 if (!isRoot)
3100 emitCheck(Prefix + ".Val->getValueType(0) == " +
3101 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00003102 return true;
Evan Chengb915f312005-12-09 22:45:35 +00003103 }
3104
Evan Cheng51fecc82006-01-09 18:27:06 +00003105 unsigned OpNo =
Evan Cheng94b30402006-10-11 21:02:01 +00003106 (unsigned) NodeHasProperty(Pat, SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00003107 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
3108 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
3109 Prefix + utostr(OpNo)))
3110 return true;
3111 return false;
3112 }
3113
3114private:
Evan Cheng54597732006-01-26 00:22:25 +00003115 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00003116 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00003117 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +00003118 bool &ChainEmitted, bool &InFlagDecled,
3119 bool &ResNodeDecled, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00003120 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00003121 unsigned OpNo =
Evan Cheng94b30402006-10-11 21:02:01 +00003122 (unsigned) NodeHasProperty(N, SDNPHasChain, ISE);
3123 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00003124 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
3125 TreePatternNode *Child = N->getChild(i);
3126 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +00003127 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
3128 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +00003129 } else {
3130 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00003131 if (!Child->getName().empty()) {
3132 std::string Name = RootName + utostr(OpNo);
3133 if (Duplicates.find(Name) != Duplicates.end())
3134 // A duplicate! Do not emit a copy for this node.
3135 continue;
3136 }
3137
Evan Chengb915f312005-12-09 22:45:35 +00003138 Record *RR = DI->getDef();
3139 if (RR->isSubClassOf("Register")) {
3140 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00003141 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +00003142 if (!InFlagDecled) {
3143 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
3144 InFlagDecled = true;
3145 } else
3146 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
3147 emitCode("AddToISelQueue(InFlag);");
Evan Chengb2c6d492006-01-11 22:16:13 +00003148 } else {
3149 if (!ChainEmitted) {
Evan Cheng676d7312006-08-26 00:59:04 +00003150 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00003151 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00003152 ChainEmitted = true;
3153 }
Evan Cheng676d7312006-08-26 00:59:04 +00003154 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
3155 if (!InFlagDecled) {
3156 emitCode("SDOperand InFlag(0, 0);");
3157 InFlagDecled = true;
3158 }
3159 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
3160 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Cheng7a33db02006-08-26 07:39:28 +00003161 ", " + ISE.getQualifiedName(RR) +
3162 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00003163 ResNodeDecled = true;
Evan Cheng67212a02006-02-09 22:12:27 +00003164 emitCode(ChainName + " = SDOperand(ResNode, 0);");
3165 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00003166 }
3167 }
3168 }
3169 }
3170 }
Evan Cheng54597732006-01-26 00:22:25 +00003171
Evan Cheng676d7312006-08-26 00:59:04 +00003172 if (HasInFlag) {
3173 if (!InFlagDecled) {
3174 emitCode("SDOperand InFlag = " + RootName +
3175 ".getOperand(" + utostr(OpNo) + ");");
3176 InFlagDecled = true;
3177 } else
3178 emitCode("InFlag = " + RootName +
3179 ".getOperand(" + utostr(OpNo) + ");");
3180 emitCode("AddToISelQueue(InFlag);");
3181 }
Evan Chengb915f312005-12-09 22:45:35 +00003182 }
Evan Cheng4fba2812005-12-20 07:37:41 +00003183
3184 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00003185 /// as specified by the instruction. It returns true if any copy is
3186 /// emitted.
Evan Cheng676d7312006-08-26 00:59:04 +00003187 bool EmitCopyFromRegs(TreePatternNode *N, bool &ResNodeDecled,
3188 bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00003189 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00003190 Record *Op = N->getOperator();
3191 if (Op->isSubClassOf("Instruction")) {
3192 const DAGInstruction &Inst = ISE.getInstruction(Op);
3193 const CodeGenTarget &CGT = ISE.getTargetInfo();
Evan Cheng4fba2812005-12-20 07:37:41 +00003194 unsigned NumImpResults = Inst.getNumImpResults();
3195 for (unsigned i = 0; i < NumImpResults; i++) {
3196 Record *RR = Inst.getImpResult(i);
3197 if (RR->isSubClassOf("Register")) {
3198 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
3199 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00003200 if (!ChainEmitted) {
Evan Cheng676d7312006-08-26 00:59:04 +00003201 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00003202 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00003203 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00003204 }
Evan Cheng676d7312006-08-26 00:59:04 +00003205 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
3206 emitCode(Decl + "ResNode = CurDAG->getCopyFromReg(" + ChainName +
Evan Chengfceb57a2006-07-15 08:45:20 +00003207 ", " + ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
Evan Chengd7805a72006-02-09 07:16:09 +00003208 ", InFlag).Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00003209 ResNodeDecled = true;
Evan Chengd7805a72006-02-09 07:16:09 +00003210 emitCode(ChainName + " = SDOperand(ResNode, 1);");
3211 emitCode("InFlag = SDOperand(ResNode, 2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00003212 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00003213 }
3214 }
3215 }
3216 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00003217 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00003218 }
Evan Chengb915f312005-12-09 22:45:35 +00003219};
3220
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00003221/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
3222/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00003223/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00003224void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00003225 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00003226 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00003227 std::vector<std::string> &TargetOpcodes,
Evan Chengf5493192006-08-26 01:02:19 +00003228 std::vector<std::string> &TargetVTs) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003229 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
3230 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00003231 GeneratedCode, GeneratedDecl,
Chris Lattner706d2d32006-08-09 16:44:44 +00003232 TargetOpcodes, TargetVTs);
Evan Chengb915f312005-12-09 22:45:35 +00003233
Chris Lattner8fc35682005-09-23 23:16:51 +00003234 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00003235 bool FoundChain = false;
Evan Cheng13e9e9c2006-10-16 06:33:44 +00003236 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00003237
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003238 // TP - Get *SOME* tree pattern, we don't care which.
3239 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00003240
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003241 // At this point, we know that we structurally match the pattern, but the
3242 // types of the nodes may not match. Figure out the fewest number of type
3243 // comparisons we need to emit. For example, if there is only one integer
3244 // type supported by a target, there should be no type comparisons at all for
3245 // integer patterns!
3246 //
3247 // To figure out the fewest number of type checks needed, clone the pattern,
3248 // remove the types, then perform type inference on the pattern as a whole.
3249 // If there are unresolved types, emit an explicit check for those types,
3250 // apply the type to the tree, then rerun type inference. Iterate until all
3251 // types are resolved.
3252 //
Evan Cheng58e84a62005-12-14 22:02:59 +00003253 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003254 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00003255
3256 do {
3257 // Resolve/propagate as many types as possible.
3258 try {
3259 bool MadeChange = true;
3260 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00003261 MadeChange = Pat->ApplyTypeConstraints(TP,
3262 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00003263 } catch (...) {
3264 assert(0 && "Error: could not find consistent types for something we"
3265 " already decided was ok!");
3266 abort();
3267 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003268
Chris Lattner7e82f132005-10-15 21:34:21 +00003269 // Insert a check for an unresolved type and add it to the tree. If we find
3270 // an unresolved type to add a check for, this returns true and we iterate,
3271 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00003272 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00003273
Evan Cheng676d7312006-08-26 00:59:04 +00003274 Emitter.EmitResultCode(Pattern.getDstPattern(),
3275 false, false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003276 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00003277}
3278
Chris Lattner24e00a42006-01-29 04:41:05 +00003279/// EraseCodeLine - Erase one code line from all of the patterns. If removing
3280/// a line causes any of them to be empty, remove them and return true when
3281/// done.
3282static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00003283 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00003284 &Patterns) {
3285 bool ErasedPatterns = false;
3286 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3287 Patterns[i].second.pop_back();
3288 if (Patterns[i].second.empty()) {
3289 Patterns.erase(Patterns.begin()+i);
3290 --i; --e;
3291 ErasedPatterns = true;
3292 }
3293 }
3294 return ErasedPatterns;
3295}
3296
Chris Lattner8bc74722006-01-29 04:25:26 +00003297/// EmitPatterns - Emit code for at least one pattern, but try to group common
3298/// code together between the patterns.
3299void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00003300 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00003301 &Patterns, unsigned Indent,
3302 std::ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00003303 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00003304 typedef std::vector<CodeLine> CodeList;
3305 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3306
3307 if (Patterns.empty()) return;
3308
Chris Lattner24e00a42006-01-29 04:41:05 +00003309 // Figure out how many patterns share the next code line. Explicitly copy
3310 // FirstCodeLine so that we don't invalidate a reference when changing
3311 // Patterns.
3312 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00003313 unsigned LastMatch = Patterns.size()-1;
3314 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3315 --LastMatch;
3316
3317 // If not all patterns share this line, split the list into two pieces. The
3318 // first chunk will use this line, the second chunk won't.
3319 if (LastMatch != 0) {
3320 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3321 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3322
3323 // FIXME: Emit braces?
3324 if (Shared.size() == 1) {
3325 PatternToMatch &Pattern = *Shared.back().first;
3326 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3327 Pattern.getSrcPattern()->print(OS);
3328 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3329 Pattern.getDstPattern()->print(OS);
3330 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003331 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003332 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003333 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003334 << " cost = "
Evan Chenge6f32032006-07-19 00:24:41 +00003335 << getResultPatternCost(Pattern.getDstPattern(), *this)
3336 << " size = "
3337 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003338 }
Evan Cheng676d7312006-08-26 00:59:04 +00003339 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00003340 OS << std::string(Indent, ' ') << "{\n";
3341 Indent += 2;
3342 }
3343 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00003344 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00003345 Indent -= 2;
3346 OS << std::string(Indent, ' ') << "}\n";
3347 }
3348
3349 if (Other.size() == 1) {
3350 PatternToMatch &Pattern = *Other.back().first;
3351 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3352 Pattern.getSrcPattern()->print(OS);
3353 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3354 Pattern.getDstPattern()->print(OS);
3355 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003356 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003357 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003358 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003359 << " cost = "
Chris Lattner706d2d32006-08-09 16:44:44 +00003360 << getResultPatternCost(Pattern.getDstPattern(), *this)
3361 << " size = "
3362 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003363 }
3364 EmitPatterns(Other, Indent, OS);
3365 return;
3366 }
3367
Chris Lattner24e00a42006-01-29 04:41:05 +00003368 // Remove this code from all of the patterns that share it.
3369 bool ErasedPatterns = EraseCodeLine(Patterns);
3370
Evan Cheng676d7312006-08-26 00:59:04 +00003371 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00003372
3373 // Otherwise, every pattern in the list has this line. Emit it.
3374 if (!isPredicate) {
3375 // Normal code.
3376 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3377 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00003378 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3379
3380 // If the next code line is another predicate, and if all of the pattern
3381 // in this group share the same next line, emit it inline now. Do this
3382 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00003383 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Chris Lattner24e00a42006-01-29 04:41:05 +00003384 // Check that all of fhe patterns in Patterns end with the same predicate.
3385 bool AllEndWithSamePredicate = true;
3386 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3387 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3388 AllEndWithSamePredicate = false;
3389 break;
3390 }
3391 // If all of the predicates aren't the same, we can't share them.
3392 if (!AllEndWithSamePredicate) break;
3393
3394 // Otherwise we can. Emit it shared now.
3395 OS << " &&\n" << std::string(Indent+4, ' ')
3396 << Patterns.back().second.back().second;
3397 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00003398 }
Chris Lattner24e00a42006-01-29 04:41:05 +00003399
3400 OS << ") {\n";
3401 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00003402 }
3403
3404 EmitPatterns(Patterns, Indent, OS);
3405
3406 if (isPredicate)
3407 OS << std::string(Indent-2, ' ') << "}\n";
3408}
3409
Evan Cheng892aaf82006-11-08 23:01:03 +00003410static std::string getOpcodeName(Record *Op, DAGISelEmitter &ISE) {
3411 const SDNodeInfo &OpcodeInfo = ISE.getSDNodeInfo(Op);
3412 return OpcodeInfo.getEnumName();
3413}
Chris Lattner8bc74722006-01-29 04:25:26 +00003414
Evan Cheng892aaf82006-11-08 23:01:03 +00003415static std::string getLegalCName(std::string OpName) {
3416 std::string::size_type pos = OpName.find("::");
3417 if (pos != std::string::npos)
3418 OpName.replace(pos, 2, "_");
3419 return OpName;
Chris Lattner37481472005-09-26 21:59:35 +00003420}
3421
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003422void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerf7560ed2006-11-20 18:54:33 +00003423 // Get the namespace to insert instructions into. Make sure not to pick up
3424 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
3425 // instruction or something.
3426 std::string InstNS;
3427 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
3428 e = Target.inst_end(); i != e; ++i) {
3429 InstNS = i->second.Namespace;
3430 if (InstNS != "TargetInstrInfo")
3431 break;
3432 }
3433
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003434 if (!InstNS.empty()) InstNS += "::";
3435
Chris Lattner602f6922006-01-04 00:25:00 +00003436 // Group the patterns by their top-level opcodes.
Evan Cheng892aaf82006-11-08 23:01:03 +00003437 std::map<std::string, std::vector<PatternToMatch*> > PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00003438 // All unique target node emission functions.
3439 std::map<std::string, unsigned> EmitFunctions;
Chris Lattner602f6922006-01-04 00:25:00 +00003440 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3441 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3442 if (!Node->isLeaf()) {
Evan Cheng892aaf82006-11-08 23:01:03 +00003443 PatternsByOpcode[getOpcodeName(Node->getOperator(), *this)].
3444 push_back(&PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003445 } else {
3446 const ComplexPattern *CP;
Chris Lattner9c5d4de2006-11-03 01:11:05 +00003447 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Evan Cheng892aaf82006-11-08 23:01:03 +00003448 PatternsByOpcode[getOpcodeName(getSDNodeNamed("imm"), *this)].
3449 push_back(&PatternsToMatch[i]);
Reid Spencer63fd6ad2006-11-02 21:07:40 +00003450 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
Chris Lattner602f6922006-01-04 00:25:00 +00003451 std::vector<Record*> OpNodes = CP->getRootNodes();
3452 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Evan Cheng892aaf82006-11-08 23:01:03 +00003453 PatternsByOpcode[getOpcodeName(OpNodes[j], *this)]
3454 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], *this)].begin(),
3455 &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003456 }
3457 } else {
Bill Wendlingf5da1332006-12-07 22:21:48 +00003458 cerr << "Unrecognized opcode '";
Chris Lattner602f6922006-01-04 00:25:00 +00003459 Node->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00003460 cerr << "' on tree pattern '";
3461 cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3462 cerr << "'!\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003463 exit(1);
3464 }
3465 }
3466 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003467
3468 // For each opcode, there might be multiple select functions, one per
3469 // ValueType of the node (or its first operand if it doesn't produce a
3470 // non-chain result.
3471 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
3472
Chris Lattner602f6922006-01-04 00:25:00 +00003473 // Emit one Select_* method for each top-level opcode. We do this instead of
3474 // emitting one giant switch statement to support compilers where this will
3475 // result in the recursive functions taking less stack space.
Evan Cheng892aaf82006-11-08 23:01:03 +00003476 for (std::map<std::string, std::vector<PatternToMatch*> >::iterator
3477 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
3478 PBOI != E; ++PBOI) {
3479 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00003480 std::vector<PatternToMatch*> &PatternsOfOp = PBOI->second;
3481 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
3482
Chris Lattner602f6922006-01-04 00:25:00 +00003483 // We want to emit all of the matching code now. However, we want to emit
3484 // the matches in order of minimal cost. Sort the patterns so the least
3485 // cost one is at the start.
Chris Lattner706d2d32006-08-09 16:44:44 +00003486 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
Chris Lattner602f6922006-01-04 00:25:00 +00003487 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00003488
Chris Lattner706d2d32006-08-09 16:44:44 +00003489 // Split them into groups by type.
3490 std::map<MVT::ValueType, std::vector<PatternToMatch*> > PatternsByType;
3491 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
3492 PatternToMatch *Pat = PatternsOfOp[i];
3493 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner706d2d32006-08-09 16:44:44 +00003494 MVT::ValueType VT = SrcPat->getTypeNum(0);
3495 std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator TI =
3496 PatternsByType.find(VT);
3497 if (TI != PatternsByType.end())
3498 TI->second.push_back(Pat);
3499 else {
3500 std::vector<PatternToMatch*> PVec;
3501 PVec.push_back(Pat);
3502 PatternsByType.insert(std::make_pair(VT, PVec));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003503 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003504 }
3505
3506 for (std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator
3507 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
3508 ++II) {
3509 MVT::ValueType OpVT = II->first;
3510 std::vector<PatternToMatch*> &Patterns = II->second;
Chris Lattner64906972006-09-21 18:28:27 +00003511 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
3512 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00003513
3514 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3515 std::vector<std::vector<std::string> > PatternOpcodes;
3516 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00003517 std::vector<std::set<std::string> > PatternDecls;
Chris Lattner706d2d32006-08-09 16:44:44 +00003518 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3519 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00003520 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00003521 std::vector<std::string> TargetOpcodes;
3522 std::vector<std::string> TargetVTs;
3523 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3524 TargetOpcodes, TargetVTs);
Chris Lattner706d2d32006-08-09 16:44:44 +00003525 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3526 PatternDecls.push_back(GeneratedDecl);
3527 PatternOpcodes.push_back(TargetOpcodes);
3528 PatternVTs.push_back(TargetVTs);
3529 }
3530
3531 // Scan the code to see if all of the patterns are reachable and if it is
3532 // possible that the last one might not match.
3533 bool mightNotMatch = true;
3534 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3535 CodeList &GeneratedCode = CodeForPatterns[i].second;
3536 mightNotMatch = false;
3537
3538 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
Evan Cheng676d7312006-08-26 00:59:04 +00003539 if (GeneratedCode[j].first == 1) { // predicate.
Chris Lattner706d2d32006-08-09 16:44:44 +00003540 mightNotMatch = true;
3541 break;
3542 }
3543 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003544
Chris Lattner706d2d32006-08-09 16:44:44 +00003545 // If this pattern definitely matches, and if it isn't the last one, the
3546 // patterns after it CANNOT ever match. Error out.
3547 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00003548 cerr << "Pattern '";
3549 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
3550 cerr << "' is impossible to select!\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003551 exit(1);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003552 }
3553 }
3554
Chris Lattner706d2d32006-08-09 16:44:44 +00003555 // Factor target node emission code (emitted by EmitResultCode) into
3556 // separate functions. Uniquing and share them among all instruction
3557 // selection routines.
3558 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3559 CodeList &GeneratedCode = CodeForPatterns[i].second;
3560 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
3561 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00003562 std::set<std::string> Decls = PatternDecls[i];
Evan Cheng676d7312006-08-26 00:59:04 +00003563 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00003564 int CodeSize = (int)GeneratedCode.size();
3565 int LastPred = -1;
3566 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00003567 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00003568 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00003569 else if (LastPred != -1 && GeneratedCode[j].first == 2)
3570 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00003571 }
3572
Evan Cheng9ade2182006-08-26 05:34:46 +00003573 std::string CalleeCode = "(const SDOperand &N";
3574 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00003575 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3576 CalleeCode += ", unsigned Opc" + utostr(j);
3577 CallerCode += ", " + TargetOpcodes[j];
3578 }
3579 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
3580 CalleeCode += ", MVT::ValueType VT" + utostr(j);
3581 CallerCode += ", " + TargetVTs[j];
3582 }
Evan Chengf5493192006-08-26 01:02:19 +00003583 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00003584 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00003585 std::string Name = *I;
Evan Cheng676d7312006-08-26 00:59:04 +00003586 CalleeCode += ", SDOperand &" + Name;
3587 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00003588 }
3589 CallerCode += ");";
3590 CalleeCode += ") ";
3591 // Prevent emission routines from being inlined to reduce selection
3592 // routines stack frame sizes.
Chris Lattner8dc728e2006-08-27 13:16:24 +00003593 CalleeCode += "DISABLE_INLINE ";
Evan Cheng676d7312006-08-26 00:59:04 +00003594 CalleeCode += "{\n";
3595
3596 for (std::vector<std::string>::const_reverse_iterator
3597 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
3598 CalleeCode += " " + *I + "\n";
3599
Evan Chengf5493192006-08-26 01:02:19 +00003600 for (int j = LastPred+1; j < CodeSize; ++j)
3601 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003602 for (int j = LastPred+1; j < CodeSize; ++j)
3603 GeneratedCode.pop_back();
3604 CalleeCode += "}\n";
3605
3606 // Uniquing the emission routines.
3607 unsigned EmitFuncNum;
3608 std::map<std::string, unsigned>::iterator EFI =
3609 EmitFunctions.find(CalleeCode);
3610 if (EFI != EmitFunctions.end()) {
3611 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003612 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00003613 EmitFuncNum = EmitFunctions.size();
3614 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Evan Cheng06d64702006-08-11 08:59:35 +00003615 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003616 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003617
Chris Lattner706d2d32006-08-09 16:44:44 +00003618 // Replace the emission code within selection routines with calls to the
3619 // emission functions.
Evan Cheng06d64702006-08-11 08:59:35 +00003620 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
Chris Lattner706d2d32006-08-09 16:44:44 +00003621 GeneratedCode.push_back(std::make_pair(false, CallerCode));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003622 }
3623
Chris Lattner706d2d32006-08-09 16:44:44 +00003624 // Print function.
Chris Lattnerab51ddd2006-11-14 21:32:01 +00003625 std::string OpVTStr;
Chris Lattner33a40042006-11-14 22:17:10 +00003626 if (OpVT == MVT::iPTR) {
3627 OpVTStr = "_iPTR";
3628 } else if (OpVT == MVT::isVoid) {
3629 // Nodes with a void result actually have a first result type of either
3630 // Other (a chain) or Flag. Since there is no one-to-one mapping from
3631 // void to this case, we handle it specially here.
3632 } else {
3633 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
3634 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003635 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3636 OpcodeVTMap.find(OpName);
3637 if (OpVTI == OpcodeVTMap.end()) {
3638 std::vector<std::string> VTSet;
3639 VTSet.push_back(OpVTStr);
3640 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
3641 } else
3642 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003643
Evan Cheng892aaf82006-11-08 23:01:03 +00003644 OS << "SDNode *Select_" << getLegalCName(OpName)
Chris Lattner33a40042006-11-14 22:17:10 +00003645 << OpVTStr << "(const SDOperand &N) {\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003646
Chris Lattner706d2d32006-08-09 16:44:44 +00003647 // Loop through and reverse all of the CodeList vectors, as we will be
3648 // accessing them from their logical front, but accessing the end of a
3649 // vector is more efficient.
3650 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3651 CodeList &GeneratedCode = CodeForPatterns[i].second;
3652 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003653 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003654
3655 // Next, reverse the list of patterns itself for the same reason.
3656 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3657
3658 // Emit all of the patterns now, grouped together to share code.
3659 EmitPatterns(CodeForPatterns, 2, OS);
3660
Chris Lattner64906972006-09-21 18:28:27 +00003661 // If the last pattern has predicates (which could fail) emit code to
3662 // catch the case where nothing handles a pattern.
Chris Lattner706d2d32006-08-09 16:44:44 +00003663 if (mightNotMatch) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00003664 OS << " cerr << \"Cannot yet select: \";\n";
Evan Cheng892aaf82006-11-08 23:01:03 +00003665 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
3666 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
3667 OpName != "ISD::INTRINSIC_VOID") {
Chris Lattner706d2d32006-08-09 16:44:44 +00003668 OS << " N.Val->dump(CurDAG);\n";
3669 } else {
3670 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3671 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00003672 << " cerr << \"intrinsic %\"<< "
Chris Lattner706d2d32006-08-09 16:44:44 +00003673 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3674 }
Bill Wendlingf5da1332006-12-07 22:21:48 +00003675 OS << " cerr << '\\n';\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003676 << " abort();\n"
3677 << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003678 }
3679 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003680 }
Chris Lattner602f6922006-01-04 00:25:00 +00003681 }
3682
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003683 // Emit boilerplate.
Evan Cheng9ade2182006-08-26 05:34:46 +00003684 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003685 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Evan Cheng0db427b2006-11-01 00:27:59 +00003686 << " AddToISelQueue(N.getOperand(0)); // Select the chain.\n\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003687 << " // Select the flag operand.\n"
3688 << " if (Ops.back().getValueType() == MVT::Flag)\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003689 << " AddToISelQueue(Ops.back());\n"
Chris Lattnerfd105d42006-02-24 02:13:31 +00003690 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003691 << " std::vector<MVT::ValueType> VTs;\n"
3692 << " VTs.push_back(MVT::Other);\n"
3693 << " VTs.push_back(MVT::Flag);\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00003694 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
3695 "Ops.size());\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00003696 << " return New.Val;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003697 << "}\n\n";
3698
Jim Laskeya683f9b2007-01-26 17:29:20 +00003699 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
3700 << " SDOperand Chain = N.getOperand(0);\n"
3701 << " SDOperand N1 = N.getOperand(1);\n"
Jim Laskey844b8922007-01-26 23:00:54 +00003702 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
3703 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00003704 << " AddToISelQueue(Chain);\n"
3705 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
Jim Laskey844b8922007-01-26 23:00:54 +00003706 << " MVT::Other, Tmp, Chain);\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00003707 << "}\n\n";
3708
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003709 OS << "// The main instruction selector code.\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00003710 << "SDNode *SelectCode(SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003711 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003712 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003713 << "INSTRUCTION_LIST_END)) {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003714 << " return NULL; // Already selected.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003715 << " }\n\n"
Evan Cheng892aaf82006-11-08 23:01:03 +00003716 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003717 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003718 << " default: break;\n"
3719 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003720 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003721 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003722 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003723 << " case ISD::TargetConstant:\n"
3724 << " case ISD::TargetConstantPool:\n"
3725 << " case ISD::TargetFrameIndex:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00003726 << " case ISD::TargetJumpTable:\n"
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00003727 << " case ISD::TargetGlobalTLSAddress:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003728 << " case ISD::TargetGlobalAddress: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003729 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003730 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003731 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003732 << " case ISD::AssertZext: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003733 << " AddToISelQueue(N.getOperand(0));\n"
3734 << " ReplaceUses(N, N.getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003735 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003736 << " }\n"
3737 << " case ISD::TokenFactor:\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00003738 << " case ISD::CopyFromReg:\n"
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003739 << " case ISD::CopyToReg: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003740 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
3741 << " AddToISelQueue(N.getOperand(i));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003742 << " return NULL;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003743 << " }\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00003744 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
3745 << " case ISD::LABEL: return Select_LABEL(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003746
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003747
Chris Lattner602f6922006-01-04 00:25:00 +00003748 // Loop over all of the case statements, emiting a call to each method we
3749 // emitted above.
Evan Cheng892aaf82006-11-08 23:01:03 +00003750 for (std::map<std::string, std::vector<PatternToMatch*> >::iterator
3751 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
3752 PBOI != E; ++PBOI) {
3753 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00003754 // Potentially multiple versions of select for this opcode. One for each
3755 // ValueType of the node (or its first true operand if it doesn't produce a
3756 // result.
3757 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3758 OpcodeVTMap.find(OpName);
3759 std::vector<std::string> &OpVTs = OpVTI->second;
Evan Cheng892aaf82006-11-08 23:01:03 +00003760 OS << " case " << OpName << ": {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003761 if (OpVTs.size() == 1) {
3762 std::string &VTStr = OpVTs[0];
Evan Cheng892aaf82006-11-08 23:01:03 +00003763 OS << " return Select_" << getLegalCName(OpName)
Chris Lattner33a40042006-11-14 22:17:10 +00003764 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003765 } else {
Chris Lattner717a6112006-11-14 21:50:27 +00003766 // Keep track of whether we see a pattern that has an iPtr result.
3767 bool HasPtrPattern = false;
Chris Lattner33a40042006-11-14 22:17:10 +00003768 bool HasDefaultPattern = false;
Chris Lattner717a6112006-11-14 21:50:27 +00003769
Evan Cheng06d64702006-08-11 08:59:35 +00003770 OS << " switch (NVT) {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003771 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
3772 std::string &VTStr = OpVTs[i];
Chris Lattner33a40042006-11-14 22:17:10 +00003773 if (VTStr.empty()) {
3774 HasDefaultPattern = true;
3775 continue;
3776 }
Chris Lattner717a6112006-11-14 21:50:27 +00003777
3778 // If this is a match on iPTR: don't emit it directly, we need special
3779 // code.
Chris Lattner33a40042006-11-14 22:17:10 +00003780 if (VTStr == "_iPTR") {
Chris Lattner717a6112006-11-14 21:50:27 +00003781 HasPtrPattern = true;
3782 continue;
3783 }
Chris Lattner33a40042006-11-14 22:17:10 +00003784 OS << " case MVT::" << VTStr.substr(1) << ":\n"
Evan Cheng892aaf82006-11-08 23:01:03 +00003785 << " return Select_" << getLegalCName(OpName)
Chris Lattner33a40042006-11-14 22:17:10 +00003786 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003787 }
Evan Cheng06d64702006-08-11 08:59:35 +00003788 OS << " default:\n";
Chris Lattner717a6112006-11-14 21:50:27 +00003789
3790 // If there is an iPTR result version of this pattern, emit it here.
3791 if (HasPtrPattern) {
3792 OS << " if (NVT == TLI.getPointerTy())\n";
3793 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
3794 }
Chris Lattner33a40042006-11-14 22:17:10 +00003795 if (HasDefaultPattern) {
3796 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
3797 }
Chris Lattner0d1bb132006-11-14 21:41:35 +00003798 OS << " break;\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003799 OS << " }\n";
3800 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003801 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003802 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00003803 }
Chris Lattner81303322005-09-23 19:36:15 +00003804
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003805 OS << " } // end of big switch.\n\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00003806 << " cerr << \"Cannot yet select: \";\n"
Chris Lattnerb026e702006-03-28 00:41:33 +00003807 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3808 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3809 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003810 << " N.Val->dump(CurDAG);\n"
3811 << " } else {\n"
3812 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3813 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00003814 << " cerr << \"intrinsic %\"<< "
3815 "Intrinsic::getName((Intrinsic::ID)iid);\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003816 << " }\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00003817 << " cerr << '\\n';\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003818 << " abort();\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003819 << " return NULL;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003820 << "}\n";
3821}
3822
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003823void DAGISelEmitter::run(std::ostream &OS) {
3824 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3825 " target", OS);
3826
Chris Lattner1f39e292005-09-14 00:09:24 +00003827 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3828 << "// *** instruction selector class. These functions are really "
3829 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003830
Chris Lattner8dc728e2006-08-27 13:16:24 +00003831 OS << "#include \"llvm/Support/Compiler.h\"\n";
Evan Cheng233baf12006-07-26 23:06:27 +00003832
Chris Lattner706d2d32006-08-09 16:44:44 +00003833 OS << "// Instruction selector priority queue:\n"
3834 << "std::vector<SDNode*> ISelQueue;\n";
3835 OS << "/// Keep track of nodes which have already been added to queue.\n"
3836 << "unsigned char *ISelQueued;\n";
3837 OS << "/// Keep track of nodes which have already been selected.\n"
3838 << "unsigned char *ISelSelected;\n";
3839 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
3840 << "std::vector<SDNode*> ISelKilled;\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003841
Evan Cheng4326ef52006-10-12 02:08:53 +00003842 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
3843 OS << "/// not reach Op.\n";
3844 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
3845 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
3846 OS << " return true;\n";
3847 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
3848 OS << " return false;\n";
3849 OS << " else if (Chain->getNumOperands() > 0) {\n";
3850 OS << " SDOperand C0 = Chain->getOperand(0);\n";
3851 OS << " if (C0.getValueType() == MVT::Other)\n";
3852 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
3853 OS << " }\n";
3854 OS << " return true;\n";
3855 OS << "}\n";
3856
Chris Lattner706d2d32006-08-09 16:44:44 +00003857 OS << "/// Sorting functions for the selection queue.\n"
3858 << "struct isel_sort : public std::binary_function"
3859 << "<SDNode*, SDNode*, bool> {\n"
3860 << " bool operator()(const SDNode* left, const SDNode* right) "
3861 << "const {\n"
3862 << " return (left->getNodeId() > right->getNodeId());\n"
3863 << " }\n"
3864 << "};\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003865
Chris Lattner706d2d32006-08-09 16:44:44 +00003866 OS << "inline void setQueued(int Id) {\n";
3867 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003868 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003869 OS << "inline bool isQueued(int Id) {\n";
3870 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003871 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003872 OS << "inline void setSelected(int Id) {\n";
3873 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003874 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003875 OS << "inline bool isSelected(int Id) {\n";
3876 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
3877 OS << "}\n\n";
Evan Cheng9bdca032006-08-07 22:17:58 +00003878
Chris Lattner8dc728e2006-08-27 13:16:24 +00003879 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003880 OS << " int Id = N.Val->getNodeId();\n";
3881 OS << " if (Id != -1 && !isQueued(Id)) {\n";
3882 OS << " ISelQueue.push_back(N.Val);\n";
3883 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3884 OS << " setQueued(Id);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003885 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003886 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003887
Chris Lattner706d2d32006-08-09 16:44:44 +00003888 OS << "inline void RemoveKilled() {\n";
3889OS << " unsigned NumKilled = ISelKilled.size();\n";
3890 OS << " if (NumKilled) {\n";
3891 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
3892 OS << " SDNode *Temp = ISelKilled[i];\n";
Evan Cheng4f776162006-10-12 23:18:52 +00003893 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
3894 << "Temp), ISelQueue.end());\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003895 OS << " };\n";
3896 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3897 OS << " ISelKilled.clear();\n";
3898 OS << " }\n";
3899 OS << "}\n\n";
3900
Chris Lattner8dc728e2006-08-27 13:16:24 +00003901 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003902 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n";
3903 OS << " setSelected(F.Val->getNodeId());\n";
3904 OS << " RemoveKilled();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003905 OS << "}\n";
3906 OS << "inline void ReplaceUses(SDNode *F, SDNode *T) {\n";
3907 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
3908 OS << " setSelected(F->getNodeId());\n";
3909 OS << " RemoveKilled();\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003910 OS << "}\n\n";
3911
Evan Chenge41bf822006-02-05 06:43:12 +00003912 OS << "// SelectRoot - Top level entry to DAG isel.\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003913 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
3914 OS << " SelectRootInit();\n";
3915 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
3916 OS << " ISelQueued = new unsigned char[NumBytes];\n";
3917 OS << " ISelSelected = new unsigned char[NumBytes];\n";
3918 OS << " memset(ISelQueued, 0, NumBytes);\n";
3919 OS << " memset(ISelSelected, 0, NumBytes);\n";
3920 OS << "\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00003921 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
3922 << " // a reference to the root node, preventing it from being deleted,\n"
3923 << " // and tracking any changes of the root.\n"
3924 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
3925 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003926 OS << " while (!ISelQueue.empty()) {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003927 OS << " SDNode *Node = ISelQueue.front();\n";
3928 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3929 OS << " ISelQueue.pop_back();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003930 OS << " if (!isSelected(Node->getNodeId())) {\n";
Evan Cheng9ade2182006-08-26 05:34:46 +00003931 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
Evan Cheng966fd372006-09-11 02:24:43 +00003932 OS << " if (ResNode != Node) {\n";
3933 OS << " if (ResNode)\n";
3934 OS << " ReplaceUses(Node, ResNode);\n";
Evan Cheng1fae00f2006-10-12 20:35:19 +00003935 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
3936 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
3937 OS << " RemoveKilled();\n";
3938 OS << " }\n";
Evan Cheng966fd372006-09-11 02:24:43 +00003939 OS << " }\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003940 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003941 OS << " }\n";
3942 OS << "\n";
3943 OS << " delete[] ISelQueued;\n";
3944 OS << " ISelQueued = NULL;\n";
3945 OS << " delete[] ISelSelected;\n";
3946 OS << " ISelSelected = NULL;\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00003947 OS << " return Dummy.getValue();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003948 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003949
Chris Lattner550525e2006-03-24 21:48:51 +00003950 Intrinsics = LoadIntrinsics(Records);
Chris Lattnerca559d02005-09-08 21:03:01 +00003951 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003952 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003953 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003954 ParsePatternFragments(OS);
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00003955 ParsePredicateOperands();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003956 ParseInstructions();
3957 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003958
Chris Lattnere97603f2005-09-28 19:27:25 +00003959 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003960 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003961 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003962
Bill Wendlingf5da1332006-12-07 22:21:48 +00003963 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
3964 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3965 DOUT << "PATTERN: "; DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
3966 DOUT << "\nRESULT: "; DEBUG(PatternsToMatch[i].getDstPattern()->dump());
3967 DOUT << "\n";
3968 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00003969
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003970 // At this point, we have full information about the 'Patterns' we need to
3971 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003972 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003973 EmitInstructionSelector(OS);
3974
3975 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3976 E = PatternFragments.end(); I != E; ++I)
3977 delete I->second;
3978 PatternFragments.clear();
3979
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003980 Instructions.clear();
3981}