blob: d2aac14819c7d3d877b1eb1174e9aa32236b73e6 [file] [log] [blame]
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner30609102007-12-29 20:37:13 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00007//
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 Cheng7774be42007-07-05 07:19:45 +0000625 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
626 R->getName() == "zero_reg") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000627 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000628 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000629 }
630
631 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000632 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000633}
634
Chris Lattner32707602005-09-08 23:22:48 +0000635/// ApplyTypeConstraints - Apply all of the type constraints relevent to
636/// this node and its children in the tree. This returns true if it makes a
637/// change, false otherwise. If a type contradiction is found, throw an
638/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000639bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000640 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000641 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000642 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000643 // If it's a regclass or something else known, include the type.
Chris Lattner52793e22006-04-06 20:19:52 +0000644 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000645 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
646 // Int inits are always integers. :)
647 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
648
649 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000650 // At some point, it may make sense for this tree pattern to have
651 // multiple types. Assert here that it does not, so we revisit this
652 // code when appropriate.
Evan Cheng2618d072006-05-17 20:37:59 +0000653 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Evan Cheng44a65fa2006-05-16 07:05:30 +0000654 MVT::ValueType VT = getTypeNum(0);
655 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
656 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
Nate Begemanb73628b2005-12-30 00:12:56 +0000657
Evan Cheng2618d072006-05-17 20:37:59 +0000658 VT = getTypeNum(0);
659 if (VT != MVT::iPTR) {
660 unsigned Size = MVT::getSizeInBits(VT);
661 // Make sure that the value is representable for this type.
662 if (Size < 32) {
663 int Val = (II->getValue() << (32-Size)) >> (32-Size);
664 if (Val != II->getValue())
665 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
666 "' is out of range for type '" +
667 getEnumName(getTypeNum(0)) + "'!");
668 }
Chris Lattner465c7372005-11-03 05:46:11 +0000669 }
670 }
671
672 return MadeChange;
673 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000674 return false;
675 }
Chris Lattner32707602005-09-08 23:22:48 +0000676
677 // special handling for set, which isn't really an SDNode.
678 if (getOperator()->getName() == "set") {
Evan Chengaeb7d4d2007-09-11 19:52:18 +0000679 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
680 unsigned NC = getNumChildren();
681 bool MadeChange = false;
682 for (unsigned i = 0; i < NC-1; ++i) {
683 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
684 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000685
Evan Chengaeb7d4d2007-09-11 19:52:18 +0000686 // Types of operands must match.
687 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
688 TP);
689 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
690 TP);
691 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
692 }
Chris Lattner32707602005-09-08 23:22:48 +0000693 return MadeChange;
Evan Chengd23aa5a2007-09-25 01:48:59 +0000694 } else if (getOperator()->getName() == "implicit" ||
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000695 getOperator()->getName() == "parallel") {
696 bool MadeChange = false;
697 for (unsigned i = 0; i < getNumChildren(); ++i)
698 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
699 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
700 return MadeChange;
Chris Lattner5a1df382006-03-24 23:10:39 +0000701 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
702 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
703 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
704 unsigned IID =
705 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
706 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
707 bool MadeChange = false;
708
709 // Apply the result type to the node.
710 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
711
712 if (getNumChildren() != Int.ArgVTs.size())
Chris Lattner2c4e65d2006-03-27 22:21:18 +0000713 TP.error("Intrinsic '" + Int.Name + "' expects " +
Chris Lattner5a1df382006-03-24 23:10:39 +0000714 utostr(Int.ArgVTs.size()-1) + " operands, not " +
715 utostr(getNumChildren()-1) + " operands!");
716
717 // Apply type info to the intrinsic ID.
Evan Cheng2618d072006-05-17 20:37:59 +0000718 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5a1df382006-03-24 23:10:39 +0000719
720 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
721 MVT::ValueType OpVT = Int.ArgVTs[i];
722 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
723 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
724 }
725 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000726 } else if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000727 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
Chris Lattnerabbb6052005-09-15 21:42:00 +0000728
729 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
730 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000731 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000732 // Branch, etc. do not produce results and top-level forms in instr pattern
733 // must have void types.
734 if (NI.getNumResults() == 0)
735 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner91ded082006-04-06 20:36:51 +0000736
737 // If this is a vector_shuffle operation, apply types to the build_vector
738 // operation. The types of the integers don't matter, but this ensures they
739 // won't get checked.
740 if (getOperator()->getName() == "vector_shuffle" &&
741 getChild(2)->getOperator()->getName() == "build_vector") {
742 TreePatternNode *BV = getChild(2);
743 const std::vector<MVT::ValueType> &LegalVTs
744 = ISE.getTargetInfo().getLegalValueTypes();
745 MVT::ValueType LegalIntVT = MVT::Other;
746 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
747 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
748 LegalIntVT = LegalVTs[i];
749 break;
750 }
751 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
752
753 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
754 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
755 }
Chris Lattnerabbb6052005-09-15 21:42:00 +0000756 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000757 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000758 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000759 bool MadeChange = false;
760 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000761
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000762 assert(NumResults <= 1 &&
763 "Only supports zero or one result instrs!");
Evan Chengeb1f40d2006-07-20 23:36:20 +0000764
765 CodeGenInstruction &InstInfo =
766 ISE.getTargetInfo().getInstruction(getOperator()->getName());
Chris Lattnera28aec12005-09-15 22:23:50 +0000767 // Apply the result type to the node
Evan Cheng102dc192007-07-20 00:21:23 +0000768 if (NumResults == 0 || InstInfo.NumDefs == 0) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000769 MadeChange = UpdateNodeType(MVT::isVoid, TP);
770 } else {
771 Record *ResultNode = Inst.getResult(0);
Chris Lattner646085d2006-11-14 21:18:40 +0000772
773 if (ResultNode->getName() == "ptr_rc") {
774 std::vector<unsigned char> VT;
775 VT.push_back(MVT::iPTR);
776 MadeChange = UpdateNodeType(VT, TP);
777 } else {
778 assert(ResultNode->isSubClassOf("RegisterClass") &&
779 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000780
Chris Lattner646085d2006-11-14 21:18:40 +0000781 const CodeGenRegisterClass &RC =
782 ISE.getTargetInfo().getRegisterClass(ResultNode);
783 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
784 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000785 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000786
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000787 unsigned ChildNo = 0;
788 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000789 Record *OperandNode = Inst.getOperand(i);
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000790
Evan Chenga9559392007-07-06 01:05:26 +0000791 // If the instruction expects a predicate or optional def operand, we
792 // codegen this by setting the operand to it's default value if it has a
793 // non-empty DefaultOps field.
794 if ((OperandNode->isSubClassOf("PredicateOperand") ||
795 OperandNode->isSubClassOf("OptionalDefOperand")) &&
796 !ISE.getDefaultOperand(OperandNode).DefaultOps.empty())
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000797 continue;
798
799 // Verify that we didn't run out of provided operands.
800 if (ChildNo >= getNumChildren())
801 TP.error("Instruction '" + getOperator()->getName() +
802 "' expects more operands than were provided.");
803
Nate Begemanddb39542005-12-01 00:06:14 +0000804 MVT::ValueType VT;
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000805 TreePatternNode *Child = getChild(ChildNo++);
Nate Begemanddb39542005-12-01 00:06:14 +0000806 if (OperandNode->isSubClassOf("RegisterClass")) {
807 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000808 ISE.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000809 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000810 } else if (OperandNode->isSubClassOf("Operand")) {
811 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000812 MadeChange |= Child->UpdateNodeType(VT, TP);
Chris Lattner646085d2006-11-14 21:18:40 +0000813 } else if (OperandNode->getName() == "ptr_rc") {
814 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000815 } else {
816 assert(0 && "Unknown operand type!");
817 abort();
818 }
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000819 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000820 }
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000821
822 if (ChildNo != getNumChildren())
823 TP.error("Instruction '" + getOperator()->getName() +
824 "' was provided too many operands!");
825
Chris Lattnera28aec12005-09-15 22:23:50 +0000826 return MadeChange;
827 } else {
828 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
829
Evan Chengf26ba692006-03-20 08:09:17 +0000830 // Node transforms always take one operand.
Chris Lattnera28aec12005-09-15 22:23:50 +0000831 if (getNumChildren() != 1)
832 TP.error("Node transform '" + getOperator()->getName() +
833 "' requires one operand!");
Chris Lattner4e2f54d2006-03-21 06:42:58 +0000834
835 // If either the output or input of the xform does not have exact
836 // type info. We assume they must be the same. Otherwise, it is perfectly
837 // legal to transform from one type to a completely different type.
838 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Evan Chengf26ba692006-03-20 08:09:17 +0000839 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
840 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
841 return MadeChange;
842 }
843 return false;
Chris Lattner32707602005-09-08 23:22:48 +0000844 }
Chris Lattner32707602005-09-08 23:22:48 +0000845}
846
Chris Lattnerce6e84c2006-09-21 20:46:13 +0000847/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
848/// RHS of a commutative operation, not the on LHS.
849static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
850 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
851 return true;
852 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
853 return true;
854 return false;
855}
856
857
Chris Lattnere97603f2005-09-28 19:27:25 +0000858/// canPatternMatch - If it is impossible for this pattern to match on this
859/// target, fill in Reason and return false. Otherwise, return true. This is
860/// used as a santity check for .td files (to prevent people from writing stuff
861/// that can never possibly work), and to prevent the pattern permuter from
862/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000863bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000864 if (isLeaf()) return true;
865
866 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
867 if (!getChild(i)->canPatternMatch(Reason, ISE))
868 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000869
Chris Lattner550525e2006-03-24 21:48:51 +0000870 // If this is an intrinsic, handle cases that would make it not match. For
871 // example, if an operand is required to be an immediate.
872 if (getOperator()->isSubClassOf("Intrinsic")) {
873 // TODO:
874 return true;
875 }
876
Chris Lattnere97603f2005-09-28 19:27:25 +0000877 // If this node is a commutative operator, check that the LHS isn't an
878 // immediate.
879 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
Evan Cheng94b30402006-10-11 21:02:01 +0000880 if (NodeInfo.hasProperty(SDNPCommutative)) {
Chris Lattnere97603f2005-09-28 19:27:25 +0000881 // Scan all of the operands of the node and make sure that only the last one
Chris Lattner7905c552006-09-14 23:54:24 +0000882 // is a constant node, unless the RHS also is.
Chris Lattnerce6e84c2006-09-21 20:46:13 +0000883 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Chris Lattner7905c552006-09-14 23:54:24 +0000884 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
Chris Lattnerce6e84c2006-09-21 20:46:13 +0000885 if (OnlyOnRHSOfCommutative(getChild(i))) {
Chris Lattner64906972006-09-21 18:28:27 +0000886 Reason="Immediate value must be on the RHS of commutative operators!";
Chris Lattner7905c552006-09-14 23:54:24 +0000887 return false;
888 }
889 }
Chris Lattnere97603f2005-09-28 19:27:25 +0000890 }
891
892 return true;
893}
Chris Lattner32707602005-09-08 23:22:48 +0000894
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000895//===----------------------------------------------------------------------===//
896// TreePattern implementation
897//
898
Chris Lattneredbd8712005-10-21 01:19:59 +0000899TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000900 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000901 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000902 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
903 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000904}
905
Chris Lattneredbd8712005-10-21 01:19:59 +0000906TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000907 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000908 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000909 Trees.push_back(ParseTreePattern(Pat));
910}
911
Chris Lattneredbd8712005-10-21 01:19:59 +0000912TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000913 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000914 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000915 Trees.push_back(Pat);
916}
917
918
919
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000920void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000921 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000922 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000923}
924
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000925TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
Chris Lattner8c063182006-03-30 22:50:40 +0000926 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
927 if (!OpDef) error("Pattern has unexpected operator type!");
928 Record *Operator = OpDef->getDef();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000929
930 if (Operator->isSubClassOf("ValueType")) {
931 // If the operator is a ValueType, then this must be "type cast" of a leaf
932 // node.
933 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000934 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000935
936 Init *Arg = Dag->getArg(0);
937 TreePatternNode *New;
938 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000939 Record *R = DI->getDef();
940 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000941 Dag->setArg(0, new DagInit(DI,
Chris Lattner72fe91c2005-09-24 00:40:24 +0000942 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000943 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000944 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000945 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000946 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
947 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000948 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
949 New = new TreePatternNode(II);
950 if (!Dag->getArgName(0).empty())
951 error("Constant int argument should not have a name!");
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000952 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
953 // Turn this into an IntInit.
954 Init *II = BI->convertInitializerTo(new IntRecTy());
955 if (II == 0 || !dynamic_cast<IntInit*>(II))
956 error("Bits value must be constants!");
957
958 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
959 if (!Dag->getArgName(0).empty())
960 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000961 } else {
962 Arg->dump();
963 error("Unknown leaf value for tree pattern!");
964 return 0;
965 }
966
Chris Lattner32707602005-09-08 23:22:48 +0000967 // Apply the type cast.
968 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000969 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000970 return New;
971 }
972
973 // Verify that this is something that makes sense for an operator.
974 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000975 !Operator->isSubClassOf("Instruction") &&
976 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner550525e2006-03-24 21:48:51 +0000977 !Operator->isSubClassOf("Intrinsic") &&
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000978 Operator->getName() != "set" &&
Evan Chengd23aa5a2007-09-25 01:48:59 +0000979 Operator->getName() != "implicit" &&
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000980 Operator->getName() != "parallel")
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000981 error("Unrecognized node '" + Operator->getName() + "'!");
982
Chris Lattneredbd8712005-10-21 01:19:59 +0000983 // Check to see if this is something that is illegal in an input pattern.
984 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
Chris Lattner5a1df382006-03-24 23:10:39 +0000985 Operator->isSubClassOf("SDNodeXForm")))
Chris Lattneredbd8712005-10-21 01:19:59 +0000986 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
987
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000988 std::vector<TreePatternNode*> Children;
989
990 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
991 Init *Arg = Dag->getArg(i);
992 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
993 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000994 if (Children.back()->getName().empty())
995 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000996 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
997 Record *R = DefI->getDef();
998 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
999 // TreePatternNode if its own.
1000 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +00001001 Dag->setArg(i, new DagInit(DefI,
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001002 std::vector<std::pair<Init*, std::string> >()));
1003 --i; // Revisit this node...
1004 } else {
1005 TreePatternNode *Node = new TreePatternNode(DefI);
1006 Node->setName(Dag->getArgName(i));
1007 Children.push_back(Node);
1008
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001009 // Input argument?
1010 if (R->getName() == "node") {
1011 if (Dag->getArgName(i).empty())
1012 error("'node' argument requires a name to match with operand list");
1013 Args.push_back(Dag->getArgName(i));
1014 }
1015 }
Chris Lattner5d5a0562005-10-19 04:30:56 +00001016 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1017 TreePatternNode *Node = new TreePatternNode(II);
1018 if (!Dag->getArgName(i).empty())
1019 error("Constant int argument should not have a name!");
1020 Children.push_back(Node);
Chris Lattnerffa4fdc2006-03-31 05:25:56 +00001021 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1022 // Turn this into an IntInit.
1023 Init *II = BI->convertInitializerTo(new IntRecTy());
1024 if (II == 0 || !dynamic_cast<IntInit*>(II))
1025 error("Bits value must be constants!");
1026
1027 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1028 if (!Dag->getArgName(i).empty())
1029 error("Constant int argument should not have a name!");
1030 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001031 } else {
Bill Wendlingf5da1332006-12-07 22:21:48 +00001032 cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001033 Arg->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00001034 cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001035 error("Unknown leaf value for tree pattern!");
1036 }
1037 }
1038
Chris Lattner5a1df382006-03-24 23:10:39 +00001039 // If the operator is an intrinsic, then this is just syntactic sugar for for
1040 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1041 // convert the intrinsic name to a number.
1042 if (Operator->isSubClassOf("Intrinsic")) {
1043 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
1044 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
1045
1046 // If this intrinsic returns void, it must have side-effects and thus a
1047 // chain.
1048 if (Int.ArgVTs[0] == MVT::isVoid) {
1049 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
1050 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1051 // Has side-effects, requires chain.
1052 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
1053 } else {
1054 // Otherwise, no chain.
1055 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
1056 }
1057
1058 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1059 Children.insert(Children.begin(), IIDNode);
1060 }
1061
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001062 return new TreePatternNode(Operator, Children);
1063}
1064
Chris Lattner32707602005-09-08 23:22:48 +00001065/// InferAllTypes - Infer/propagate as many types throughout the expression
1066/// patterns as possible. Return true if all types are infered, false
1067/// otherwise. Throw an exception if a type contradiction is found.
1068bool TreePattern::InferAllTypes() {
1069 bool MadeChange = true;
1070 while (MadeChange) {
1071 MadeChange = false;
1072 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001073 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +00001074 }
1075
1076 bool HasUnresolvedTypes = false;
1077 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1078 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1079 return !HasUnresolvedTypes;
1080}
1081
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001082void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001083 OS << getRecord()->getName();
1084 if (!Args.empty()) {
1085 OS << "(" << Args[0];
1086 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1087 OS << ", " << Args[i];
1088 OS << ")";
1089 }
1090 OS << ": ";
1091
1092 if (Trees.size() > 1)
1093 OS << "[\n";
1094 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1095 OS << "\t";
1096 Trees[i]->print(OS);
1097 OS << "\n";
1098 }
1099
1100 if (Trees.size() > 1)
1101 OS << "]\n";
1102}
1103
Bill Wendlingf5da1332006-12-07 22:21:48 +00001104void TreePattern::dump() const { print(*cerr.stream()); }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001105
1106
1107
1108//===----------------------------------------------------------------------===//
1109// DAGISelEmitter implementation
1110//
1111
Chris Lattnerca559d02005-09-08 21:03:01 +00001112// Parse all of the SDNode definitions for the target, populating SDNodes.
1113void DAGISelEmitter::ParseNodeInfo() {
1114 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1115 while (!Nodes.empty()) {
1116 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1117 Nodes.pop_back();
1118 }
Chris Lattner5a1df382006-03-24 23:10:39 +00001119
1120 // Get the buildin intrinsic nodes.
1121 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1122 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1123 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
Chris Lattnerca559d02005-09-08 21:03:01 +00001124}
1125
Chris Lattner24eeeb82005-09-13 21:51:00 +00001126/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1127/// map, and emit them to the file as functions.
1128void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1129 OS << "\n// Node transformations.\n";
1130 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1131 while (!Xforms.empty()) {
1132 Record *XFormNode = Xforms.back();
1133 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1134 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1135 SDNodeXForms.insert(std::make_pair(XFormNode,
1136 std::make_pair(SDNode, Code)));
1137
Chris Lattner1048b7a2005-09-13 22:03:37 +00001138 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +00001139 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1140 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1141
Chris Lattner1048b7a2005-09-13 22:03:37 +00001142 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +00001143 << "(SDNode *" << C2 << ") {\n";
1144 if (ClassName != "SDNode")
1145 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1146 OS << Code << "\n}\n";
1147 }
1148
1149 Xforms.pop_back();
1150 }
1151}
1152
Evan Cheng0fc71982005-12-08 02:00:36 +00001153void DAGISelEmitter::ParseComplexPatterns() {
1154 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1155 while (!AMs.empty()) {
1156 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1157 AMs.pop_back();
1158 }
1159}
Chris Lattner24eeeb82005-09-13 21:51:00 +00001160
1161
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001162/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1163/// file, building up the PatternFragments map. After we've collected them all,
1164/// inline fragments together as necessary, so that there are no references left
1165/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001166///
1167/// This also emits all of the predicate functions to the output file.
1168///
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001169void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001170 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1171
1172 // First step, parse all of the fragments and emit predicate functions.
1173 OS << "\n// Predicate functions.\n";
1174 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001175 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +00001176 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001177 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +00001178
1179 // Validate the argument list, converting it to map, to discard duplicates.
1180 std::vector<std::string> &Args = P->getArgList();
1181 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1182
1183 if (OperandsMap.count(""))
1184 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1185
1186 // Parse the operands list.
1187 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Chris Lattner8c063182006-03-30 22:50:40 +00001188 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
Evan Cheng64d80e32007-07-19 01:14:50 +00001189 // Special cases: ops == outs == ins. Different names are used to
1190 // improve readibility.
1191 if (!OpsOp ||
1192 (OpsOp->getDef()->getName() != "ops" &&
1193 OpsOp->getDef()->getName() != "outs" &&
1194 OpsOp->getDef()->getName() != "ins"))
Chris Lattneree9f0c32005-09-13 21:20:49 +00001195 P->error("Operands list should start with '(ops ... '!");
1196
1197 // Copy over the arguments.
1198 Args.clear();
1199 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1200 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1201 static_cast<DefInit*>(OpsList->getArg(j))->
1202 getDef()->getName() != "node")
1203 P->error("Operands list should all be 'node' values.");
1204 if (OpsList->getArgName(j).empty())
1205 P->error("Operands list should have names for each operand!");
1206 if (!OperandsMap.count(OpsList->getArgName(j)))
1207 P->error("'" + OpsList->getArgName(j) +
1208 "' does not occur in pattern or was multiply specified!");
1209 OperandsMap.erase(OpsList->getArgName(j));
1210 Args.push_back(OpsList->getArgName(j));
1211 }
1212
1213 if (!OperandsMap.empty())
1214 P->error("Operands list does not contain an entry for operand '" +
1215 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001216
1217 // If there is a code init for this fragment, emit the predicate code and
1218 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +00001219 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1220 if (!Code.empty()) {
Evan Chengd46bd602006-09-19 19:08:04 +00001221 if (P->getOnlyTree()->isLeaf())
1222 OS << "inline bool Predicate_" << Fragments[i]->getName()
1223 << "(SDNode *N) {\n";
1224 else {
1225 std::string ClassName =
1226 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1227 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001228
Evan Chengd46bd602006-09-19 19:08:04 +00001229 OS << "inline bool Predicate_" << Fragments[i]->getName()
1230 << "(SDNode *" << C2 << ") {\n";
1231 if (ClassName != "SDNode")
1232 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1233 }
Chris Lattner24eeeb82005-09-13 21:51:00 +00001234 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +00001235 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001236 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001237
1238 // If there is a node transformation corresponding to this, keep track of
1239 // it.
1240 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1241 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001242 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001243 }
1244
1245 OS << "\n\n";
1246
1247 // Now that we've parsed all of the tree fragments, do a closure on them so
1248 // that there are not references to PatFrags left inside of them.
1249 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1250 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001251 TreePattern *ThePat = I->second;
1252 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001253
Chris Lattner32707602005-09-08 23:22:48 +00001254 // Infer as many types as possible. Don't worry about it if we don't infer
1255 // all of them, some may depend on the inputs of the pattern.
1256 try {
1257 ThePat->InferAllTypes();
1258 } catch (...) {
1259 // If this pattern fragment is not supported by this target (no types can
1260 // satisfy its constraints), just ignore it. If the bogus pattern is
1261 // actually used by instructions, the type consistency error will be
1262 // reported there.
1263 }
1264
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001265 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001266 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001267 }
1268}
1269
Evan Chenga9559392007-07-06 01:05:26 +00001270void DAGISelEmitter::ParseDefaultOperands() {
1271 std::vector<Record*> DefaultOps[2];
1272 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1273 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001274
1275 // Find some SDNode.
1276 assert(!SDNodes.empty() && "No SDNodes parsed?");
1277 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1278
Evan Chenga9559392007-07-06 01:05:26 +00001279 for (unsigned iter = 0; iter != 2; ++iter) {
1280 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1281 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001282
Evan Chenga9559392007-07-06 01:05:26 +00001283 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1284 // SomeSDnode so that we can parse this.
1285 std::vector<std::pair<Init*, std::string> > Ops;
1286 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1287 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1288 DefaultInfo->getArgName(op)));
1289 DagInit *DI = new DagInit(SomeSDNode, Ops);
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001290
Evan Chenga9559392007-07-06 01:05:26 +00001291 // Create a TreePattern to parse this.
1292 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1293 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001294
Evan Chenga9559392007-07-06 01:05:26 +00001295 // Copy the operands over into a DAGDefaultOperand.
1296 DAGDefaultOperand DefaultOpInfo;
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001297
Evan Chenga9559392007-07-06 01:05:26 +00001298 TreePatternNode *T = P.getTree(0);
1299 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1300 TreePatternNode *TPN = T->getChild(op);
1301 while (TPN->ApplyTypeConstraints(P, false))
1302 /* Resolve all types */;
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001303
Evan Chenga9559392007-07-06 01:05:26 +00001304 if (TPN->ContainsUnresolvedType())
1305 if (iter == 0)
1306 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1307 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1308 else
1309 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1310 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001311
Evan Chenga9559392007-07-06 01:05:26 +00001312 DefaultOpInfo.DefaultOps.push_back(TPN);
1313 }
1314
1315 // Insert it into the DefaultOperands map so we can find it later.
1316 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001317 }
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001318 }
1319}
1320
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001321/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001322/// instruction input. Return true if this is a real use.
1323static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001324 std::map<std::string, TreePatternNode*> &InstInputs,
1325 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001326 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001327 if (Pat->getName().empty()) {
1328 if (Pat->isLeaf()) {
1329 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1330 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1331 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001332 else if (DI && DI->getDef()->isSubClassOf("Register"))
1333 InstImpInputs.push_back(DI->getDef());
Evan Chengaeb7d4d2007-09-11 19:52:18 +00001334 ;
Chris Lattner7da852f2005-09-14 22:06:36 +00001335 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001336 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001337 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001338
1339 Record *Rec;
1340 if (Pat->isLeaf()) {
1341 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1342 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1343 Rec = DI->getDef();
1344 } else {
1345 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1346 Rec = Pat->getOperator();
1347 }
1348
Evan Cheng01f318b2005-12-14 02:21:57 +00001349 // SRCVALUE nodes are ignored.
1350 if (Rec->getName() == "srcvalue")
1351 return false;
1352
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001353 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1354 if (!Slot) {
1355 Slot = Pat;
1356 } else {
1357 Record *SlotRec;
1358 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001359 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001360 } else {
1361 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1362 SlotRec = Slot->getOperator();
1363 }
1364
1365 // Ensure that the inputs agree if we've already seen this input.
1366 if (Rec != SlotRec)
1367 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001368 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001369 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1370 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001371 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001372}
1373
1374/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1375/// part of "I", the instruction), computing the set of inputs and outputs of
1376/// the pattern. Report errors if we see anything naughty.
1377void DAGISelEmitter::
1378FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1379 std::map<std::string, TreePatternNode*> &InstInputs,
Chris Lattner947604b2006-03-24 21:52:20 +00001380 std::map<std::string, TreePatternNode*>&InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001381 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001382 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001383 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001384 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001385 if (!isUse && Pat->getTransformFn())
1386 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001387 return;
Evan Chengd23aa5a2007-09-25 01:48:59 +00001388 } else if (Pat->getOperator()->getName() == "implicit") {
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001389 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1390 TreePatternNode *Dest = Pat->getChild(i);
1391 if (!Dest->isLeaf())
Evan Chengd23aa5a2007-09-25 01:48:59 +00001392 I->error("implicitly defined value should be a register!");
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001393
1394 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1395 if (!Val || !Val->getDef()->isSubClassOf("Register"))
Evan Chengd23aa5a2007-09-25 01:48:59 +00001396 I->error("implicitly defined value should be a register!");
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001397 InstImpResults.push_back(Val->getDef());
1398 }
1399 return;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001400 } else if (Pat->getOperator()->getName() != "set") {
1401 // If this is not a set, verify that the children nodes are not void typed,
1402 // and recurse.
1403 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001404 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001405 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001406 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001407 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001408 }
1409
1410 // If this is a non-leaf node with no children, treat it basically as if
1411 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001412 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001413 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001414 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001415
Chris Lattnerf1311842005-09-14 23:05:13 +00001416 if (!isUse && Pat->getTransformFn())
1417 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001418 return;
1419 }
1420
1421 // Otherwise, this is a set, validate and collect instruction results.
1422 if (Pat->getNumChildren() == 0)
1423 I->error("set requires operands!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001424
Chris Lattnerf1311842005-09-14 23:05:13 +00001425 if (Pat->getTransformFn())
1426 I->error("Cannot specify a transform function on a set node!");
1427
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001428 // Check the set destinations.
Evan Chengaeb7d4d2007-09-11 19:52:18 +00001429 unsigned NumDests = Pat->getNumChildren()-1;
1430 for (unsigned i = 0; i != NumDests; ++i) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001431 TreePatternNode *Dest = Pat->getChild(i);
1432 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001433 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001434
1435 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1436 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001437 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001438
Chris Lattner646085d2006-11-14 21:18:40 +00001439 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1440 Val->getDef()->getName() == "ptr_rc") {
Evan Chengbcecf332005-12-17 01:19:28 +00001441 if (Dest->getName().empty())
1442 I->error("set destination must have a name!");
1443 if (InstResults.count(Dest->getName()))
1444 I->error("cannot set '" + Dest->getName() +"' multiple times");
Evan Cheng420132e2006-03-20 06:04:09 +00001445 InstResults[Dest->getName()] = Dest;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001446 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001447 InstImpResults.push_back(Val->getDef());
1448 } else {
1449 I->error("set destination should be a register!");
1450 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001451 }
Evan Chengaeb7d4d2007-09-11 19:52:18 +00001452
1453 // Verify and collect info from the computation.
1454 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1455 InstInputs, InstResults,
1456 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001457}
1458
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001459/// ParseInstructions - Parse all of the instructions, inlining and resolving
1460/// any fragments involved. This populates the Instructions list with fully
1461/// resolved instructions.
1462void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001463 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1464
1465 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001466 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001467
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001468 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1469 LI = Instrs[i]->getValueAsListInit("Pattern");
1470
1471 // If there is no pattern, only collect minimal information about the
1472 // instruction for its operand list. We have to assume that there is one
1473 // result, as we have no detailed info.
1474 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001475 std::vector<Record*> Results;
1476 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001477
1478 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001479
Evan Cheng3a217f32005-12-22 02:35:21 +00001480 if (InstInfo.OperandList.size() != 0) {
Evan Cheng102dc192007-07-20 00:21:23 +00001481 if (InstInfo.NumDefs == 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001482 // These produce no results
1483 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1484 Operands.push_back(InstInfo.OperandList[j].Rec);
1485 } else {
1486 // Assume the first operand is the result.
1487 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001488
Evan Cheng3a217f32005-12-22 02:35:21 +00001489 // The rest are inputs.
1490 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1491 Operands.push_back(InstInfo.OperandList[j].Rec);
1492 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001493 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001494
1495 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001496 std::vector<Record*> ImpResults;
1497 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001498 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001499 DAGInstruction(0, Results, Operands, ImpResults,
1500 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001501 continue; // no pattern.
1502 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001503
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001504 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001505 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001506 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001507 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001508
Chris Lattner95f6b762005-09-08 23:26:30 +00001509 // Infer as many types as possible. If we cannot infer all of them, we can
1510 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001511 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001512 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001513
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001514 // InstInputs - Keep track of all of the inputs of the instruction, along
1515 // with the record they are declared as.
1516 std::map<std::string, TreePatternNode*> InstInputs;
1517
1518 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001519 // in the instruction, including what reg class they are.
Evan Cheng420132e2006-03-20 06:04:09 +00001520 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001521
1522 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001523 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001524
Chris Lattner1f39e292005-09-14 00:09:24 +00001525 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001526 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001527 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1528 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001529 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001530 I->error("Top-level forms in instruction pattern should have"
1531 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001532
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001533 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001534 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001535 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001536 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001537
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001538 // Now that we have inputs and outputs of the pattern, inspect the operands
1539 // list for the instruction. This determines the order that operands are
1540 // added to the machine instruction the node corresponds to.
1541 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001542
1543 // Parse the operands list from the (ops) list, validating it.
Chris Lattner20c2b352007-06-19 06:40:46 +00001544 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001545 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1546
1547 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001548 std::vector<Record*> Results;
Evan Cheng420132e2006-03-20 06:04:09 +00001549 TreePatternNode *Res0Node = NULL;
Chris Lattner39e8af92005-09-14 18:19:25 +00001550 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001551 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001552 I->error("'" + InstResults.begin()->first +
1553 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001554 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001555
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001556 // Check that it exists in InstResults.
Evan Cheng420132e2006-03-20 06:04:09 +00001557 TreePatternNode *RNode = InstResults[OpName];
Chris Lattner5c4c7742006-03-25 22:12:44 +00001558 if (RNode == 0)
1559 I->error("Operand $" + OpName + " does not exist in operand list!");
1560
Evan Cheng420132e2006-03-20 06:04:09 +00001561 if (i == 0)
1562 Res0Node = RNode;
1563 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner39e8af92005-09-14 18:19:25 +00001564 if (R == 0)
1565 I->error("Operand $" + OpName + " should be a set destination: all "
1566 "outputs must occur before inputs in operand list!");
1567
1568 if (CGI.OperandList[i].Rec != R)
1569 I->error("Operand $" + OpName + " class mismatch!");
1570
Chris Lattnerae6d8282005-09-15 21:51:12 +00001571 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001572 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001573
Chris Lattner39e8af92005-09-14 18:19:25 +00001574 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001575 InstResults.erase(OpName);
1576 }
1577
Chris Lattner0b592252005-09-14 21:59:34 +00001578 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1579 // the copy while we're checking the inputs.
1580 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001581
1582 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001583 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001584 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001585 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1586 const std::string &OpName = Op.Name;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001587 if (OpName.empty())
1588 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1589
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001590 if (!InstInputsCheck.count(OpName)) {
Evan Chenga9559392007-07-06 01:05:26 +00001591 // If this is an predicate operand or optional def operand with an
1592 // DefaultOps set filled in, we can ignore this. When we codegen it,
1593 // we will do so as always executed.
1594 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1595 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1596 // Does it have a non-empty DefaultOps field? If so, ignore this
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001597 // operand.
Evan Chenga9559392007-07-06 01:05:26 +00001598 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001599 continue;
1600 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001601 I->error("Operand $" + OpName +
1602 " does not appear in the instruction pattern");
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001603 }
Chris Lattner0b592252005-09-14 21:59:34 +00001604 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001605 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001606
1607 if (InVal->isLeaf() &&
1608 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1609 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001610 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001611 I->error("Operand $" + OpName + "'s register class disagrees"
1612 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001613 }
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001614 Operands.push_back(Op.Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001615
Chris Lattner2175c182005-09-14 23:01:59 +00001616 // Construct the result for the dest-pattern operand list.
1617 TreePatternNode *OpNode = InVal->clone();
1618
1619 // No predicate is useful on the result.
1620 OpNode->setPredicateFn("");
1621
1622 // Promote the xform function to be an explicit node if set.
1623 if (Record *Xform = OpNode->getTransformFn()) {
1624 OpNode->setTransformFn(0);
1625 std::vector<TreePatternNode*> Children;
1626 Children.push_back(OpNode);
1627 OpNode = new TreePatternNode(Xform, Children);
1628 }
1629
1630 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001631 }
1632
Chris Lattner0b592252005-09-14 21:59:34 +00001633 if (!InstInputsCheck.empty())
1634 I->error("Input operand $" + InstInputsCheck.begin()->first +
1635 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001636
1637 TreePatternNode *ResultPattern =
1638 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Evan Cheng420132e2006-03-20 06:04:09 +00001639 // Copy fully inferred output node type to instruction result pattern.
1640 if (NumResults > 0)
1641 ResultPattern->setTypes(Res0Node->getExtTypes());
Chris Lattnera28aec12005-09-15 22:23:50 +00001642
1643 // Create and insert the instruction.
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001644 // FIXME: InstImpResults and InstImpInputs should not be part of
1645 // DAGInstruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001646 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001647 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1648
1649 // Use a temporary tree pattern to infer all types and make sure that the
1650 // constructed result is correct. This depends on the instruction already
1651 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001652 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001653 Temp.InferAllTypes();
1654
1655 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1656 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001657
Chris Lattner32707602005-09-08 23:22:48 +00001658 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001659 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001660
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001661 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001662 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1663 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001664 DAGInstruction &TheInst = II->second;
1665 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001666 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001667
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001668 // FIXME: Assume only the first tree is the pattern. The others are clobber
1669 // nodes.
Chris Lattner1f39e292005-09-14 00:09:24 +00001670 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001671 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001672 if (Pattern->getOperator()->getName() == "set") {
Evan Chengaeb7d4d2007-09-11 19:52:18 +00001673 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001674 } else{
1675 // Not a set (store or something?)
1676 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001677 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001678
1679 std::string Reason;
1680 if (!SrcPattern->canPatternMatch(Reason, *this))
1681 I->error("Instruction can never match: " + Reason);
1682
Evan Cheng58e84a62005-12-14 22:02:59 +00001683 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001684 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001685 PatternsToMatch.
1686 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001687 SrcPattern, DstPattern, TheInst.getImpResults(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001688 Instr->getValueAsInt("AddedComplexity")));
Chris Lattner1f39e292005-09-14 00:09:24 +00001689 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001690}
1691
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001692void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001693 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001694
Chris Lattnerabbb6052005-09-15 21:42:00 +00001695 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001696 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001697 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
1698 Record *Operator = OpDef->getDef();
1699 TreePattern *Pattern;
1700 if (Operator->getName() != "parallel")
1701 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1702 else {
1703 std::vector<Init*> Values;
1704 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
1705 Values.push_back(Tree->getArg(j));
1706 ListInit *LI = new ListInit(Values);
1707 Pattern = new TreePattern(Patterns[i], LI, true, *this);
1708 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001709
Chris Lattnerabbb6052005-09-15 21:42:00 +00001710 // Inline pattern fragments into it.
1711 Pattern->InlinePatternFragments();
1712
Chris Lattnera3548492006-06-20 00:18:02 +00001713 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1714 if (LI->getSize() == 0) continue; // no pattern.
1715
1716 // Parse the instruction.
1717 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1718
1719 // Inline pattern fragments into it.
1720 Result->InlinePatternFragments();
Chris Lattner09c03392005-11-17 17:43:52 +00001721
Chris Lattnera3548492006-06-20 00:18:02 +00001722 if (Result->getNumTrees() != 1)
1723 Result->error("Cannot handle instructions producing instructions "
1724 "with temporaries yet!");
1725
1726 bool IterateInference;
Chris Lattner186fb7d2006-06-20 00:31:27 +00001727 bool InferredAllPatternTypes, InferredAllResultTypes;
Chris Lattnera3548492006-06-20 00:18:02 +00001728 do {
1729 // Infer as many types as possible. If we cannot infer all of them, we
1730 // can never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001731 InferredAllPatternTypes = Pattern->InferAllTypes();
Chris Lattnera3548492006-06-20 00:18:02 +00001732
Chris Lattner64906972006-09-21 18:28:27 +00001733 // Infer as many types as possible. If we cannot infer all of them, we
1734 // can never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001735 InferredAllResultTypes = Result->InferAllTypes();
1736
Chris Lattnera3548492006-06-20 00:18:02 +00001737 // Apply the type of the result to the source pattern. This helps us
1738 // resolve cases where the input type is known to be a pointer type (which
1739 // is considered resolved), but the result knows it needs to be 32- or
1740 // 64-bits. Infer the other way for good measure.
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001741 IterateInference = Pattern->getTree(0)->
1742 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
1743 IterateInference |= Result->getTree(0)->
1744 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
Chris Lattnera3548492006-06-20 00:18:02 +00001745 } while (IterateInference);
Chris Lattner186fb7d2006-06-20 00:31:27 +00001746
1747 // Verify that we inferred enough types that we can do something with the
1748 // pattern and result. If these fire the user has to add type casts.
1749 if (!InferredAllPatternTypes)
1750 Pattern->error("Could not infer all types in pattern!");
1751 if (!InferredAllResultTypes)
1752 Result->error("Could not infer all types in pattern result!");
Chris Lattnera3548492006-06-20 00:18:02 +00001753
Chris Lattner09c03392005-11-17 17:43:52 +00001754 // Validate that the input pattern is correct.
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001755 std::map<std::string, TreePatternNode*> InstInputs;
1756 std::map<std::string, TreePatternNode*> InstResults;
1757 std::vector<Record*> InstImpInputs;
1758 std::vector<Record*> InstImpResults;
1759 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
1760 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
Evan Chengbcecf332005-12-17 01:19:28 +00001761 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001762 InstImpInputs, InstImpResults);
Chris Lattnere97603f2005-09-28 19:27:25 +00001763
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001764 // Promote the xform function to be an explicit node if set.
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001765 TreePatternNode *DstPattern = Result->getOnlyTree();
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001766 std::vector<TreePatternNode*> ResultNodeOperands;
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001767 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1768 TreePatternNode *OpNode = DstPattern->getChild(ii);
1769 if (Record *Xform = OpNode->getTransformFn()) {
1770 OpNode->setTransformFn(0);
1771 std::vector<TreePatternNode*> Children;
1772 Children.push_back(OpNode);
1773 OpNode = new TreePatternNode(Xform, Children);
1774 }
1775 ResultNodeOperands.push_back(OpNode);
1776 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00001777 DstPattern = Result->getOnlyTree();
1778 if (!DstPattern->isLeaf())
1779 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1780 ResultNodeOperands);
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001781 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1782 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1783 Temp.InferAllTypes();
1784
Chris Lattnere97603f2005-09-28 19:27:25 +00001785 std::string Reason;
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001786 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
Chris Lattnere97603f2005-09-28 19:27:25 +00001787 Pattern->error("Pattern can never match: " + Reason);
1788
Evan Cheng58e84a62005-12-14 22:02:59 +00001789 PatternsToMatch.
1790 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001791 Pattern->getTree(0),
1792 Temp.getOnlyTree(), InstImpResults,
Evan Chengc81d2a02006-04-19 20:36:09 +00001793 Patterns[i]->getValueAsInt("AddedComplexity")));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001794 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001795}
1796
Chris Lattnere46e17b2005-09-29 19:28:10 +00001797/// CombineChildVariants - Given a bunch of permutations of each child of the
1798/// 'operator' node, put them together in all possible ways.
1799static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001800 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001801 std::vector<TreePatternNode*> &OutVariants,
1802 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001803 // Make sure that each operand has at least one variant to choose from.
1804 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1805 if (ChildVariants[i].empty())
1806 return;
1807
Chris Lattnere46e17b2005-09-29 19:28:10 +00001808 // The end result is an all-pairs construction of the resultant pattern.
1809 std::vector<unsigned> Idxs;
1810 Idxs.resize(ChildVariants.size());
1811 bool NotDone = true;
1812 while (NotDone) {
1813 // Create the variant and add it to the output list.
1814 std::vector<TreePatternNode*> NewChildren;
1815 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1816 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1817 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1818
1819 // Copy over properties.
1820 R->setName(Orig->getName());
1821 R->setPredicateFn(Orig->getPredicateFn());
1822 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001823 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001824
1825 // If this pattern cannot every match, do not include it as a variant.
1826 std::string ErrString;
1827 if (!R->canPatternMatch(ErrString, ISE)) {
1828 delete R;
1829 } else {
1830 bool AlreadyExists = false;
1831
1832 // Scan to see if this pattern has already been emitted. We can get
1833 // duplication due to things like commuting:
1834 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1835 // which are the same pattern. Ignore the dups.
1836 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1837 if (R->isIsomorphicTo(OutVariants[i])) {
1838 AlreadyExists = true;
1839 break;
1840 }
1841
1842 if (AlreadyExists)
1843 delete R;
1844 else
1845 OutVariants.push_back(R);
1846 }
1847
1848 // Increment indices to the next permutation.
1849 NotDone = false;
1850 // Look for something we can increment without causing a wrap-around.
1851 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1852 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1853 NotDone = true; // Found something to increment.
1854 break;
1855 }
1856 Idxs[IdxsIdx] = 0;
1857 }
1858 }
1859}
1860
Chris Lattneraf302912005-09-29 22:36:54 +00001861/// CombineChildVariants - A helper function for binary operators.
1862///
1863static void CombineChildVariants(TreePatternNode *Orig,
1864 const std::vector<TreePatternNode*> &LHS,
1865 const std::vector<TreePatternNode*> &RHS,
1866 std::vector<TreePatternNode*> &OutVariants,
1867 DAGISelEmitter &ISE) {
1868 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1869 ChildVariants.push_back(LHS);
1870 ChildVariants.push_back(RHS);
1871 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1872}
1873
1874
1875static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1876 std::vector<TreePatternNode *> &Children) {
1877 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1878 Record *Operator = N->getOperator();
1879
1880 // Only permit raw nodes.
1881 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1882 N->getTransformFn()) {
1883 Children.push_back(N);
1884 return;
1885 }
1886
1887 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1888 Children.push_back(N->getChild(0));
1889 else
1890 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1891
1892 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1893 Children.push_back(N->getChild(1));
1894 else
1895 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1896}
1897
Chris Lattnere46e17b2005-09-29 19:28:10 +00001898/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1899/// the (potentially recursive) pattern by using algebraic laws.
1900///
1901static void GenerateVariantsOf(TreePatternNode *N,
1902 std::vector<TreePatternNode*> &OutVariants,
1903 DAGISelEmitter &ISE) {
1904 // We cannot permute leaves.
1905 if (N->isLeaf()) {
1906 OutVariants.push_back(N);
1907 return;
1908 }
1909
1910 // Look up interesting info about the node.
Chris Lattner5a1df382006-03-24 23:10:39 +00001911 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001912
1913 // If this node is associative, reassociate.
Evan Cheng94b30402006-10-11 21:02:01 +00001914 if (NodeInfo.hasProperty(SDNPAssociative)) {
Chris Lattneraf302912005-09-29 22:36:54 +00001915 // Reassociate by pulling together all of the linked operators
1916 std::vector<TreePatternNode*> MaximalChildren;
1917 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1918
1919 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1920 // permutations.
1921 if (MaximalChildren.size() == 3) {
1922 // Find the variants of all of our maximal children.
1923 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1924 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1925 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1926 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1927
1928 // There are only two ways we can permute the tree:
1929 // (A op B) op C and A op (B op C)
1930 // Within these forms, we can also permute A/B/C.
1931
1932 // Generate legal pair permutations of A/B/C.
1933 std::vector<TreePatternNode*> ABVariants;
1934 std::vector<TreePatternNode*> BAVariants;
1935 std::vector<TreePatternNode*> ACVariants;
1936 std::vector<TreePatternNode*> CAVariants;
1937 std::vector<TreePatternNode*> BCVariants;
1938 std::vector<TreePatternNode*> CBVariants;
1939 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1940 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1941 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1942 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1943 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1944 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1945
1946 // Combine those into the result: (x op x) op x
1947 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1948 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1949 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1950 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1951 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1952 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1953
1954 // Combine those into the result: x op (x op x)
1955 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1956 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1957 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1958 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1959 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1960 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1961 return;
1962 }
1963 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001964
1965 // Compute permutations of all children.
1966 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1967 ChildVariants.resize(N->getNumChildren());
1968 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1969 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1970
1971 // Build all permutations based on how the children were formed.
1972 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1973
1974 // If this node is commutative, consider the commuted order.
Evan Cheng94b30402006-10-11 21:02:01 +00001975 if (NodeInfo.hasProperty(SDNPCommutative)) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001976 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattner706d2d32006-08-09 16:44:44 +00001977 // Don't count children which are actually register references.
1978 unsigned NC = 0;
1979 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1980 TreePatternNode *Child = N->getChild(i);
1981 if (Child->isLeaf())
1982 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1983 Record *RR = DI->getDef();
1984 if (RR->isSubClassOf("Register"))
1985 continue;
1986 }
1987 NC++;
1988 }
Chris Lattneraf302912005-09-29 22:36:54 +00001989 // Consider the commuted order.
Chris Lattner706d2d32006-08-09 16:44:44 +00001990 if (NC == 2)
1991 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1992 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001993 }
1994}
1995
1996
Chris Lattnere97603f2005-09-28 19:27:25 +00001997// GenerateVariants - Generate variants. For example, commutative patterns can
1998// match multiple ways. Add them to PatternsToMatch as well.
1999void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00002000
Bill Wendlingf5da1332006-12-07 22:21:48 +00002001 DOUT << "Generating instruction variants.\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00002002
2003 // Loop over all of the patterns we've collected, checking to see if we can
2004 // generate variants of the instruction, through the exploitation of
2005 // identities. This permits the target to provide agressive matching without
2006 // the .td file having to contain tons of variants of instructions.
2007 //
2008 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2009 // intentionally do not reconsider these. Any variants of added patterns have
2010 // already been added.
2011 //
2012 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2013 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00002014 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00002015
2016 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00002017 Variants.erase(Variants.begin()); // Remove the original pattern.
2018
2019 if (Variants.empty()) // No variants for this pattern.
2020 continue;
2021
Bill Wendlingf5da1332006-12-07 22:21:48 +00002022 DOUT << "FOUND VARIANTS OF: ";
2023 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2024 DOUT << "\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00002025
2026 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2027 TreePatternNode *Variant = Variants[v];
2028
Bill Wendlingf5da1332006-12-07 22:21:48 +00002029 DOUT << " VAR#" << v << ": ";
2030 DEBUG(Variant->dump());
2031 DOUT << "\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00002032
2033 // Scan to see if an instruction or explicit pattern already matches this.
2034 bool AlreadyExists = false;
2035 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2036 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00002037 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00002038 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00002039 AlreadyExists = true;
2040 break;
2041 }
2042 }
2043 // If we already have it, ignore the variant.
2044 if (AlreadyExists) continue;
2045
2046 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00002047 PatternsToMatch.
2048 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
Evan Cheng59413202006-04-19 18:07:24 +00002049 Variant, PatternsToMatch[i].getDstPattern(),
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002050 PatternsToMatch[i].getDstRegs(),
Evan Chengc81d2a02006-04-19 20:36:09 +00002051 PatternsToMatch[i].getAddedComplexity()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00002052 }
2053
Bill Wendlingf5da1332006-12-07 22:21:48 +00002054 DOUT << "\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00002055 }
Chris Lattnere97603f2005-09-28 19:27:25 +00002056}
2057
Evan Cheng0fc71982005-12-08 02:00:36 +00002058// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
2059// ComplexPattern.
2060static bool NodeIsComplexPattern(TreePatternNode *N)
2061{
2062 return (N->isLeaf() &&
2063 dynamic_cast<DefInit*>(N->getLeafValue()) &&
2064 static_cast<DefInit*>(N->getLeafValue())->getDef()->
2065 isSubClassOf("ComplexPattern"));
2066}
2067
2068// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
2069// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
2070static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
2071 DAGISelEmitter &ISE)
2072{
2073 if (N->isLeaf() &&
2074 dynamic_cast<DefInit*>(N->getLeafValue()) &&
2075 static_cast<DefInit*>(N->getLeafValue())->getDef()->
2076 isSubClassOf("ComplexPattern")) {
2077 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
2078 ->getDef());
2079 }
2080 return NULL;
2081}
2082
Chris Lattner05814af2005-09-28 17:57:56 +00002083/// getPatternSize - Return the 'size' of this pattern. We want to match large
2084/// patterns before small ones. This is used to determine the size of a
2085/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00002086static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng2618d072006-05-17 20:37:59 +00002087 assert((isExtIntegerInVTs(P->getExtTypes()) ||
2088 isExtFloatingPointInVTs(P->getExtTypes()) ||
2089 P->getExtTypeNum(0) == MVT::isVoid ||
2090 P->getExtTypeNum(0) == MVT::Flag ||
2091 P->getExtTypeNum(0) == MVT::iPTR) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +00002092 "Not a valid pattern node to size!");
Evan Cheng6cec34e2006-09-08 07:26:39 +00002093 unsigned Size = 3; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00002094 // If the root node is a ConstantSDNode, increases its size.
2095 // e.g. (set R32:$dst, 0).
2096 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +00002097 Size += 2;
Evan Cheng0fc71982005-12-08 02:00:36 +00002098
2099 // FIXME: This is a hack to statically increase the priority of patterns
2100 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
2101 // Later we can allow complexity / cost for each pattern to be (optionally)
2102 // specified. To get best possible pattern match we'll need to dynamically
2103 // calculate the complexity of all patterns a dag can potentially map to.
2104 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
2105 if (AM)
Evan Cheng6cec34e2006-09-08 07:26:39 +00002106 Size += AM->getNumOperands() * 3;
Chris Lattner3e179802006-02-03 18:06:02 +00002107
2108 // If this node has some predicate function that must match, it adds to the
2109 // complexity of this node.
2110 if (!P->getPredicateFn().empty())
2111 ++Size;
2112
Chris Lattner05814af2005-09-28 17:57:56 +00002113 // Count children in the count if they are also nodes.
2114 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
2115 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00002116 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00002117 Size += getPatternSize(Child, ISE);
2118 else if (Child->isLeaf()) {
2119 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +00002120 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Evan Cheng4a7c2842006-01-06 22:19:44 +00002121 else if (NodeIsComplexPattern(Child))
2122 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00002123 else if (!Child->getPredicateFn().empty())
2124 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00002125 }
Chris Lattner05814af2005-09-28 17:57:56 +00002126 }
2127
2128 return Size;
2129}
2130
2131/// getResultPatternCost - Compute the number of instructions for this pattern.
2132/// This is a temporary hack. We should really include the instruction
2133/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00002134static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00002135 if (P->isLeaf()) return 0;
2136
Evan Chengfbad7082006-02-18 02:33:09 +00002137 unsigned Cost = 0;
2138 Record *Op = P->getOperator();
2139 if (Op->isSubClassOf("Instruction")) {
2140 Cost++;
2141 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
2142 if (II.usesCustomDAGSchedInserter)
2143 Cost += 10;
2144 }
Chris Lattner05814af2005-09-28 17:57:56 +00002145 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00002146 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00002147 return Cost;
2148}
2149
Evan Chenge6f32032006-07-19 00:24:41 +00002150/// getResultPatternCodeSize - Compute the code size of instructions for this
2151/// pattern.
2152static unsigned getResultPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
2153 if (P->isLeaf()) return 0;
2154
2155 unsigned Cost = 0;
2156 Record *Op = P->getOperator();
2157 if (Op->isSubClassOf("Instruction")) {
2158 Cost += Op->getValueAsInt("CodeSize");
2159 }
2160 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2161 Cost += getResultPatternSize(P->getChild(i), ISE);
2162 return Cost;
2163}
2164
Chris Lattner05814af2005-09-28 17:57:56 +00002165// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
2166// In particular, we want to match maximal patterns first and lowest cost within
2167// a particular complexity first.
2168struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00002169 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
2170 DAGISelEmitter &ISE;
2171
Evan Cheng58e84a62005-12-14 22:02:59 +00002172 bool operator()(PatternToMatch *LHS,
2173 PatternToMatch *RHS) {
2174 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
2175 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Evan Chengc81d2a02006-04-19 20:36:09 +00002176 LHSSize += LHS->getAddedComplexity();
2177 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +00002178 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
2179 if (LHSSize < RHSSize) return false;
2180
2181 // If the patterns have equal complexity, compare generated instruction cost
Evan Chenge6f32032006-07-19 00:24:41 +00002182 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), ISE);
2183 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), ISE);
2184 if (LHSCost < RHSCost) return true;
2185 if (LHSCost > RHSCost) return false;
2186
2187 return getResultPatternSize(LHS->getDstPattern(), ISE) <
2188 getResultPatternSize(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00002189 }
2190};
2191
Nate Begeman6510b222005-12-01 04:51:06 +00002192/// getRegisterValueType - Look up and return the first ValueType of specified
2193/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00002194static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00002195 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2196 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00002197 return MVT::Other;
2198}
2199
Chris Lattner72fe91c2005-09-24 00:40:24 +00002200
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002201/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2202/// type information from it.
2203static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00002204 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002205 if (!N->isLeaf())
2206 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2207 RemoveAllTypes(N->getChild(i));
2208}
Chris Lattner72fe91c2005-09-24 00:40:24 +00002209
Chris Lattner0614b622005-11-02 06:49:14 +00002210Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2211 Record *N = Records.getDef(Name);
Chris Lattner5a1df382006-03-24 23:10:39 +00002212 if (!N || !N->isSubClassOf("SDNode")) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00002213 cerr << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner5a1df382006-03-24 23:10:39 +00002214 exit(1);
2215 }
Chris Lattner0614b622005-11-02 06:49:14 +00002216 return N;
2217}
2218
Evan Cheng51fecc82006-01-09 18:27:06 +00002219/// NodeHasProperty - return true if TreePatternNode has the specified
2220/// property.
Evan Cheng94b30402006-10-11 21:02:01 +00002221static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
Evan Cheng51fecc82006-01-09 18:27:06 +00002222 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002223{
Evan Cheng94b30402006-10-11 21:02:01 +00002224 if (N->isLeaf()) {
2225 const ComplexPattern *CP = NodeGetComplexPattern(N, ISE);
2226 if (CP)
2227 return CP->hasProperty(Property);
2228 return false;
2229 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002230 Record *Operator = N->getOperator();
2231 if (!Operator->isSubClassOf("SDNode")) return false;
2232
2233 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00002234 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002235}
2236
Evan Cheng94b30402006-10-11 21:02:01 +00002237static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
Evan Cheng51fecc82006-01-09 18:27:06 +00002238 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002239{
Evan Cheng51fecc82006-01-09 18:27:06 +00002240 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00002241 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00002242
2243 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2244 TreePatternNode *Child = N->getChild(i);
2245 if (PatternHasProperty(Child, Property, ISE))
2246 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002247 }
2248
2249 return false;
2250}
2251
Evan Chengb915f312005-12-09 22:45:35 +00002252class PatternCodeEmitter {
2253private:
2254 DAGISelEmitter &ISE;
2255
Evan Cheng58e84a62005-12-14 22:02:59 +00002256 // Predicates.
2257 ListInit *Predicates;
Evan Cheng59413202006-04-19 18:07:24 +00002258 // Pattern cost.
2259 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +00002260 // Instruction selector pattern.
2261 TreePatternNode *Pattern;
2262 // Matched instruction.
2263 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002264
Evan Chengb915f312005-12-09 22:45:35 +00002265 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00002266 std::map<std::string, std::string> VariableMap;
2267 // Node to operator mapping
2268 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00002269 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002270 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Cheng4326ef52006-10-12 02:08:53 +00002271 // Original input chain(s).
2272 std::vector<std::pair<std::string, std::string> > OrigChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00002273 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +00002274
Evan Cheng676d7312006-08-26 00:59:04 +00002275 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +00002276 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +00002277 /// tested, and if true, the match fails) [when 1], or normal code to emit
2278 /// [when 0], or initialization code to emit [when 2].
2279 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002280 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2281 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +00002282 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +00002283 /// TargetOpcodes - The target specific opcodes used by the resulting
2284 /// instructions.
2285 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +00002286 std::vector<std::string> &TargetVTs;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002287
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002288 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002289 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +00002290 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +00002291 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002292
2293 void emitCheck(const std::string &S) {
2294 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +00002295 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002296 }
2297 void emitCode(const std::string &S) {
2298 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +00002299 GeneratedCode.push_back(std::make_pair(0, S));
2300 }
2301 void emitInit(const std::string &S) {
2302 if (!S.empty())
2303 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002304 }
Evan Chengf5493192006-08-26 01:02:19 +00002305 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002306 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +00002307 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +00002308 }
Evan Chengfceb57a2006-07-15 08:45:20 +00002309 void emitOpcode(const std::string &Opc) {
2310 TargetOpcodes.push_back(Opc);
2311 OpcNo++;
2312 }
Evan Chengf8729402006-07-16 06:12:52 +00002313 void emitVT(const std::string &VT) {
2314 TargetVTs.push_back(VT);
2315 VTNo++;
2316 }
Evan Chengb915f312005-12-09 22:45:35 +00002317public:
Evan Cheng58e84a62005-12-14 22:02:59 +00002318 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2319 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +00002320 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +00002321 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +00002322 std::vector<std::string> &to,
Chris Lattner706d2d32006-08-09 16:44:44 +00002323 std::vector<std::string> &tv)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002324 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +00002325 GeneratedCode(gc), GeneratedDecl(gd),
2326 TargetOpcodes(to), TargetVTs(tv),
Chris Lattner706d2d32006-08-09 16:44:44 +00002327 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00002328
2329 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2330 /// if the match fails. At this point, we already know that the opcode for N
2331 /// matches, and the SDNode for the result has the RootName specified name.
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002332 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2333 const std::string &RootName, const std::string &ChainSuffix,
2334 bool &FoundChain) {
Evan Chenge41bf822006-02-05 06:43:12 +00002335 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00002336 // Emit instruction predicates. Each predicate is just a string for now.
2337 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002338 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00002339 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2340 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2341 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002342 if (!Def->isSubClassOf("Predicate")) {
Jim Laskey16d42c62006-07-11 18:25:13 +00002343#ifndef NDEBUG
2344 Def->dump();
2345#endif
Evan Cheng58e84a62005-12-14 22:02:59 +00002346 assert(0 && "Unknown predicate type!");
2347 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002348 if (!PredicateCheck.empty())
Chris Lattnerbc7fa522006-09-19 00:41:36 +00002349 PredicateCheck += " && ";
Chris Lattner67a202b2006-01-28 20:43:52 +00002350 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00002351 }
2352 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002353
2354 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00002355 }
2356
Evan Chengb915f312005-12-09 22:45:35 +00002357 if (N->isLeaf()) {
2358 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002359 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00002360 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002361 return;
2362 } else if (!NodeIsComplexPattern(N)) {
2363 assert(0 && "Cannot match this as a leaf value!");
2364 abort();
2365 }
2366 }
2367
Chris Lattner488580c2006-01-28 19:06:51 +00002368 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002369 // we already saw this in the pattern, emit code to verify dagness.
2370 if (!N->getName().empty()) {
2371 std::string &VarMapEntry = VariableMap[N->getName()];
2372 if (VarMapEntry.empty()) {
2373 VarMapEntry = RootName;
2374 } else {
2375 // If we get here, this is a second reference to a specific name. Since
2376 // we already have checked that the first reference is valid, we don't
2377 // have to recursively match it, just check that it's the same as the
2378 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002379 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00002380 return;
2381 }
Evan Chengf805c2e2006-01-12 19:35:54 +00002382
2383 if (!N->isLeaf())
2384 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00002385 }
2386
2387
2388 // Emit code to load the child nodes and match their contents recursively.
2389 unsigned OpNo = 0;
Evan Cheng94b30402006-10-11 21:02:01 +00002390 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, ISE);
2391 bool HasChain = PatternHasProperty(N, SDNPHasChain, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00002392 bool EmittedUseCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00002393 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00002394 if (NodeHasChain)
2395 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00002396 if (!isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002397 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002398 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00002399 EmittedUseCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00002400 if (NodeHasChain) {
Evan Chenge41bf822006-02-05 06:43:12 +00002401 // If the immediate use can somehow reach this node through another
2402 // path, then can't fold it either or it will create a cycle.
2403 // e.g. In the following diagram, XX can reach ld through YY. If
2404 // ld is folded into XX, then YY is both a predecessor and a successor
2405 // of XX.
2406 //
2407 // [ld]
2408 // ^ ^
2409 // | |
2410 // / \---
2411 // / [YY]
2412 // | ^
2413 // [XX]-------|
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002414 bool NeedCheck = false;
2415 if (P != Pattern)
2416 NeedCheck = true;
2417 else {
2418 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2419 NeedCheck =
2420 P->getOperator() == ISE.get_intrinsic_void_sdnode() ||
2421 P->getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
2422 P->getOperator() == ISE.get_intrinsic_wo_chain_sdnode() ||
Evan Chengce1381a2006-10-14 08:30:15 +00002423 PInfo.getNumOperands() > 1 ||
Evan Cheng94b30402006-10-11 21:02:01 +00002424 PInfo.hasProperty(SDNPHasChain) ||
2425 PInfo.hasProperty(SDNPInFlag) ||
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002426 PInfo.hasProperty(SDNPOptInFlag);
2427 }
2428
2429 if (NeedCheck) {
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002430 std::string ParentName(RootName.begin(), RootName.end()-1);
Chris Lattner706d2d32006-08-09 16:44:44 +00002431 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
Evan Chengce1381a2006-10-14 08:30:15 +00002432 ".Val, N.Val)");
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002433 }
Evan Chenge41bf822006-02-05 06:43:12 +00002434 }
Evan Chengb915f312005-12-09 22:45:35 +00002435 }
Evan Chenge41bf822006-02-05 06:43:12 +00002436
Evan Chengc15d18c2006-01-27 22:13:45 +00002437 if (NodeHasChain) {
Evan Cheng4326ef52006-10-12 02:08:53 +00002438 if (FoundChain) {
2439 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
2440 "IsChainCompatible(" + ChainName + ".Val, " +
2441 RootName + ".Val))");
2442 OrigChains.push_back(std::make_pair(ChainName, RootName));
2443 } else
Evan Chenge6389932006-07-21 22:19:51 +00002444 FoundChain = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002445 ChainName = "Chain" + ChainSuffix;
Evan Cheng676d7312006-08-26 00:59:04 +00002446 emitInit("SDOperand " + ChainName + " = " + RootName +
Evan Chenge6389932006-07-21 22:19:51 +00002447 ".getOperand(0);");
Evan Cheng1cf6db22006-01-06 00:41:12 +00002448 }
Evan Chengb915f312005-12-09 22:45:35 +00002449 }
2450
Evan Cheng54597732006-01-26 00:22:25 +00002451 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002452 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002453 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002454 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2455 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002456 if (!isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002457 (PatternHasProperty(N, SDNPInFlag, ISE) ||
2458 PatternHasProperty(N, SDNPOptInFlag, ISE) ||
2459 PatternHasProperty(N, SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002460 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002461 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002462 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002463 }
2464 }
2465
Evan Chengd3eea902006-10-09 21:02:17 +00002466 // If there is a node predicate for this, emit the call.
2467 if (!N->getPredicateFn().empty())
2468 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2469
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002470
Chris Lattner39e73f72006-10-11 04:05:55 +00002471 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
2472 // a constant without a predicate fn that has more that one bit set, handle
2473 // this as a special case. This is usually for targets that have special
2474 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
2475 // handling stuff). Using these instructions is often far more efficient
2476 // than materializing the constant. Unfortunately, both the instcombiner
2477 // and the dag combiner can often infer that bits are dead, and thus drop
2478 // them from the mask in the dag. For example, it might turn 'AND X, 255'
2479 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
2480 // to handle this.
2481 if (!N->isLeaf() &&
2482 (N->getOperator()->getName() == "and" ||
2483 N->getOperator()->getName() == "or") &&
2484 N->getChild(1)->isLeaf() &&
2485 N->getChild(1)->getPredicateFn().empty()) {
2486 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
2487 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
2488 emitInit("SDOperand " + RootName + "0" + " = " +
2489 RootName + ".getOperand(" + utostr(0) + ");");
2490 emitInit("SDOperand " + RootName + "1" + " = " +
2491 RootName + ".getOperand(" + utostr(1) + ");");
2492
2493 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
2494 const char *MaskPredicate = N->getOperator()->getName() == "or"
2495 ? "CheckOrMask(" : "CheckAndMask(";
2496 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
2497 RootName + "1), " + itostr(II->getValue()) + ")");
2498
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002499 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
Chris Lattner39e73f72006-10-11 04:05:55 +00002500 ChainSuffix + utostr(0), FoundChain);
2501 return;
2502 }
2503 }
2504 }
2505
Evan Chengb915f312005-12-09 22:45:35 +00002506 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng676d7312006-08-26 00:59:04 +00002507 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002508 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002509
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002510 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002511 ChainSuffix + utostr(OpNo), FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002512 }
2513
Evan Cheng676d7312006-08-26 00:59:04 +00002514 // Handle cases when root is a complex pattern.
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002515 const ComplexPattern *CP;
Evan Cheng676d7312006-08-26 00:59:04 +00002516 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2517 std::string Fn = CP->getSelectFunc();
2518 unsigned NumOps = CP->getNumOperands();
2519 for (unsigned i = 0; i < NumOps; ++i) {
2520 emitDecl("CPTmp" + utostr(i));
2521 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2522 }
Evan Cheng94b30402006-10-11 21:02:01 +00002523 if (CP->hasProperty(SDNPHasChain)) {
2524 emitDecl("CPInChain");
2525 emitDecl("Chain" + ChainSuffix);
2526 emitCode("SDOperand CPInChain;");
2527 emitCode("SDOperand Chain" + ChainSuffix + ";");
2528 }
Evan Cheng676d7312006-08-26 00:59:04 +00002529
Evan Cheng811731e2006-11-08 20:31:10 +00002530 std::string Code = Fn + "(" + RootName + ", " + RootName;
Evan Cheng676d7312006-08-26 00:59:04 +00002531 for (unsigned i = 0; i < NumOps; i++)
2532 Code += ", CPTmp" + utostr(i);
Evan Cheng94b30402006-10-11 21:02:01 +00002533 if (CP->hasProperty(SDNPHasChain)) {
2534 ChainName = "Chain" + ChainSuffix;
2535 Code += ", CPInChain, Chain" + ChainSuffix;
2536 }
Evan Cheng676d7312006-08-26 00:59:04 +00002537 emitCheck(Code + ")");
2538 }
Evan Chengb915f312005-12-09 22:45:35 +00002539 }
Chris Lattner39e73f72006-10-11 04:05:55 +00002540
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002541 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
2542 const std::string &RootName,
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002543 const std::string &ChainSuffix, bool &FoundChain) {
2544 if (!Child->isLeaf()) {
2545 // If it's not a leaf, recursively match.
2546 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2547 emitCheck(RootName + ".getOpcode() == " +
2548 CInfo.getEnumName());
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002549 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
Evan Cheng94b30402006-10-11 21:02:01 +00002550 if (NodeHasProperty(Child, SDNPHasChain, ISE))
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002551 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
2552 } else {
2553 // If this child has a name associated with it, capture it in VarMap. If
2554 // we already saw this in the pattern, emit code to verify dagness.
2555 if (!Child->getName().empty()) {
2556 std::string &VarMapEntry = VariableMap[Child->getName()];
2557 if (VarMapEntry.empty()) {
2558 VarMapEntry = RootName;
2559 } else {
2560 // If we get here, this is a second reference to a specific name.
2561 // Since we already have checked that the first reference is valid,
2562 // we don't have to recursively match it, just check that it's the
2563 // same as the previously named thing.
2564 emitCheck(VarMapEntry + " == " + RootName);
2565 Duplicates.insert(RootName);
2566 return;
2567 }
2568 }
2569
2570 // Handle leaves of various types.
2571 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2572 Record *LeafRec = DI->getDef();
Chris Lattner646085d2006-11-14 21:18:40 +00002573 if (LeafRec->isSubClassOf("RegisterClass") ||
2574 LeafRec->getName() == "ptr_rc") {
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002575 // Handle register references. Nothing to do here.
2576 } else if (LeafRec->isSubClassOf("Register")) {
2577 // Handle register references.
2578 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2579 // Handle complex pattern.
2580 const ComplexPattern *CP = NodeGetComplexPattern(Child, ISE);
2581 std::string Fn = CP->getSelectFunc();
2582 unsigned NumOps = CP->getNumOperands();
2583 for (unsigned i = 0; i < NumOps; ++i) {
2584 emitDecl("CPTmp" + utostr(i));
2585 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2586 }
Evan Cheng94b30402006-10-11 21:02:01 +00002587 if (CP->hasProperty(SDNPHasChain)) {
2588 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(Parent->getOperator());
2589 FoldedChains.push_back(std::make_pair("CPInChain",
2590 PInfo.getNumResults()));
2591 ChainName = "Chain" + ChainSuffix;
2592 emitDecl("CPInChain");
2593 emitDecl(ChainName);
2594 emitCode("SDOperand CPInChain;");
2595 emitCode("SDOperand " + ChainName + ";");
2596 }
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002597
Evan Cheng811731e2006-11-08 20:31:10 +00002598 std::string Code = Fn + "(N, ";
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002599 if (CP->hasProperty(SDNPHasChain)) {
2600 std::string ParentName(RootName.begin(), RootName.end()-1);
Evan Cheng811731e2006-11-08 20:31:10 +00002601 Code += ParentName + ", ";
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002602 }
2603 Code += RootName;
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002604 for (unsigned i = 0; i < NumOps; i++)
2605 Code += ", CPTmp" + utostr(i);
Evan Cheng94b30402006-10-11 21:02:01 +00002606 if (CP->hasProperty(SDNPHasChain))
2607 Code += ", CPInChain, Chain" + ChainSuffix;
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002608 emitCheck(Code + ")");
2609 } else if (LeafRec->getName() == "srcvalue") {
2610 // Place holder for SRCVALUE nodes. Nothing to do here.
2611 } else if (LeafRec->isSubClassOf("ValueType")) {
2612 // Make sure this is the specified value type.
2613 emitCheck("cast<VTSDNode>(" + RootName +
2614 ")->getVT() == MVT::" + LeafRec->getName());
2615 } else if (LeafRec->isSubClassOf("CondCode")) {
2616 // Make sure this is the specified cond code.
2617 emitCheck("cast<CondCodeSDNode>(" + RootName +
2618 ")->get() == ISD::" + LeafRec->getName());
2619 } else {
2620#ifndef NDEBUG
2621 Child->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00002622 cerr << " ";
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002623#endif
2624 assert(0 && "Unknown leaf type!");
2625 }
2626
2627 // If there is a node predicate for this, emit the call.
2628 if (!Child->getPredicateFn().empty())
2629 emitCheck(Child->getPredicateFn() + "(" + RootName +
2630 ".Val)");
2631 } else if (IntInit *II =
2632 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2633 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
2634 unsigned CTmp = TmpNo++;
2635 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2636 RootName + ")->getSignExtended();");
2637
2638 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2639 } else {
2640#ifndef NDEBUG
2641 Child->dump();
2642#endif
2643 assert(0 && "Unknown leaf type!");
2644 }
2645 }
2646 }
Evan Chengb915f312005-12-09 22:45:35 +00002647
2648 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2649 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +00002650 std::vector<std::string>
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002651 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Evan Cheng676d7312006-08-26 00:59:04 +00002652 bool InFlagDecled, bool ResNodeDecled,
2653 bool LikeLeaf = false, bool isRoot = false) {
2654 // List of arguments of getTargetNode() or SelectNodeTo().
2655 std::vector<std::string> NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002656 // This is something selected from the pattern we matched.
2657 if (!N->getName().empty()) {
Evan Chengb915f312005-12-09 22:45:35 +00002658 std::string &Val = VariableMap[N->getName()];
2659 assert(!Val.empty() &&
2660 "Variable referenced but not defined and not caught earlier!");
2661 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2662 // Already selected this operand, just return the tmpval.
Evan Cheng676d7312006-08-26 00:59:04 +00002663 NodeOps.push_back(Val);
2664 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002665 }
2666
2667 const ComplexPattern *CP;
2668 unsigned ResNo = TmpNo++;
Evan Chengb915f312005-12-09 22:45:35 +00002669 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002670 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002671 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002672 switch (N->getTypeNum(0)) {
Chris Lattnerd8a17282007-01-17 07:45:12 +00002673 default:
2674 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
2675 << " type as an immediate constant. Aborting\n";
2676 abort();
Chris Lattner78593132006-01-29 20:01:35 +00002677 case MVT::i1: CastType = "bool"; break;
2678 case MVT::i8: CastType = "unsigned char"; break;
2679 case MVT::i16: CastType = "unsigned short"; break;
2680 case MVT::i32: CastType = "unsigned"; break;
2681 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002682 }
Evan Cheng676d7312006-08-26 00:59:04 +00002683 emitCode("SDOperand Tmp" + utostr(ResNo) +
Evan Chengfceb57a2006-07-15 08:45:20 +00002684 " = CurDAG->getTargetConstant(((" + CastType +
2685 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2686 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002687 NodeOps.push_back("Tmp" + utostr(ResNo));
2688 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2689 // value if used multiple times by this pattern result.
2690 Val = "Tmp"+utostr(ResNo);
Evan Chengbb48e332006-01-12 07:54:57 +00002691 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002692 Record *Op = OperatorMap[N->getName()];
2693 // Transform ExternalSymbol to TargetExternalSymbol
2694 if (Op && Op->getName() == "externalsym") {
Evan Cheng676d7312006-08-26 00:59:04 +00002695 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002696 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002697 Val + ")->getSymbol(), " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002698 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002699 NodeOps.push_back("Tmp" + utostr(ResNo));
Chris Lattner64906972006-09-21 18:28:27 +00002700 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2701 // this value if used multiple times by this pattern result.
Evan Cheng676d7312006-08-26 00:59:04 +00002702 Val = "Tmp"+utostr(ResNo);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002703 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002704 NodeOps.push_back(Val);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002705 }
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00002706 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
2707 || N->getOperator()->getName() == "tglobaltlsaddr")) {
Evan Chengf805c2e2006-01-12 19:35:54 +00002708 Record *Op = OperatorMap[N->getName()];
2709 // Transform GlobalAddress to TargetGlobalAddress
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00002710 if (Op && (Op->getName() == "globaladdr" ||
2711 Op->getName() == "globaltlsaddr")) {
Evan Cheng676d7312006-08-26 00:59:04 +00002712 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002713 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
Evan Cheng2618d072006-05-17 20:37:59 +00002714 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002715 ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002716 NodeOps.push_back("Tmp" + utostr(ResNo));
Chris Lattner64906972006-09-21 18:28:27 +00002717 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2718 // this value if used multiple times by this pattern result.
Evan Cheng676d7312006-08-26 00:59:04 +00002719 Val = "Tmp"+utostr(ResNo);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002720 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002721 NodeOps.push_back(Val);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002722 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002723 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng676d7312006-08-26 00:59:04 +00002724 NodeOps.push_back(Val);
2725 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2726 // value if used multiple times by this pattern result.
2727 Val = "Tmp"+utostr(ResNo);
Evan Chengbb48e332006-01-12 07:54:57 +00002728 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng676d7312006-08-26 00:59:04 +00002729 NodeOps.push_back(Val);
2730 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2731 // value if used multiple times by this pattern result.
2732 Val = "Tmp"+utostr(ResNo);
Evan Chengb915f312005-12-09 22:45:35 +00002733 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
Evan Cheng676d7312006-08-26 00:59:04 +00002734 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
2735 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
2736 NodeOps.push_back("CPTmp" + utostr(i));
Evan Chengb0793f92006-05-25 00:21:44 +00002737 }
Evan Chengb915f312005-12-09 22:45:35 +00002738 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002739 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
Evan Cheng863bf5a2006-03-20 22:53:06 +00002740 // node even if it isn't one. Don't select it.
Evan Cheng676d7312006-08-26 00:59:04 +00002741 if (!LikeLeaf) {
2742 emitCode("AddToISelQueue(" + Val + ");");
Chris Lattner706d2d32006-08-09 16:44:44 +00002743 if (isRoot && N->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +00002744 emitCode("ReplaceUses(N, " + Val + ");");
Evan Cheng06d64702006-08-11 08:59:35 +00002745 emitCode("return NULL;");
Chris Lattner706d2d32006-08-09 16:44:44 +00002746 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00002747 }
Evan Cheng676d7312006-08-26 00:59:04 +00002748 NodeOps.push_back(Val);
Evan Chengb915f312005-12-09 22:45:35 +00002749 }
Evan Cheng676d7312006-08-26 00:59:04 +00002750 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002751 }
Evan Chengb915f312005-12-09 22:45:35 +00002752 if (N->isLeaf()) {
2753 // If this is an explicit register reference, handle it.
2754 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2755 unsigned ResNo = TmpNo++;
2756 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng676d7312006-08-26 00:59:04 +00002757 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002758 ISE.getQualifiedName(DI->getDef()) + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002759 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002760 NodeOps.push_back("Tmp" + utostr(ResNo));
2761 return NodeOps;
Evan Cheng7774be42007-07-05 07:19:45 +00002762 } else if (DI->getDef()->getName() == "zero_reg") {
2763 emitCode("SDOperand Tmp" + utostr(ResNo) +
2764 " = CurDAG->getRegister(0, " +
2765 getEnumName(N->getTypeNum(0)) + ");");
2766 NodeOps.push_back("Tmp" + utostr(ResNo));
2767 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002768 }
2769 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2770 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002771 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng676d7312006-08-26 00:59:04 +00002772 emitCode("SDOperand Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002773 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
Evan Cheng2618d072006-05-17 20:37:59 +00002774 ", " + getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002775 NodeOps.push_back("Tmp" + utostr(ResNo));
2776 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002777 }
2778
Jim Laskey16d42c62006-07-11 18:25:13 +00002779#ifndef NDEBUG
2780 N->dump();
2781#endif
Evan Chengb915f312005-12-09 22:45:35 +00002782 assert(0 && "Unknown leaf type!");
Evan Cheng676d7312006-08-26 00:59:04 +00002783 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002784 }
2785
2786 Record *Op = N->getOperator();
2787 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002788 const CodeGenTarget &CGT = ISE.getTargetInfo();
2789 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002790 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng045953c2006-05-10 00:05:46 +00002791 TreePattern *InstPat = Inst.getPattern();
Evan Chengd23aa5a2007-09-25 01:48:59 +00002792 // FIXME: Assume actual pattern comes before "implicit".
Evan Cheng045953c2006-05-10 00:05:46 +00002793 TreePatternNode *InstPatNode =
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002794 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
2795 : (InstPat ? InstPat->getTree(0) : NULL);
Evan Cheng045953c2006-05-10 00:05:46 +00002796 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
Evan Chengaeb7d4d2007-09-11 19:52:18 +00002797 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
Evan Cheng045953c2006-05-10 00:05:46 +00002798 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002799 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002800 // FIXME: fix how we deal with physical register operands.
Evan Cheng045953c2006-05-10 00:05:46 +00002801 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002802 bool HasImpResults = isRoot && DstRegs.size() > 0;
Evan Cheng045953c2006-05-10 00:05:46 +00002803 bool NodeHasOptInFlag = isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002804 PatternHasProperty(Pattern, SDNPOptInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002805 bool NodeHasInFlag = isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002806 PatternHasProperty(Pattern, SDNPInFlag, ISE);
Evan Chengef61ed32007-09-07 23:59:02 +00002807 bool NodeHasOutFlag = isRoot &&
2808 PatternHasProperty(Pattern, SDNPOutFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002809 bool NodeHasChain = InstPatNode &&
Evan Cheng94b30402006-10-11 21:02:01 +00002810 PatternHasProperty(InstPatNode, SDNPHasChain, ISE);
Evan Cheng3eff89b2006-05-10 02:47:57 +00002811 bool InputHasChain = isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002812 NodeHasProperty(Pattern, SDNPHasChain, ISE);
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002813 unsigned NumResults = Inst.getNumResults();
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002814 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
Evan Cheng4fba2812005-12-20 07:37:41 +00002815
Evan Chengfceb57a2006-07-15 08:45:20 +00002816 if (NodeHasOptInFlag) {
Evan Cheng676d7312006-08-26 00:59:04 +00002817 emitCode("bool HasInFlag = "
Evan Chengf8729402006-07-16 06:12:52 +00002818 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
Evan Chengfceb57a2006-07-15 08:45:20 +00002819 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002820 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +00002821 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
Evan Cheng4fba2812005-12-20 07:37:41 +00002822
Evan Cheng823b7522006-01-19 21:57:10 +00002823 // How many results is this pattern expected to produce?
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002824 unsigned NumPatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +00002825 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2826 MVT::ValueType VT = Pattern->getTypeNum(i);
2827 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002828 NumPatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +00002829 }
2830
Evan Cheng4326ef52006-10-12 02:08:53 +00002831 if (OrigChains.size() > 0) {
2832 // The original input chain is being ignored. If it is not just
2833 // pointing to the op that's being folded, we should create a
2834 // TokenFactor with it and the chain of the folded op as the new chain.
2835 // We could potentially be doing multiple levels of folding, in that
2836 // case, the TokenFactor can have more operands.
2837 emitCode("SmallVector<SDOperand, 8> InChains;");
2838 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
2839 emitCode("if (" + OrigChains[i].first + ".Val != " +
2840 OrigChains[i].second + ".Val) {");
2841 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
2842 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
2843 emitCode("}");
2844 }
2845 emitCode("AddToISelQueue(" + ChainName + ");");
2846 emitCode("InChains.push_back(" + ChainName + ");");
2847 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
2848 "&InChains[0], InChains.size());");
2849 }
2850
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002851 // Loop over all of the operands of the instruction pattern, emitting code
2852 // to fill them all in. The node 'N' usually has number children equal to
2853 // the number of input operands of the instruction. However, in cases
2854 // where there are predicate operands for an instruction, we need to fill
2855 // in the 'execute always' values. Match up the node operands to the
2856 // instruction operands to do this.
Evan Cheng676d7312006-08-26 00:59:04 +00002857 std::vector<std::string> AllOps;
Evan Cheng39376d02007-05-15 01:19:51 +00002858 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002859 for (unsigned ChildNo = 0, InstOpNo = NumResults;
2860 InstOpNo != II.OperandList.size(); ++InstOpNo) {
2861 std::vector<std::string> Ops;
2862
Evan Cheng59039632007-05-08 21:04:07 +00002863 // If this is a normal operand or a predicate operand without
2864 // 'execute always', emit it.
2865 Record *OperandNode = II.OperandList[InstOpNo].Rec;
Evan Chenga9559392007-07-06 01:05:26 +00002866 if ((!OperandNode->isSubClassOf("PredicateOperand") &&
2867 !OperandNode->isSubClassOf("OptionalDefOperand")) ||
2868 ISE.getDefaultOperand(OperandNode).DefaultOps.empty()) {
Evan Cheng30729b42007-09-17 22:26:41 +00002869 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002870 InFlagDecled, ResNodeDecled);
2871 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
2872 ++ChildNo;
2873 } else {
Evan Chenga9559392007-07-06 01:05:26 +00002874 // Otherwise, this is a predicate or optional def operand, emit the
2875 // 'default ops' operands.
2876 const DAGDefaultOperand &DefaultOp =
2877 ISE.getDefaultOperand(II.OperandList[InstOpNo].Rec);
2878 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
Evan Cheng30729b42007-09-17 22:26:41 +00002879 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002880 InFlagDecled, ResNodeDecled);
2881 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
Evan Cheng39376d02007-05-15 01:19:51 +00002882 NumEAInputs += Ops.size();
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002883 }
2884 }
Evan Chengb915f312005-12-09 22:45:35 +00002885 }
2886
Evan Chengb915f312005-12-09 22:45:35 +00002887 // Emit all the chain and CopyToReg stuff.
Evan Cheng045953c2006-05-10 00:05:46 +00002888 bool ChainEmitted = NodeHasChain;
2889 if (NodeHasChain)
Evan Cheng676d7312006-08-26 00:59:04 +00002890 emitCode("AddToISelQueue(" + ChainName + ");");
Evan Chengbc6b86a2006-06-14 19:27:50 +00002891 if (NodeHasInFlag || HasImpInputs)
Evan Cheng676d7312006-08-26 00:59:04 +00002892 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
2893 InFlagDecled, ResNodeDecled, true);
Evan Chengf037ca62006-08-27 08:11:28 +00002894 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
Evan Cheng676d7312006-08-26 00:59:04 +00002895 if (!InFlagDecled) {
2896 emitCode("SDOperand InFlag(0, 0);");
2897 InFlagDecled = true;
2898 }
Evan Chengf037ca62006-08-27 08:11:28 +00002899 if (NodeHasOptInFlag) {
2900 emitCode("if (HasInFlag) {");
2901 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
2902 emitCode(" AddToISelQueue(InFlag);");
2903 emitCode("}");
2904 }
Evan Chengbc6b86a2006-06-14 19:27:50 +00002905 }
Evan Chengb915f312005-12-09 22:45:35 +00002906
Evan Chengb915f312005-12-09 22:45:35 +00002907 unsigned ResNo = TmpNo++;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002908 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
Evan Chengef61ed32007-09-07 23:59:02 +00002909 NodeHasOptInFlag || HasImpResults) {
Evan Chenge945f4d2006-06-14 22:22:20 +00002910 std::string Code;
2911 std::string Code2;
2912 std::string NodeName;
2913 if (!isRoot) {
2914 NodeName = "Tmp" + utostr(ResNo);
Dan Gohmana6a1ab32007-07-24 22:58:00 +00002915 Code2 = "SDOperand " + NodeName + "(";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002916 } else {
Evan Chenge945f4d2006-06-14 22:22:20 +00002917 NodeName = "ResNode";
Lauro Ramos Venancio195c6c22007-04-26 17:03:22 +00002918 if (!ResNodeDecled) {
Evan Cheng676d7312006-08-26 00:59:04 +00002919 Code2 = "SDNode *" + NodeName + " = ";
Lauro Ramos Venancio195c6c22007-04-26 17:03:22 +00002920 ResNodeDecled = true;
2921 } else
Evan Cheng676d7312006-08-26 00:59:04 +00002922 Code2 = NodeName + " = ";
Evan Chengbcecf332005-12-17 01:19:28 +00002923 }
Evan Chengf037ca62006-08-27 08:11:28 +00002924
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002925 Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
Evan Chengf037ca62006-08-27 08:11:28 +00002926 unsigned OpsNo = OpcNo;
Evan Chengfceb57a2006-07-15 08:45:20 +00002927 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
Evan Chenge945f4d2006-06-14 22:22:20 +00002928
2929 // Output order: results, chain, flags
2930 // Result types.
Evan Chengf8729402006-07-16 06:12:52 +00002931 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
2932 Code += ", VT" + utostr(VTNo);
2933 emitVT(getEnumName(N->getTypeNum(0)));
2934 }
Evan Chengef61ed32007-09-07 23:59:02 +00002935 // Add types for implicit results in physical registers, scheduler will
2936 // care of adding copyfromreg nodes.
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002937 for (unsigned i = 0; i < NumDstRegs; i++) {
2938 Record *RR = DstRegs[i];
2939 if (RR->isSubClassOf("Register")) {
2940 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2941 Code += ", " + getEnumName(RVT);
Evan Chengef61ed32007-09-07 23:59:02 +00002942 }
2943 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002944 if (NodeHasChain)
2945 Code += ", MVT::Other";
2946 if (NodeHasOutFlag)
2947 Code += ", MVT::Flag";
2948
Chris Lattner7c3a96b2006-11-14 18:41:38 +00002949 // Figure out how many fixed inputs the node has. This is important to
2950 // know which inputs are the variable ones if present.
2951 unsigned NumInputs = AllOps.size();
2952 NumInputs += NodeHasChain;
2953
Evan Chenge945f4d2006-06-14 22:22:20 +00002954 // Inputs.
Evan Chengf037ca62006-08-27 08:11:28 +00002955 if (HasVarOps) {
2956 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
2957 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
2958 AllOps.clear();
Evan Chenge945f4d2006-06-14 22:22:20 +00002959 }
2960
2961 if (HasVarOps) {
Chris Lattner7c3a96b2006-11-14 18:41:38 +00002962 // Figure out whether any operands at the end of the op list are not
2963 // part of the variable section.
2964 std::string EndAdjust;
Evan Chenge945f4d2006-06-14 22:22:20 +00002965 if (NodeHasInFlag || HasImpInputs)
Chris Lattner7c3a96b2006-11-14 18:41:38 +00002966 EndAdjust = "-1"; // Always has one flag.
2967 else if (NodeHasOptInFlag)
2968 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
2969
Evan Cheng39376d02007-05-15 01:19:51 +00002970 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
Chris Lattner7c3a96b2006-11-14 18:41:38 +00002971 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
2972
Evan Cheng676d7312006-08-26 00:59:04 +00002973 emitCode(" AddToISelQueue(N.getOperand(i));");
Evan Chengf037ca62006-08-27 08:11:28 +00002974 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
Evan Chenge945f4d2006-06-14 22:22:20 +00002975 emitCode("}");
2976 }
2977
2978 if (NodeHasChain) {
2979 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +00002980 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
Evan Chenge945f4d2006-06-14 22:22:20 +00002981 else
Evan Chengf037ca62006-08-27 08:11:28 +00002982 AllOps.push_back(ChainName);
Evan Chenge945f4d2006-06-14 22:22:20 +00002983 }
2984
Evan Chengf037ca62006-08-27 08:11:28 +00002985 if (HasVarOps) {
2986 if (NodeHasInFlag || HasImpInputs)
2987 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2988 else if (NodeHasOptInFlag) {
2989 emitCode("if (HasInFlag)");
2990 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2991 }
2992 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
2993 ".size()";
2994 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002995 AllOps.push_back("InFlag");
Evan Chenge945f4d2006-06-14 22:22:20 +00002996
Evan Chengf037ca62006-08-27 08:11:28 +00002997 unsigned NumOps = AllOps.size();
2998 if (NumOps) {
2999 if (!NodeHasOptInFlag && NumOps < 4) {
3000 for (unsigned i = 0; i != NumOps; ++i)
3001 Code += ", " + AllOps[i];
3002 } else {
3003 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
3004 for (unsigned i = 0; i != NumOps; ++i) {
3005 OpsCode += AllOps[i];
3006 if (i != NumOps-1)
3007 OpsCode += ", ";
3008 }
3009 emitCode(OpsCode + " };");
3010 Code += ", Ops" + utostr(OpsNo) + ", ";
3011 if (NodeHasOptInFlag) {
3012 Code += "HasInFlag ? ";
3013 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
3014 } else
3015 Code += utostr(NumOps);
3016 }
3017 }
3018
Evan Chenge945f4d2006-06-14 22:22:20 +00003019 if (!isRoot)
3020 Code += "), 0";
3021 emitCode(Code2 + Code + ");");
3022
3023 if (NodeHasChain)
3024 // Remember which op produces the chain.
3025 if (!isRoot)
3026 emitCode(ChainName + " = SDOperand(" + NodeName +
Evan Cheng85dbe1a2007-09-12 23:30:14 +00003027 ".Val, " + utostr(NumResults+NumDstRegs) + ");");
Evan Chenge945f4d2006-06-14 22:22:20 +00003028 else
3029 emitCode(ChainName + " = SDOperand(" + NodeName +
Evan Cheng85dbe1a2007-09-12 23:30:14 +00003030 ", " + utostr(NumResults+NumDstRegs) + ");");
Evan Cheng1b80f4d2005-12-19 07:18:51 +00003031
Evan Cheng676d7312006-08-26 00:59:04 +00003032 if (!isRoot) {
3033 NodeOps.push_back("Tmp" + utostr(ResNo));
3034 return NodeOps;
3035 }
Evan Cheng045953c2006-05-10 00:05:46 +00003036
Evan Cheng06d64702006-08-11 08:59:35 +00003037 bool NeedReplace = false;
Evan Cheng676d7312006-08-26 00:59:04 +00003038 if (NodeHasOutFlag) {
3039 if (!InFlagDecled) {
Dan Gohmana6a1ab32007-07-24 22:58:00 +00003040 emitCode("SDOperand InFlag(ResNode, " +
Evan Cheng30729b42007-09-17 22:26:41 +00003041 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00003042 InFlagDecled = true;
3043 } else
3044 emitCode("InFlag = SDOperand(ResNode, " +
Evan Cheng30729b42007-09-17 22:26:41 +00003045 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00003046 }
Evan Cheng4fba2812005-12-20 07:37:41 +00003047
Evan Cheng97938882005-12-22 02:24:50 +00003048 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00003049 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00003050 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Chris Lattner706d2d32006-08-09 16:44:44 +00003051 emitCode("ReplaceUses(SDOperand(" +
Evan Cheng67212a02006-02-09 22:12:27 +00003052 FoldedChains[j].first + ".Val, " +
Chris Lattner706d2d32006-08-09 16:44:44 +00003053 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
Evan Cheng85dbe1a2007-09-12 23:30:14 +00003054 utostr(NumResults+NumDstRegs) + "));");
Evan Cheng06d64702006-08-11 08:59:35 +00003055 NeedReplace = true;
Evan Chengb915f312005-12-09 22:45:35 +00003056 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00003057
Evan Cheng06d64702006-08-11 08:59:35 +00003058 if (NodeHasOutFlag) {
Chris Lattner706d2d32006-08-09 16:44:44 +00003059 emitCode("ReplaceUses(SDOperand(N.Val, " +
Evan Cheng30729b42007-09-17 22:26:41 +00003060 utostr(NumPatResults + (unsigned)InputHasChain)
3061 +"), InFlag);");
Evan Cheng06d64702006-08-11 08:59:35 +00003062 NeedReplace = true;
3063 }
3064
Evan Cheng30729b42007-09-17 22:26:41 +00003065 if (NeedReplace && InputHasChain)
3066 emitCode("ReplaceUses(SDOperand(N.Val, " +
3067 utostr(NumPatResults) + "), SDOperand(" + ChainName
3068 + ".Val, " + ChainName + ".ResNo" + "));");
Evan Cheng97938882005-12-22 02:24:50 +00003069
Evan Chenged66e852006-03-09 08:19:11 +00003070 // User does not expect the instruction would produce a chain!
Evan Cheng06d64702006-08-11 08:59:35 +00003071 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
Evan Cheng9ade2182006-08-26 05:34:46 +00003072 ;
Evan Cheng3eff89b2006-05-10 02:47:57 +00003073 } else if (InputHasChain && !NodeHasChain) {
3074 // One of the inner node produces a chain.
Evan Cheng9ade2182006-08-26 05:34:46 +00003075 if (NodeHasOutFlag)
Evan Cheng85dbe1a2007-09-12 23:30:14 +00003076 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
Evan Cheng06d64702006-08-11 08:59:35 +00003077 "), SDOperand(ResNode, N.ResNo-1));");
Evan Cheng85dbe1a2007-09-12 23:30:14 +00003078 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
Evan Cheng06d64702006-08-11 08:59:35 +00003079 "), " + ChainName + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00003080 }
Evan Cheng06d64702006-08-11 08:59:35 +00003081
Evan Cheng30729b42007-09-17 22:26:41 +00003082 emitCode("return ResNode;");
Evan Chengb915f312005-12-09 22:45:35 +00003083 } else {
Evan Cheng9ade2182006-08-26 05:34:46 +00003084 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
Evan Chengfceb57a2006-07-15 08:45:20 +00003085 utostr(OpcNo);
Nate Begemanb73628b2005-12-30 00:12:56 +00003086 if (N->getTypeNum(0) != MVT::isVoid)
Evan Chengf8729402006-07-16 06:12:52 +00003087 Code += ", VT" + utostr(VTNo);
Evan Cheng54597732006-01-26 00:22:25 +00003088 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00003089 Code += ", MVT::Flag";
Evan Chengf037ca62006-08-27 08:11:28 +00003090
3091 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
3092 AllOps.push_back("InFlag");
3093
3094 unsigned NumOps = AllOps.size();
3095 if (NumOps) {
3096 if (!NodeHasOptInFlag && NumOps < 4) {
3097 for (unsigned i = 0; i != NumOps; ++i)
3098 Code += ", " + AllOps[i];
3099 } else {
3100 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
3101 for (unsigned i = 0; i != NumOps; ++i) {
3102 OpsCode += AllOps[i];
3103 if (i != NumOps-1)
3104 OpsCode += ", ";
3105 }
3106 emitCode(OpsCode + " };");
3107 Code += ", Ops" + utostr(OpcNo) + ", ";
3108 Code += utostr(NumOps);
3109 }
3110 }
Evan Cheng95514ba2006-08-26 08:00:10 +00003111 emitCode(Code + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00003112 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
3113 if (N->getTypeNum(0) != MVT::isVoid)
3114 emitVT(getEnumName(N->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00003115 }
Evan Cheng4fba2812005-12-20 07:37:41 +00003116
Evan Cheng676d7312006-08-26 00:59:04 +00003117 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00003118 } else if (Op->isSubClassOf("SDNodeXForm")) {
3119 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng863bf5a2006-03-20 22:53:06 +00003120 // PatLeaf node - the operand may or may not be a leaf node. But it should
3121 // behave like one.
Evan Cheng676d7312006-08-26 00:59:04 +00003122 std::vector<std::string> Ops =
Evan Cheng30729b42007-09-17 22:26:41 +00003123 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
Evan Cheng676d7312006-08-26 00:59:04 +00003124 ResNodeDecled, true);
Evan Chengb915f312005-12-09 22:45:35 +00003125 unsigned ResNo = TmpNo++;
Evan Cheng676d7312006-08-26 00:59:04 +00003126 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
3127 + "(" + Ops.back() + ".Val);");
3128 NodeOps.push_back("Tmp" + utostr(ResNo));
Evan Cheng9ade2182006-08-26 05:34:46 +00003129 if (isRoot)
3130 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00003131 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00003132 } else {
3133 N->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00003134 cerr << "\n";
Chris Lattner7893f132006-01-11 01:33:49 +00003135 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00003136 }
3137 }
3138
Chris Lattner488580c2006-01-28 19:06:51 +00003139 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
3140 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00003141 /// 'Pat' may be missing types. If we find an unresolved type to add a check
3142 /// for, this returns true otherwise false if Pat has all types.
3143 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +00003144 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00003145 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +00003146 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +00003147 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00003148 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +00003149 // The top level node type is checked outside of the select function.
3150 if (!isRoot)
3151 emitCheck(Prefix + ".Val->getValueType(0) == " +
3152 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00003153 return true;
Evan Chengb915f312005-12-09 22:45:35 +00003154 }
3155
Evan Cheng51fecc82006-01-09 18:27:06 +00003156 unsigned OpNo =
Evan Cheng94b30402006-10-11 21:02:01 +00003157 (unsigned) NodeHasProperty(Pat, SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00003158 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
3159 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
3160 Prefix + utostr(OpNo)))
3161 return true;
3162 return false;
3163 }
3164
3165private:
Evan Cheng54597732006-01-26 00:22:25 +00003166 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00003167 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00003168 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +00003169 bool &ChainEmitted, bool &InFlagDecled,
3170 bool &ResNodeDecled, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00003171 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00003172 unsigned OpNo =
Evan Cheng94b30402006-10-11 21:02:01 +00003173 (unsigned) NodeHasProperty(N, SDNPHasChain, ISE);
3174 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00003175 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
3176 TreePatternNode *Child = N->getChild(i);
3177 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +00003178 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
3179 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +00003180 } else {
3181 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00003182 if (!Child->getName().empty()) {
3183 std::string Name = RootName + utostr(OpNo);
3184 if (Duplicates.find(Name) != Duplicates.end())
3185 // A duplicate! Do not emit a copy for this node.
3186 continue;
3187 }
3188
Evan Chengb915f312005-12-09 22:45:35 +00003189 Record *RR = DI->getDef();
3190 if (RR->isSubClassOf("Register")) {
3191 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00003192 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +00003193 if (!InFlagDecled) {
3194 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
3195 InFlagDecled = true;
3196 } else
3197 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
3198 emitCode("AddToISelQueue(InFlag);");
Evan Chengb2c6d492006-01-11 22:16:13 +00003199 } else {
3200 if (!ChainEmitted) {
Evan Cheng676d7312006-08-26 00:59:04 +00003201 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00003202 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00003203 ChainEmitted = true;
3204 }
Evan Cheng676d7312006-08-26 00:59:04 +00003205 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
3206 if (!InFlagDecled) {
3207 emitCode("SDOperand InFlag(0, 0);");
3208 InFlagDecled = true;
3209 }
3210 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
3211 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Cheng7a33db02006-08-26 07:39:28 +00003212 ", " + ISE.getQualifiedName(RR) +
3213 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00003214 ResNodeDecled = true;
Evan Cheng67212a02006-02-09 22:12:27 +00003215 emitCode(ChainName + " = SDOperand(ResNode, 0);");
3216 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00003217 }
3218 }
3219 }
3220 }
3221 }
Evan Cheng54597732006-01-26 00:22:25 +00003222
Evan Cheng676d7312006-08-26 00:59:04 +00003223 if (HasInFlag) {
3224 if (!InFlagDecled) {
3225 emitCode("SDOperand InFlag = " + RootName +
3226 ".getOperand(" + utostr(OpNo) + ");");
3227 InFlagDecled = true;
3228 } else
3229 emitCode("InFlag = " + RootName +
3230 ".getOperand(" + utostr(OpNo) + ");");
3231 emitCode("AddToISelQueue(InFlag);");
3232 }
Evan Chengb915f312005-12-09 22:45:35 +00003233 }
3234};
3235
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00003236/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
3237/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00003238/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00003239void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00003240 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00003241 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00003242 std::vector<std::string> &TargetOpcodes,
Evan Chengf5493192006-08-26 01:02:19 +00003243 std::vector<std::string> &TargetVTs) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003244 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
3245 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00003246 GeneratedCode, GeneratedDecl,
Chris Lattner706d2d32006-08-09 16:44:44 +00003247 TargetOpcodes, TargetVTs);
Evan Chengb915f312005-12-09 22:45:35 +00003248
Chris Lattner8fc35682005-09-23 23:16:51 +00003249 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00003250 bool FoundChain = false;
Evan Cheng13e9e9c2006-10-16 06:33:44 +00003251 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00003252
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003253 // TP - Get *SOME* tree pattern, we don't care which.
3254 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00003255
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003256 // At this point, we know that we structurally match the pattern, but the
3257 // types of the nodes may not match. Figure out the fewest number of type
3258 // comparisons we need to emit. For example, if there is only one integer
3259 // type supported by a target, there should be no type comparisons at all for
3260 // integer patterns!
3261 //
3262 // To figure out the fewest number of type checks needed, clone the pattern,
3263 // remove the types, then perform type inference on the pattern as a whole.
3264 // If there are unresolved types, emit an explicit check for those types,
3265 // apply the type to the tree, then rerun type inference. Iterate until all
3266 // types are resolved.
3267 //
Evan Cheng58e84a62005-12-14 22:02:59 +00003268 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003269 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00003270
3271 do {
3272 // Resolve/propagate as many types as possible.
3273 try {
3274 bool MadeChange = true;
3275 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00003276 MadeChange = Pat->ApplyTypeConstraints(TP,
3277 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00003278 } catch (...) {
3279 assert(0 && "Error: could not find consistent types for something we"
3280 " already decided was ok!");
3281 abort();
3282 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003283
Chris Lattner7e82f132005-10-15 21:34:21 +00003284 // Insert a check for an unresolved type and add it to the tree. If we find
3285 // an unresolved type to add a check for, this returns true and we iterate,
3286 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00003287 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00003288
Evan Cheng85dbe1a2007-09-12 23:30:14 +00003289 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Cheng30729b42007-09-17 22:26:41 +00003290 false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003291 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00003292}
3293
Chris Lattner24e00a42006-01-29 04:41:05 +00003294/// EraseCodeLine - Erase one code line from all of the patterns. If removing
3295/// a line causes any of them to be empty, remove them and return true when
3296/// done.
3297static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00003298 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00003299 &Patterns) {
3300 bool ErasedPatterns = false;
3301 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3302 Patterns[i].second.pop_back();
3303 if (Patterns[i].second.empty()) {
3304 Patterns.erase(Patterns.begin()+i);
3305 --i; --e;
3306 ErasedPatterns = true;
3307 }
3308 }
3309 return ErasedPatterns;
3310}
3311
Chris Lattner8bc74722006-01-29 04:25:26 +00003312/// EmitPatterns - Emit code for at least one pattern, but try to group common
3313/// code together between the patterns.
3314void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00003315 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00003316 &Patterns, unsigned Indent,
3317 std::ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00003318 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00003319 typedef std::vector<CodeLine> CodeList;
3320 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3321
3322 if (Patterns.empty()) return;
3323
Chris Lattner24e00a42006-01-29 04:41:05 +00003324 // Figure out how many patterns share the next code line. Explicitly copy
3325 // FirstCodeLine so that we don't invalidate a reference when changing
3326 // Patterns.
3327 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00003328 unsigned LastMatch = Patterns.size()-1;
3329 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3330 --LastMatch;
3331
3332 // If not all patterns share this line, split the list into two pieces. The
3333 // first chunk will use this line, the second chunk won't.
3334 if (LastMatch != 0) {
3335 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3336 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3337
3338 // FIXME: Emit braces?
3339 if (Shared.size() == 1) {
3340 PatternToMatch &Pattern = *Shared.back().first;
3341 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3342 Pattern.getSrcPattern()->print(OS);
3343 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3344 Pattern.getDstPattern()->print(OS);
3345 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003346 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003347 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003348 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003349 << " cost = "
Evan Chenge6f32032006-07-19 00:24:41 +00003350 << getResultPatternCost(Pattern.getDstPattern(), *this)
3351 << " size = "
3352 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003353 }
Evan Cheng676d7312006-08-26 00:59:04 +00003354 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00003355 OS << std::string(Indent, ' ') << "{\n";
3356 Indent += 2;
3357 }
3358 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00003359 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00003360 Indent -= 2;
3361 OS << std::string(Indent, ' ') << "}\n";
3362 }
3363
3364 if (Other.size() == 1) {
3365 PatternToMatch &Pattern = *Other.back().first;
3366 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3367 Pattern.getSrcPattern()->print(OS);
3368 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3369 Pattern.getDstPattern()->print(OS);
3370 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003371 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003372 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003373 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003374 << " cost = "
Chris Lattner706d2d32006-08-09 16:44:44 +00003375 << getResultPatternCost(Pattern.getDstPattern(), *this)
3376 << " size = "
3377 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003378 }
3379 EmitPatterns(Other, Indent, OS);
3380 return;
3381 }
3382
Chris Lattner24e00a42006-01-29 04:41:05 +00003383 // Remove this code from all of the patterns that share it.
3384 bool ErasedPatterns = EraseCodeLine(Patterns);
3385
Evan Cheng676d7312006-08-26 00:59:04 +00003386 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00003387
3388 // Otherwise, every pattern in the list has this line. Emit it.
3389 if (!isPredicate) {
3390 // Normal code.
3391 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3392 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00003393 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3394
3395 // If the next code line is another predicate, and if all of the pattern
3396 // in this group share the same next line, emit it inline now. Do this
3397 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00003398 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Chris Lattner24e00a42006-01-29 04:41:05 +00003399 // Check that all of fhe patterns in Patterns end with the same predicate.
3400 bool AllEndWithSamePredicate = true;
3401 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3402 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3403 AllEndWithSamePredicate = false;
3404 break;
3405 }
3406 // If all of the predicates aren't the same, we can't share them.
3407 if (!AllEndWithSamePredicate) break;
3408
3409 // Otherwise we can. Emit it shared now.
3410 OS << " &&\n" << std::string(Indent+4, ' ')
3411 << Patterns.back().second.back().second;
3412 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00003413 }
Chris Lattner24e00a42006-01-29 04:41:05 +00003414
3415 OS << ") {\n";
3416 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00003417 }
3418
3419 EmitPatterns(Patterns, Indent, OS);
3420
3421 if (isPredicate)
3422 OS << std::string(Indent-2, ' ') << "}\n";
3423}
3424
Evan Cheng892aaf82006-11-08 23:01:03 +00003425static std::string getOpcodeName(Record *Op, DAGISelEmitter &ISE) {
3426 const SDNodeInfo &OpcodeInfo = ISE.getSDNodeInfo(Op);
3427 return OpcodeInfo.getEnumName();
3428}
Chris Lattner8bc74722006-01-29 04:25:26 +00003429
Evan Cheng892aaf82006-11-08 23:01:03 +00003430static std::string getLegalCName(std::string OpName) {
3431 std::string::size_type pos = OpName.find("::");
3432 if (pos != std::string::npos)
3433 OpName.replace(pos, 2, "_");
3434 return OpName;
Chris Lattner37481472005-09-26 21:59:35 +00003435}
3436
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003437void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerf7560ed2006-11-20 18:54:33 +00003438 // Get the namespace to insert instructions into. Make sure not to pick up
3439 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
3440 // instruction or something.
3441 std::string InstNS;
3442 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
3443 e = Target.inst_end(); i != e; ++i) {
3444 InstNS = i->second.Namespace;
3445 if (InstNS != "TargetInstrInfo")
3446 break;
3447 }
3448
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003449 if (!InstNS.empty()) InstNS += "::";
3450
Chris Lattner602f6922006-01-04 00:25:00 +00003451 // Group the patterns by their top-level opcodes.
Evan Cheng892aaf82006-11-08 23:01:03 +00003452 std::map<std::string, std::vector<PatternToMatch*> > PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00003453 // All unique target node emission functions.
3454 std::map<std::string, unsigned> EmitFunctions;
Chris Lattner602f6922006-01-04 00:25:00 +00003455 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3456 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3457 if (!Node->isLeaf()) {
Evan Cheng892aaf82006-11-08 23:01:03 +00003458 PatternsByOpcode[getOpcodeName(Node->getOperator(), *this)].
3459 push_back(&PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003460 } else {
3461 const ComplexPattern *CP;
Chris Lattner9c5d4de2006-11-03 01:11:05 +00003462 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Evan Cheng892aaf82006-11-08 23:01:03 +00003463 PatternsByOpcode[getOpcodeName(getSDNodeNamed("imm"), *this)].
3464 push_back(&PatternsToMatch[i]);
Reid Spencer63fd6ad2006-11-02 21:07:40 +00003465 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
Chris Lattner602f6922006-01-04 00:25:00 +00003466 std::vector<Record*> OpNodes = CP->getRootNodes();
3467 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Evan Cheng892aaf82006-11-08 23:01:03 +00003468 PatternsByOpcode[getOpcodeName(OpNodes[j], *this)]
3469 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], *this)].begin(),
3470 &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003471 }
3472 } else {
Bill Wendlingf5da1332006-12-07 22:21:48 +00003473 cerr << "Unrecognized opcode '";
Chris Lattner602f6922006-01-04 00:25:00 +00003474 Node->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00003475 cerr << "' on tree pattern '";
3476 cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3477 cerr << "'!\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003478 exit(1);
3479 }
3480 }
3481 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003482
3483 // For each opcode, there might be multiple select functions, one per
3484 // ValueType of the node (or its first operand if it doesn't produce a
3485 // non-chain result.
3486 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
3487
Chris Lattner602f6922006-01-04 00:25:00 +00003488 // Emit one Select_* method for each top-level opcode. We do this instead of
3489 // emitting one giant switch statement to support compilers where this will
3490 // result in the recursive functions taking less stack space.
Evan Cheng892aaf82006-11-08 23:01:03 +00003491 for (std::map<std::string, std::vector<PatternToMatch*> >::iterator
3492 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
3493 PBOI != E; ++PBOI) {
3494 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00003495 std::vector<PatternToMatch*> &PatternsOfOp = PBOI->second;
3496 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
3497
Chris Lattner602f6922006-01-04 00:25:00 +00003498 // We want to emit all of the matching code now. However, we want to emit
3499 // the matches in order of minimal cost. Sort the patterns so the least
3500 // cost one is at the start.
Chris Lattner706d2d32006-08-09 16:44:44 +00003501 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
Chris Lattner602f6922006-01-04 00:25:00 +00003502 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00003503
Chris Lattner706d2d32006-08-09 16:44:44 +00003504 // Split them into groups by type.
3505 std::map<MVT::ValueType, std::vector<PatternToMatch*> > PatternsByType;
3506 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
3507 PatternToMatch *Pat = PatternsOfOp[i];
3508 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner706d2d32006-08-09 16:44:44 +00003509 MVT::ValueType VT = SrcPat->getTypeNum(0);
3510 std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator TI =
3511 PatternsByType.find(VT);
3512 if (TI != PatternsByType.end())
3513 TI->second.push_back(Pat);
3514 else {
3515 std::vector<PatternToMatch*> PVec;
3516 PVec.push_back(Pat);
3517 PatternsByType.insert(std::make_pair(VT, PVec));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003518 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003519 }
3520
3521 for (std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator
3522 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
3523 ++II) {
3524 MVT::ValueType OpVT = II->first;
3525 std::vector<PatternToMatch*> &Patterns = II->second;
Chris Lattner64906972006-09-21 18:28:27 +00003526 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
3527 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00003528
3529 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3530 std::vector<std::vector<std::string> > PatternOpcodes;
3531 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00003532 std::vector<std::set<std::string> > PatternDecls;
Chris Lattner706d2d32006-08-09 16:44:44 +00003533 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3534 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00003535 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00003536 std::vector<std::string> TargetOpcodes;
3537 std::vector<std::string> TargetVTs;
3538 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3539 TargetOpcodes, TargetVTs);
Chris Lattner706d2d32006-08-09 16:44:44 +00003540 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3541 PatternDecls.push_back(GeneratedDecl);
3542 PatternOpcodes.push_back(TargetOpcodes);
3543 PatternVTs.push_back(TargetVTs);
3544 }
3545
3546 // Scan the code to see if all of the patterns are reachable and if it is
3547 // possible that the last one might not match.
3548 bool mightNotMatch = true;
3549 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3550 CodeList &GeneratedCode = CodeForPatterns[i].second;
3551 mightNotMatch = false;
3552
3553 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
Evan Cheng676d7312006-08-26 00:59:04 +00003554 if (GeneratedCode[j].first == 1) { // predicate.
Chris Lattner706d2d32006-08-09 16:44:44 +00003555 mightNotMatch = true;
3556 break;
3557 }
3558 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003559
Chris Lattner706d2d32006-08-09 16:44:44 +00003560 // If this pattern definitely matches, and if it isn't the last one, the
3561 // patterns after it CANNOT ever match. Error out.
3562 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00003563 cerr << "Pattern '";
3564 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
3565 cerr << "' is impossible to select!\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003566 exit(1);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003567 }
3568 }
3569
Chris Lattner706d2d32006-08-09 16:44:44 +00003570 // Factor target node emission code (emitted by EmitResultCode) into
3571 // separate functions. Uniquing and share them among all instruction
3572 // selection routines.
3573 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3574 CodeList &GeneratedCode = CodeForPatterns[i].second;
3575 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
3576 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00003577 std::set<std::string> Decls = PatternDecls[i];
Evan Cheng676d7312006-08-26 00:59:04 +00003578 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00003579 int CodeSize = (int)GeneratedCode.size();
3580 int LastPred = -1;
3581 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00003582 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00003583 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00003584 else if (LastPred != -1 && GeneratedCode[j].first == 2)
3585 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00003586 }
3587
Evan Cheng9ade2182006-08-26 05:34:46 +00003588 std::string CalleeCode = "(const SDOperand &N";
3589 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00003590 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3591 CalleeCode += ", unsigned Opc" + utostr(j);
3592 CallerCode += ", " + TargetOpcodes[j];
3593 }
3594 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
3595 CalleeCode += ", MVT::ValueType VT" + utostr(j);
3596 CallerCode += ", " + TargetVTs[j];
3597 }
Evan Chengf5493192006-08-26 01:02:19 +00003598 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00003599 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00003600 std::string Name = *I;
Evan Cheng676d7312006-08-26 00:59:04 +00003601 CalleeCode += ", SDOperand &" + Name;
3602 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00003603 }
3604 CallerCode += ");";
3605 CalleeCode += ") ";
3606 // Prevent emission routines from being inlined to reduce selection
3607 // routines stack frame sizes.
Chris Lattner8dc728e2006-08-27 13:16:24 +00003608 CalleeCode += "DISABLE_INLINE ";
Evan Cheng676d7312006-08-26 00:59:04 +00003609 CalleeCode += "{\n";
3610
3611 for (std::vector<std::string>::const_reverse_iterator
3612 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
3613 CalleeCode += " " + *I + "\n";
3614
Evan Chengf5493192006-08-26 01:02:19 +00003615 for (int j = LastPred+1; j < CodeSize; ++j)
3616 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003617 for (int j = LastPred+1; j < CodeSize; ++j)
3618 GeneratedCode.pop_back();
3619 CalleeCode += "}\n";
3620
3621 // Uniquing the emission routines.
3622 unsigned EmitFuncNum;
3623 std::map<std::string, unsigned>::iterator EFI =
3624 EmitFunctions.find(CalleeCode);
3625 if (EFI != EmitFunctions.end()) {
3626 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003627 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00003628 EmitFuncNum = EmitFunctions.size();
3629 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Evan Cheng06d64702006-08-11 08:59:35 +00003630 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003631 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003632
Chris Lattner706d2d32006-08-09 16:44:44 +00003633 // Replace the emission code within selection routines with calls to the
3634 // emission functions.
Evan Cheng06d64702006-08-11 08:59:35 +00003635 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
Chris Lattner706d2d32006-08-09 16:44:44 +00003636 GeneratedCode.push_back(std::make_pair(false, CallerCode));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003637 }
3638
Chris Lattner706d2d32006-08-09 16:44:44 +00003639 // Print function.
Chris Lattnerab51ddd2006-11-14 21:32:01 +00003640 std::string OpVTStr;
Chris Lattner33a40042006-11-14 22:17:10 +00003641 if (OpVT == MVT::iPTR) {
3642 OpVTStr = "_iPTR";
3643 } else if (OpVT == MVT::isVoid) {
3644 // Nodes with a void result actually have a first result type of either
3645 // Other (a chain) or Flag. Since there is no one-to-one mapping from
3646 // void to this case, we handle it specially here.
3647 } else {
3648 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
3649 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003650 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3651 OpcodeVTMap.find(OpName);
3652 if (OpVTI == OpcodeVTMap.end()) {
3653 std::vector<std::string> VTSet;
3654 VTSet.push_back(OpVTStr);
3655 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
3656 } else
3657 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003658
Evan Cheng892aaf82006-11-08 23:01:03 +00003659 OS << "SDNode *Select_" << getLegalCName(OpName)
Chris Lattner33a40042006-11-14 22:17:10 +00003660 << OpVTStr << "(const SDOperand &N) {\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003661
Chris Lattner706d2d32006-08-09 16:44:44 +00003662 // Loop through and reverse all of the CodeList vectors, as we will be
3663 // accessing them from their logical front, but accessing the end of a
3664 // vector is more efficient.
3665 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3666 CodeList &GeneratedCode = CodeForPatterns[i].second;
3667 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003668 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003669
3670 // Next, reverse the list of patterns itself for the same reason.
3671 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3672
3673 // Emit all of the patterns now, grouped together to share code.
3674 EmitPatterns(CodeForPatterns, 2, OS);
3675
Chris Lattner64906972006-09-21 18:28:27 +00003676 // If the last pattern has predicates (which could fail) emit code to
3677 // catch the case where nothing handles a pattern.
Chris Lattner706d2d32006-08-09 16:44:44 +00003678 if (mightNotMatch) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00003679 OS << " cerr << \"Cannot yet select: \";\n";
Evan Cheng892aaf82006-11-08 23:01:03 +00003680 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
3681 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
3682 OpName != "ISD::INTRINSIC_VOID") {
Chris Lattner706d2d32006-08-09 16:44:44 +00003683 OS << " N.Val->dump(CurDAG);\n";
3684 } else {
3685 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3686 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00003687 << " cerr << \"intrinsic %\"<< "
Chris Lattner706d2d32006-08-09 16:44:44 +00003688 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3689 }
Bill Wendlingf5da1332006-12-07 22:21:48 +00003690 OS << " cerr << '\\n';\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003691 << " abort();\n"
3692 << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003693 }
3694 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003695 }
Chris Lattner602f6922006-01-04 00:25:00 +00003696 }
3697
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003698 // Emit boilerplate.
Evan Cheng9ade2182006-08-26 05:34:46 +00003699 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003700 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Chris Lattner4ef9b112007-05-15 01:36:44 +00003701 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
3702
3703 << " // Ensure that the asm operands are themselves selected.\n"
3704 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
3705 << " AddToISelQueue(Ops[j]);\n\n"
3706
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003707 << " std::vector<MVT::ValueType> VTs;\n"
3708 << " VTs.push_back(MVT::Other);\n"
3709 << " VTs.push_back(MVT::Flag);\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00003710 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
3711 "Ops.size());\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00003712 << " return New.Val;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003713 << "}\n\n";
3714
Jim Laskeya683f9b2007-01-26 17:29:20 +00003715 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
3716 << " SDOperand Chain = N.getOperand(0);\n"
3717 << " SDOperand N1 = N.getOperand(1);\n"
Jim Laskey844b8922007-01-26 23:00:54 +00003718 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
3719 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00003720 << " AddToISelQueue(Chain);\n"
Chris Lattner44f14762007-10-24 06:25:09 +00003721 << " SDOperand Ops[] = { Tmp, Chain };\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00003722 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
Chris Lattner44f14762007-10-24 06:25:09 +00003723 << " MVT::Other, Ops, 2);\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00003724 << "}\n\n";
3725
Christopher Lamb08d52072007-07-26 07:48:21 +00003726 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
3727 << " SDOperand N0 = N.getOperand(0);\n"
3728 << " SDOperand N1 = N.getOperand(1);\n"
3729 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
3730 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
3731 << " AddToISelQueue(N0);\n"
Chris Lattner44f14762007-10-24 06:25:09 +00003732 << " SDOperand Ops[] = { N0, Tmp };\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00003733 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
Chris Lattner44f14762007-10-24 06:25:09 +00003734 << " N.getValueType(), Ops, 2);\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00003735 << "}\n\n";
3736
3737 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
3738 << " SDOperand N0 = N.getOperand(0);\n"
3739 << " SDOperand N1 = N.getOperand(1);\n"
3740 << " SDOperand N2 = N.getOperand(2);\n"
3741 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
3742 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
3743 << " AddToISelQueue(N1);\n"
Chris Lattner44f14762007-10-24 06:25:09 +00003744 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00003745 << " if (N0.getOpcode() == ISD::UNDEF) {\n"
Evan Cheng3393f892007-10-12 08:39:02 +00003746 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
Chris Lattner44f14762007-10-24 06:25:09 +00003747 << " N.getValueType(), Ops+1, 2);\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00003748 << " } else {\n"
3749 << " AddToISelQueue(N0);\n"
Evan Cheng3393f892007-10-12 08:39:02 +00003750 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
Chris Lattner44f14762007-10-24 06:25:09 +00003751 << " N.getValueType(), Ops, 3);\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00003752 << " }\n"
3753 << "}\n\n";
3754
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003755 OS << "// The main instruction selector code.\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00003756 << "SDNode *SelectCode(SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003757 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003758 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003759 << "INSTRUCTION_LIST_END)) {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003760 << " return NULL; // Already selected.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003761 << " }\n\n"
Evan Cheng892aaf82006-11-08 23:01:03 +00003762 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003763 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003764 << " default: break;\n"
3765 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003766 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003767 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003768 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003769 << " case ISD::TargetConstant:\n"
3770 << " case ISD::TargetConstantPool:\n"
3771 << " case ISD::TargetFrameIndex:\n"
Chris Lattner4ef9b112007-05-15 01:36:44 +00003772 << " case ISD::TargetExternalSymbol:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00003773 << " case ISD::TargetJumpTable:\n"
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00003774 << " case ISD::TargetGlobalTLSAddress:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003775 << " case ISD::TargetGlobalAddress: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003776 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003777 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003778 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003779 << " case ISD::AssertZext: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003780 << " AddToISelQueue(N.getOperand(0));\n"
3781 << " ReplaceUses(N, N.getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003782 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003783 << " }\n"
3784 << " case ISD::TokenFactor:\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00003785 << " case ISD::CopyFromReg:\n"
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003786 << " case ISD::CopyToReg: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003787 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
3788 << " AddToISelQueue(N.getOperand(i));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003789 << " return NULL;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003790 << " }\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00003791 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00003792 << " case ISD::LABEL: return Select_LABEL(N);\n"
3793 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
3794 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003795
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003796
Chris Lattner602f6922006-01-04 00:25:00 +00003797 // Loop over all of the case statements, emiting a call to each method we
3798 // emitted above.
Evan Cheng892aaf82006-11-08 23:01:03 +00003799 for (std::map<std::string, std::vector<PatternToMatch*> >::iterator
3800 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
3801 PBOI != E; ++PBOI) {
3802 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00003803 // Potentially multiple versions of select for this opcode. One for each
3804 // ValueType of the node (or its first true operand if it doesn't produce a
3805 // result.
3806 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3807 OpcodeVTMap.find(OpName);
3808 std::vector<std::string> &OpVTs = OpVTI->second;
Evan Cheng892aaf82006-11-08 23:01:03 +00003809 OS << " case " << OpName << ": {\n";
Evan Cheng425e8c72007-09-04 20:18:28 +00003810 // Keep track of whether we see a pattern that has an iPtr result.
3811 bool HasPtrPattern = false;
3812 bool HasDefaultPattern = false;
Chris Lattner717a6112006-11-14 21:50:27 +00003813
Evan Cheng425e8c72007-09-04 20:18:28 +00003814 OS << " switch (NVT) {\n";
3815 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
3816 std::string &VTStr = OpVTs[i];
3817 if (VTStr.empty()) {
3818 HasDefaultPattern = true;
3819 continue;
3820 }
Chris Lattner717a6112006-11-14 21:50:27 +00003821
Evan Cheng425e8c72007-09-04 20:18:28 +00003822 // If this is a match on iPTR: don't emit it directly, we need special
3823 // code.
3824 if (VTStr == "_iPTR") {
3825 HasPtrPattern = true;
3826 continue;
Chris Lattner706d2d32006-08-09 16:44:44 +00003827 }
Evan Cheng425e8c72007-09-04 20:18:28 +00003828 OS << " case MVT::" << VTStr.substr(1) << ":\n"
3829 << " return Select_" << getLegalCName(OpName)
3830 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003831 }
Evan Cheng425e8c72007-09-04 20:18:28 +00003832 OS << " default:\n";
3833
3834 // If there is an iPTR result version of this pattern, emit it here.
3835 if (HasPtrPattern) {
3836 OS << " if (NVT == TLI.getPointerTy())\n";
3837 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
3838 }
3839 if (HasDefaultPattern) {
3840 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
3841 }
3842 OS << " break;\n";
3843 OS << " }\n";
3844 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003845 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00003846 }
Chris Lattner81303322005-09-23 19:36:15 +00003847
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003848 OS << " } // end of big switch.\n\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00003849 << " cerr << \"Cannot yet select: \";\n"
Chris Lattnerb026e702006-03-28 00:41:33 +00003850 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3851 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3852 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003853 << " N.Val->dump(CurDAG);\n"
3854 << " } else {\n"
3855 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3856 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00003857 << " cerr << \"intrinsic %\"<< "
3858 "Intrinsic::getName((Intrinsic::ID)iid);\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003859 << " }\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00003860 << " cerr << '\\n';\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003861 << " abort();\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003862 << " return NULL;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003863 << "}\n";
3864}
3865
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003866void DAGISelEmitter::run(std::ostream &OS) {
3867 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3868 " target", OS);
3869
Chris Lattner1f39e292005-09-14 00:09:24 +00003870 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3871 << "// *** instruction selector class. These functions are really "
3872 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003873
Chris Lattner8dc728e2006-08-27 13:16:24 +00003874 OS << "#include \"llvm/Support/Compiler.h\"\n";
Evan Cheng233baf12006-07-26 23:06:27 +00003875
Chris Lattner706d2d32006-08-09 16:44:44 +00003876 OS << "// Instruction selector priority queue:\n"
3877 << "std::vector<SDNode*> ISelQueue;\n";
3878 OS << "/// Keep track of nodes which have already been added to queue.\n"
3879 << "unsigned char *ISelQueued;\n";
3880 OS << "/// Keep track of nodes which have already been selected.\n"
3881 << "unsigned char *ISelSelected;\n";
3882 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
3883 << "std::vector<SDNode*> ISelKilled;\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003884
Evan Cheng4326ef52006-10-12 02:08:53 +00003885 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
3886 OS << "/// not reach Op.\n";
3887 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
3888 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
3889 OS << " return true;\n";
3890 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
3891 OS << " return false;\n";
3892 OS << " else if (Chain->getNumOperands() > 0) {\n";
3893 OS << " SDOperand C0 = Chain->getOperand(0);\n";
3894 OS << " if (C0.getValueType() == MVT::Other)\n";
3895 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
3896 OS << " }\n";
3897 OS << " return true;\n";
3898 OS << "}\n";
3899
Chris Lattner706d2d32006-08-09 16:44:44 +00003900 OS << "/// Sorting functions for the selection queue.\n"
3901 << "struct isel_sort : public std::binary_function"
3902 << "<SDNode*, SDNode*, bool> {\n"
3903 << " bool operator()(const SDNode* left, const SDNode* right) "
3904 << "const {\n"
3905 << " return (left->getNodeId() > right->getNodeId());\n"
3906 << " }\n"
3907 << "};\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003908
Chris Lattner706d2d32006-08-09 16:44:44 +00003909 OS << "inline void setQueued(int Id) {\n";
3910 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003911 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003912 OS << "inline bool isQueued(int Id) {\n";
3913 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003914 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003915 OS << "inline void setSelected(int Id) {\n";
3916 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003917 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003918 OS << "inline bool isSelected(int Id) {\n";
3919 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
3920 OS << "}\n\n";
Evan Cheng9bdca032006-08-07 22:17:58 +00003921
Chris Lattner8dc728e2006-08-27 13:16:24 +00003922 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003923 OS << " int Id = N.Val->getNodeId();\n";
3924 OS << " if (Id != -1 && !isQueued(Id)) {\n";
3925 OS << " ISelQueue.push_back(N.Val);\n";
3926 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3927 OS << " setQueued(Id);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003928 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003929 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003930
Chris Lattner706d2d32006-08-09 16:44:44 +00003931 OS << "inline void RemoveKilled() {\n";
3932OS << " unsigned NumKilled = ISelKilled.size();\n";
3933 OS << " if (NumKilled) {\n";
3934 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
3935 OS << " SDNode *Temp = ISelKilled[i];\n";
Evan Cheng4f776162006-10-12 23:18:52 +00003936 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
3937 << "Temp), ISelQueue.end());\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003938 OS << " };\n";
3939 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3940 OS << " ISelKilled.clear();\n";
3941 OS << " }\n";
3942 OS << "}\n\n";
3943
Chris Lattner8dc728e2006-08-27 13:16:24 +00003944 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
Chris Lattner01d029b2007-10-15 06:10:22 +00003945 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISelKilled);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003946 OS << " setSelected(F.Val->getNodeId());\n";
3947 OS << " RemoveKilled();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003948 OS << "}\n";
Evan Cheng85dbe1a2007-09-12 23:30:14 +00003949 OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
Evan Cheng30729b42007-09-17 22:26:41 +00003950 OS << " unsigned FNumVals = F->getNumValues();\n";
3951 OS << " unsigned TNumVals = T->getNumValues();\n";
3952 OS << " if (FNumVals != TNumVals) {\n";
3953 OS << " for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
3954 << "i < e; ++i)\n";
Evan Cheng85dbe1a2007-09-12 23:30:14 +00003955 OS << " CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
Chris Lattner01d029b2007-10-15 06:10:22 +00003956 << "SDOperand(T, i), &ISelKilled);\n";
Evan Cheng85dbe1a2007-09-12 23:30:14 +00003957 OS << " } else {\n";
3958 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
3959 OS << " }\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003960 OS << " setSelected(F->getNodeId());\n";
3961 OS << " RemoveKilled();\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003962 OS << "}\n\n";
3963
Evan Chenge41bf822006-02-05 06:43:12 +00003964 OS << "// SelectRoot - Top level entry to DAG isel.\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003965 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
3966 OS << " SelectRootInit();\n";
3967 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
3968 OS << " ISelQueued = new unsigned char[NumBytes];\n";
3969 OS << " ISelSelected = new unsigned char[NumBytes];\n";
3970 OS << " memset(ISelQueued, 0, NumBytes);\n";
3971 OS << " memset(ISelSelected, 0, NumBytes);\n";
3972 OS << "\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00003973 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
3974 << " // a reference to the root node, preventing it from being deleted,\n"
3975 << " // and tracking any changes of the root.\n"
3976 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
3977 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003978 OS << " while (!ISelQueue.empty()) {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003979 OS << " SDNode *Node = ISelQueue.front();\n";
3980 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3981 OS << " ISelQueue.pop_back();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003982 OS << " if (!isSelected(Node->getNodeId())) {\n";
Evan Cheng9ade2182006-08-26 05:34:46 +00003983 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
Evan Cheng966fd372006-09-11 02:24:43 +00003984 OS << " if (ResNode != Node) {\n";
3985 OS << " if (ResNode)\n";
3986 OS << " ReplaceUses(Node, ResNode);\n";
Evan Cheng1fae00f2006-10-12 20:35:19 +00003987 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
3988 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
3989 OS << " RemoveKilled();\n";
3990 OS << " }\n";
Evan Cheng966fd372006-09-11 02:24:43 +00003991 OS << " }\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003992 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003993 OS << " }\n";
3994 OS << "\n";
3995 OS << " delete[] ISelQueued;\n";
3996 OS << " ISelQueued = NULL;\n";
3997 OS << " delete[] ISelSelected;\n";
3998 OS << " ISelSelected = NULL;\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00003999 OS << " return Dummy.getValue();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00004000 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00004001
Chris Lattner550525e2006-03-24 21:48:51 +00004002 Intrinsics = LoadIntrinsics(Records);
Chris Lattnerca559d02005-09-08 21:03:01 +00004003 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00004004 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00004005 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00004006 ParsePatternFragments(OS);
Evan Chenga9559392007-07-06 01:05:26 +00004007 ParseDefaultOperands();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00004008 ParseInstructions();
4009 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00004010
Chris Lattnere97603f2005-09-28 19:27:25 +00004011 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00004012 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00004013 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00004014
Bill Wendlingf5da1332006-12-07 22:21:48 +00004015 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
4016 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
4017 DOUT << "PATTERN: "; DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
4018 DOUT << "\nRESULT: "; DEBUG(PatternsToMatch[i].getDstPattern()->dump());
4019 DOUT << "\n";
4020 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00004021
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00004022 // At this point, we have full information about the 'Patterns' we need to
4023 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00004024 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00004025 EmitInstructionSelector(OS);
4026
4027 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
4028 E = PatternFragments.end(); I != E; ++I)
4029 delete I->second;
4030 PatternFragments.clear();
4031
Chris Lattner54cb8fd2005-09-07 23:44:43 +00004032 Instructions.clear();
4033}