blob: e8049d6baf52fdf17b69a922e6bb06d2b983ab22 [file] [log] [blame]
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Support/Debug.h"
Chris Lattnerbe8e7212006-10-11 03:35:34 +000018#include "llvm/Support/MathExtras.h"
Bill Wendlingf5da1332006-12-07 22:21:48 +000019#include "llvm/Support/Streams.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000020#include <algorithm>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000021#include <set>
22using namespace llvm;
23
Chris Lattnerca559d02005-09-08 21:03:01 +000024//===----------------------------------------------------------------------===//
Chris Lattner3c7e18d2005-10-14 06:12:03 +000025// Helpers for working with extended types.
26
27/// FilterVTs - Filter a list of VT's according to a predicate.
28///
29template<typename T>
30static std::vector<MVT::ValueType>
31FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
32 std::vector<MVT::ValueType> Result;
33 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
34 if (Filter(InVTs[i]))
35 Result.push_back(InVTs[i]);
36 return Result;
37}
38
Nate Begemanb73628b2005-12-30 00:12:56 +000039template<typename T>
40static std::vector<unsigned char>
41FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42 std::vector<unsigned char> Result;
43 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
44 if (Filter((MVT::ValueType)InVTs[i]))
45 Result.push_back(InVTs[i]);
46 return Result;
Chris Lattner3c7e18d2005-10-14 06:12:03 +000047}
48
Nate Begemanb73628b2005-12-30 00:12:56 +000049static std::vector<unsigned char>
50ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
51 std::vector<unsigned char> Result;
52 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53 Result.push_back(InVTs[i]);
54 return Result;
55}
56
57static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
58 const std::vector<unsigned char> &RHS) {
59 if (LHS.size() > RHS.size()) return false;
60 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
Duraid Madinad47ae092005-12-30 16:41:48 +000061 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
Nate Begemanb73628b2005-12-30 00:12:56 +000062 return false;
63 return true;
64}
65
66/// isExtIntegerVT - Return true if the specified extended value type vector
67/// contains isInt or an integer value type.
Chris Lattner697f8842006-03-20 05:39:48 +000068static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000069 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
70 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
71}
72
73/// isExtFloatingPointVT - Return true if the specified extended value type
74/// vector contains isFP or a FP value type.
Chris Lattner697f8842006-03-20 05:39:48 +000075static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000076 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
Chris Lattner488580c2006-01-28 19:06:51 +000077 return EVTs[0] == MVT::isFP ||
78 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
Chris Lattner3c7e18d2005-10-14 06:12:03 +000079}
80
81//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000082// SDTypeConstraint implementation
83//
84
85SDTypeConstraint::SDTypeConstraint(Record *R) {
86 OperandNo = R->getValueAsInt("OperandNum");
87
88 if (R->isSubClassOf("SDTCisVT")) {
89 ConstraintType = SDTCisVT;
90 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattner5b21be72005-12-09 22:57:42 +000091 } else if (R->isSubClassOf("SDTCisPtrTy")) {
92 ConstraintType = SDTCisPtrTy;
Chris Lattner33c92e92005-09-08 21:27:15 +000093 } else if (R->isSubClassOf("SDTCisInt")) {
94 ConstraintType = SDTCisInt;
95 } else if (R->isSubClassOf("SDTCisFP")) {
96 ConstraintType = SDTCisFP;
97 } else if (R->isSubClassOf("SDTCisSameAs")) {
98 ConstraintType = SDTCisSameAs;
99 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
100 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
101 ConstraintType = SDTCisVTSmallerThanOp;
102 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
103 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +0000104 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
105 ConstraintType = SDTCisOpSmallerThanOp;
106 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
107 R->getValueAsInt("BigOperandNum");
Chris Lattner697f8842006-03-20 05:39:48 +0000108 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
109 ConstraintType = SDTCisIntVectorOfSameSize;
110 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
111 R->getValueAsInt("OtherOpNum");
Chris Lattner33c92e92005-09-08 21:27:15 +0000112 } else {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000113 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner33c92e92005-09-08 21:27:15 +0000114 exit(1);
115 }
116}
117
Chris Lattner32707602005-09-08 23:22:48 +0000118/// getOperandNum - Return the node corresponding to operand #OpNo in tree
119/// N, which has NumResults results.
120TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
121 TreePatternNode *N,
122 unsigned NumResults) const {
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000123 assert(NumResults <= 1 &&
124 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000125
Evan Cheng50c997e2006-06-13 21:47:27 +0000126 if (OpNo >= (NumResults + N->getNumChildren())) {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000127 cerr << "Invalid operand number " << OpNo << " ";
Evan Cheng50c997e2006-06-13 21:47:27 +0000128 N->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +0000129 cerr << '\n';
Evan Cheng50c997e2006-06-13 21:47:27 +0000130 exit(1);
131 }
132
Chris Lattner32707602005-09-08 23:22:48 +0000133 if (OpNo < NumResults)
134 return N; // FIXME: need value #
135 else
136 return N->getChild(OpNo-NumResults);
137}
138
139/// ApplyTypeConstraint - Given a node in a pattern, apply this type
140/// constraint to the nodes operands. This returns true if it makes a
141/// change, false otherwise. If a type contradiction is found, throw an
142/// exception.
143bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
144 const SDNodeInfo &NodeInfo,
145 TreePattern &TP) const {
146 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000147 assert(NumResults <= 1 &&
148 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000149
Chris Lattner8f60d542006-06-16 18:25:06 +0000150 // Check that the number of operands is sane. Negative operands -> varargs.
Chris Lattner32707602005-09-08 23:22:48 +0000151 if (NodeInfo.getNumOperands() >= 0) {
152 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
153 TP.error(N->getOperator()->getName() + " node requires exactly " +
154 itostr(NodeInfo.getNumOperands()) + " operands!");
155 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000156
157 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000158
159 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
160
161 switch (ConstraintType) {
162 default: assert(0 && "Unknown constraint type!");
163 case SDTCisVT:
164 // Operand must be a particular type.
165 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000166 case SDTCisPtrTy: {
167 // Operand must be same as target pointer type.
Evan Cheng2618d072006-05-17 20:37:59 +0000168 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000169 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000170 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000171 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000172 std::vector<MVT::ValueType> IntVTs =
173 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000174
175 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000176 if (IntVTs.size() == 1)
177 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000178 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000179 }
180 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000181 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000182 std::vector<MVT::ValueType> FPVTs =
183 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000184
185 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000186 if (FPVTs.size() == 1)
187 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000188 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000189 }
Chris Lattner32707602005-09-08 23:22:48 +0000190 case SDTCisSameAs: {
191 TreePatternNode *OtherNode =
192 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Nate Begemanb73628b2005-12-30 00:12:56 +0000193 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
194 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000195 }
196 case SDTCisVTSmallerThanOp: {
197 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
198 // have an integer type that is smaller than the VT.
199 if (!NodeToApply->isLeaf() ||
200 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
201 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
202 ->isSubClassOf("ValueType"))
203 TP.error(N->getOperator()->getName() + " expects a VT operand!");
204 MVT::ValueType VT =
205 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
206 if (!MVT::isInteger(VT))
207 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
208
209 TreePatternNode *OtherNode =
210 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000211
212 // It must be integer.
213 bool MadeChange = false;
214 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
215
Nate Begemanb73628b2005-12-30 00:12:56 +0000216 // This code only handles nodes that have one type set. Assert here so
217 // that we can change this if we ever need to deal with multiple value
218 // types at this point.
219 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
220 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000221 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
222 return false;
223 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000224 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000225 TreePatternNode *BigOperand =
226 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
227
228 // Both operands must be integer or FP, but we don't care which.
229 bool MadeChange = false;
230
Nate Begemanb73628b2005-12-30 00:12:56 +0000231 // This code does not currently handle nodes which have multiple types,
232 // where some types are integer, and some are fp. Assert that this is not
233 // the case.
234 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
235 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
236 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
237 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
238 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
239 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000240 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000241 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000242 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000243 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000244 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000245 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000246 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
247
248 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
249
Nate Begemanb73628b2005-12-30 00:12:56 +0000250 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000251 VTs = FilterVTs(VTs, MVT::isInteger);
Nate Begemanb73628b2005-12-30 00:12:56 +0000252 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000253 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
254 } else {
255 VTs.clear();
256 }
257
258 switch (VTs.size()) {
259 default: // Too many VT's to pick from.
260 case 0: break; // No info yet.
261 case 1:
262 // Only one VT of this flavor. Cannot ever satisify the constraints.
263 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
264 case 2:
265 // If we have exactly two possible types, the little operand must be the
266 // small one, the big operand should be the big one. Common with
267 // float/double for example.
268 assert(VTs[0] < VTs[1] && "Should be sorted!");
269 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
270 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
271 break;
272 }
273 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000274 }
Chris Lattner697f8842006-03-20 05:39:48 +0000275 case SDTCisIntVectorOfSameSize: {
276 TreePatternNode *OtherOperand =
277 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
278 N, NumResults);
279 if (OtherOperand->hasTypeSet()) {
280 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
281 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
282 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
283 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
284 return NodeToApply->UpdateNodeType(IVT, TP);
285 }
286 return false;
287 }
Chris Lattner32707602005-09-08 23:22:48 +0000288 }
289 return false;
290}
291
292
Chris Lattner33c92e92005-09-08 21:27:15 +0000293//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000294// SDNodeInfo implementation
295//
296SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
297 EnumName = R->getValueAsString("Opcode");
298 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000299 Record *TypeProfile = R->getValueAsDef("TypeProfile");
300 NumResults = TypeProfile->getValueAsInt("NumResults");
301 NumOperands = TypeProfile->getValueAsInt("NumOperands");
302
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000303 // Parse the properties.
304 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000305 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000306 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
307 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000308 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000309 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000310 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000311 } else if (PropList[i]->getName() == "SDNPHasChain") {
312 Properties |= 1 << SDNPHasChain;
Evan Cheng51fecc82006-01-09 18:27:06 +0000313 } else if (PropList[i]->getName() == "SDNPOutFlag") {
314 Properties |= 1 << SDNPOutFlag;
315 } else if (PropList[i]->getName() == "SDNPInFlag") {
316 Properties |= 1 << SDNPInFlag;
317 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
318 Properties |= 1 << SDNPOptInFlag;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000319 } else {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000320 cerr << "Unknown SD Node property '" << PropList[i]->getName()
321 << "' on node '" << R->getName() << "'!\n";
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000322 exit(1);
323 }
324 }
325
326
Chris Lattner33c92e92005-09-08 21:27:15 +0000327 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000328 std::vector<Record*> ConstraintList =
329 TypeProfile->getValueAsListOfDefs("Constraints");
330 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000331}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000332
333//===----------------------------------------------------------------------===//
334// TreePatternNode implementation
335//
336
337TreePatternNode::~TreePatternNode() {
338#if 0 // FIXME: implement refcounted tree nodes!
339 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
340 delete getChild(i);
341#endif
342}
343
Chris Lattner32707602005-09-08 23:22:48 +0000344/// UpdateNodeType - Set the node type of N to VT if VT contains
345/// information. If N already contains a conflicting type, then throw an
346/// exception. This returns true if any information was updated.
347///
Nate Begemanb73628b2005-12-30 00:12:56 +0000348bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
349 TreePattern &TP) {
350 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
351
352 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
353 return false;
354 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
355 setTypes(ExtVTs);
Chris Lattner32707602005-09-08 23:22:48 +0000356 return true;
357 }
Evan Cheng2618d072006-05-17 20:37:59 +0000358
359 if (getExtTypeNum(0) == MVT::iPTR) {
360 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
361 return false;
362 if (isExtIntegerInVTs(ExtVTs)) {
363 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
364 if (FVTs.size()) {
365 setTypes(ExtVTs);
366 return true;
367 }
368 }
369 }
Chris Lattner32707602005-09-08 23:22:48 +0000370
Nate Begemanb73628b2005-12-30 00:12:56 +0000371 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
372 assert(hasTypeSet() && "should be handled above!");
373 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
374 if (getExtTypes() == FVTs)
375 return false;
376 setTypes(FVTs);
377 return true;
378 }
Evan Cheng2618d072006-05-17 20:37:59 +0000379 if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
380 //assert(hasTypeSet() && "should be handled above!");
381 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
382 if (getExtTypes() == FVTs)
383 return false;
384 if (FVTs.size()) {
385 setTypes(FVTs);
386 return true;
387 }
388 }
Nate Begemanb73628b2005-12-30 00:12:56 +0000389 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
390 assert(hasTypeSet() && "should be handled above!");
Chris Lattner488580c2006-01-28 19:06:51 +0000391 std::vector<unsigned char> FVTs =
392 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
Nate Begemanb73628b2005-12-30 00:12:56 +0000393 if (getExtTypes() == FVTs)
394 return false;
395 setTypes(FVTs);
396 return true;
397 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000398
399 // If we know this is an int or fp type, and we are told it is a specific one,
400 // take the advice.
Nate Begemanb73628b2005-12-30 00:12:56 +0000401 //
402 // Similarly, we should probably set the type here to the intersection of
403 // {isInt|isFP} and ExtVTs
404 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
405 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
406 setTypes(ExtVTs);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000407 return true;
Evan Cheng2618d072006-05-17 20:37:59 +0000408 }
409 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
410 setTypes(ExtVTs);
411 return true;
412 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000413
Chris Lattner1531f202005-10-26 16:59:37 +0000414 if (isLeaf()) {
415 dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +0000416 cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000417 TP.error("Type inference contradiction found in node!");
418 } else {
419 TP.error("Type inference contradiction found in node " +
420 getOperator()->getName() + "!");
421 }
Chris Lattner32707602005-09-08 23:22:48 +0000422 return true; // unreachable
423}
424
425
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000426void TreePatternNode::print(std::ostream &OS) const {
427 if (isLeaf()) {
428 OS << *getLeafValue();
429 } else {
430 OS << "(" << getOperator()->getName();
431 }
432
Nate Begemanb73628b2005-12-30 00:12:56 +0000433 // FIXME: At some point we should handle printing all the value types for
434 // nodes that are multiply typed.
435 switch (getExtTypeNum(0)) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000436 case MVT::Other: OS << ":Other"; break;
437 case MVT::isInt: OS << ":isInt"; break;
438 case MVT::isFP : OS << ":isFP"; break;
439 case MVT::isUnknown: ; /*OS << ":?";*/ break;
Evan Cheng2618d072006-05-17 20:37:59 +0000440 case MVT::iPTR: OS << ":iPTR"; break;
Chris Lattner02cdb372006-06-20 00:56:37 +0000441 default: {
442 std::string VTName = llvm::getName(getTypeNum(0));
443 // Strip off MVT:: prefix if present.
444 if (VTName.substr(0,5) == "MVT::")
445 VTName = VTName.substr(5);
446 OS << ":" << VTName;
447 break;
448 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000449 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000450
451 if (!isLeaf()) {
452 if (getNumChildren() != 0) {
453 OS << " ";
454 getChild(0)->print(OS);
455 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
456 OS << ", ";
457 getChild(i)->print(OS);
458 }
459 }
460 OS << ")";
461 }
462
463 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000464 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000465 if (TransformFn)
466 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000467 if (!getName().empty())
468 OS << ":$" << getName();
469
470}
471void TreePatternNode::dump() const {
Bill Wendlingf5da1332006-12-07 22:21:48 +0000472 print(*cerr.stream());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000473}
474
Chris Lattnere46e17b2005-09-29 19:28:10 +0000475/// isIsomorphicTo - Return true if this node is recursively isomorphic to
476/// the specified node. For this comparison, all of the state of the node
477/// is considered, except for the assigned name. Nodes with differing names
478/// that are otherwise identical are considered isomorphic.
479bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
480 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000481 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000482 getPredicateFn() != N->getPredicateFn() ||
483 getTransformFn() != N->getTransformFn())
484 return false;
485
486 if (isLeaf()) {
487 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
488 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
489 return DI->getDef() == NDI->getDef();
490 return getLeafValue() == N->getLeafValue();
491 }
492
493 if (N->getOperator() != getOperator() ||
494 N->getNumChildren() != getNumChildren()) return false;
495 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
496 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
497 return false;
498 return true;
499}
500
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000501/// clone - Make a copy of this tree and all of its children.
502///
503TreePatternNode *TreePatternNode::clone() const {
504 TreePatternNode *New;
505 if (isLeaf()) {
506 New = new TreePatternNode(getLeafValue());
507 } else {
508 std::vector<TreePatternNode*> CChildren;
509 CChildren.reserve(Children.size());
510 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
511 CChildren.push_back(getChild(i)->clone());
512 New = new TreePatternNode(getOperator(), CChildren);
513 }
514 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000515 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000516 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000517 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000518 return New;
519}
520
Chris Lattner32707602005-09-08 23:22:48 +0000521/// SubstituteFormalArguments - Replace the formal arguments in this tree
522/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000523void TreePatternNode::
524SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
525 if (isLeaf()) return;
526
527 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
528 TreePatternNode *Child = getChild(i);
529 if (Child->isLeaf()) {
530 Init *Val = Child->getLeafValue();
531 if (dynamic_cast<DefInit*>(Val) &&
532 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
533 // We found a use of a formal argument, replace it with its value.
534 Child = ArgMap[Child->getName()];
535 assert(Child && "Couldn't find formal argument!");
536 setChild(i, Child);
537 }
538 } else {
539 getChild(i)->SubstituteFormalArguments(ArgMap);
540 }
541 }
542}
543
544
545/// InlinePatternFragments - If this pattern refers to any pattern
546/// fragments, inline them into place, giving us a pattern without any
547/// PatFrag references.
548TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
549 if (isLeaf()) return this; // nothing to do.
550 Record *Op = getOperator();
551
552 if (!Op->isSubClassOf("PatFrag")) {
553 // Just recursively inline children nodes.
554 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
555 setChild(i, getChild(i)->InlinePatternFragments(TP));
556 return this;
557 }
558
559 // Otherwise, we found a reference to a fragment. First, look up its
560 // TreePattern record.
561 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
562
563 // Verify that we are passing the right number of operands.
564 if (Frag->getNumArgs() != Children.size())
565 TP.error("'" + Op->getName() + "' fragment requires " +
566 utostr(Frag->getNumArgs()) + " operands!");
567
Chris Lattner37937092005-09-09 01:15:01 +0000568 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000569
570 // Resolve formal arguments to their actual value.
571 if (Frag->getNumArgs()) {
572 // Compute the map of formal to actual arguments.
573 std::map<std::string, TreePatternNode*> ArgMap;
574 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
575 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
576
577 FragTree->SubstituteFormalArguments(ArgMap);
578 }
579
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000580 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000581 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000582
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000583 // Get a new copy of this fragment to stitch into here.
584 //delete this; // FIXME: implement refcounting!
585 return FragTree;
586}
587
Chris Lattner52793e22006-04-06 20:19:52 +0000588/// getImplicitType - Check to see if the specified record has an implicit
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000589/// type which should be applied to it. This infer the type of register
590/// references from the register file information, for example.
591///
Chris Lattner52793e22006-04-06 20:19:52 +0000592static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000593 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000594 // Some common return values
595 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
596 std::vector<unsigned char> Other(1, MVT::Other);
597
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000598 // Check to see if this is a register or a register class...
599 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000600 if (NotRegisters)
601 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000602 const CodeGenRegisterClass &RC =
603 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000604 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000605 } else if (R->isSubClassOf("PatFrag")) {
606 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000607 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000608 } else if (R->isSubClassOf("Register")) {
Evan Cheng37e90052006-01-15 10:04:45 +0000609 if (NotRegisters)
610 return Unknown;
Chris Lattner22faeab2005-12-05 02:36:37 +0000611 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
Evan Cheng44a65fa2006-05-16 07:05:30 +0000612 return T.getRegisterVTs(R);
Chris Lattner1531f202005-10-26 16:59:37 +0000613 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
614 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000615 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000616 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng57c517d2006-01-17 07:36:41 +0000617 if (NotRegisters)
618 return Unknown;
Nate Begemanb73628b2005-12-30 00:12:56 +0000619 std::vector<unsigned char>
620 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
621 return ComplexPat;
Chris Lattner646085d2006-11-14 21:18:40 +0000622 } else if (R->getName() == "ptr_rc") {
623 Other[0] = MVT::iPTR;
624 return Other;
Evan 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") {
679 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000680 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
681 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000682
683 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000684 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
685 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000686 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
687 return MadeChange;
Chris Lattner5a1df382006-03-24 23:10:39 +0000688 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
689 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
690 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
691 unsigned IID =
692 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
693 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
694 bool MadeChange = false;
695
696 // Apply the result type to the node.
697 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
698
699 if (getNumChildren() != Int.ArgVTs.size())
Chris Lattner2c4e65d2006-03-27 22:21:18 +0000700 TP.error("Intrinsic '" + Int.Name + "' expects " +
Chris Lattner5a1df382006-03-24 23:10:39 +0000701 utostr(Int.ArgVTs.size()-1) + " operands, not " +
702 utostr(getNumChildren()-1) + " operands!");
703
704 // Apply type info to the intrinsic ID.
Evan Cheng2618d072006-05-17 20:37:59 +0000705 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5a1df382006-03-24 23:10:39 +0000706
707 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
708 MVT::ValueType OpVT = Int.ArgVTs[i];
709 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
710 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
711 }
712 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000713 } else if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000714 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
Chris Lattnerabbb6052005-09-15 21:42:00 +0000715
716 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
717 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000718 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000719 // Branch, etc. do not produce results and top-level forms in instr pattern
720 // must have void types.
721 if (NI.getNumResults() == 0)
722 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner91ded082006-04-06 20:36:51 +0000723
724 // If this is a vector_shuffle operation, apply types to the build_vector
725 // operation. The types of the integers don't matter, but this ensures they
726 // won't get checked.
727 if (getOperator()->getName() == "vector_shuffle" &&
728 getChild(2)->getOperator()->getName() == "build_vector") {
729 TreePatternNode *BV = getChild(2);
730 const std::vector<MVT::ValueType> &LegalVTs
731 = ISE.getTargetInfo().getLegalValueTypes();
732 MVT::ValueType LegalIntVT = MVT::Other;
733 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
734 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
735 LegalIntVT = LegalVTs[i];
736 break;
737 }
738 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
739
740 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
741 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
742 }
Chris Lattnerabbb6052005-09-15 21:42:00 +0000743 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000744 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000745 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000746 bool MadeChange = false;
747 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000748
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000749 assert(NumResults <= 1 &&
750 "Only supports zero or one result instrs!");
Evan Chengeb1f40d2006-07-20 23:36:20 +0000751
752 CodeGenInstruction &InstInfo =
753 ISE.getTargetInfo().getInstruction(getOperator()->getName());
Chris Lattnera28aec12005-09-15 22:23:50 +0000754 // Apply the result type to the node
Chris Lattner646085d2006-11-14 21:18:40 +0000755 if (NumResults == 0 || InstInfo.noResults) { // FIXME: temporary hack.
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000756 MadeChange = UpdateNodeType(MVT::isVoid, TP);
757 } else {
758 Record *ResultNode = Inst.getResult(0);
Chris Lattner646085d2006-11-14 21:18:40 +0000759
760 if (ResultNode->getName() == "ptr_rc") {
761 std::vector<unsigned char> VT;
762 VT.push_back(MVT::iPTR);
763 MadeChange = UpdateNodeType(VT, TP);
764 } else {
765 assert(ResultNode->isSubClassOf("RegisterClass") &&
766 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000767
Chris Lattner646085d2006-11-14 21:18:40 +0000768 const CodeGenRegisterClass &RC =
769 ISE.getTargetInfo().getRegisterClass(ResultNode);
770 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
771 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000772 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000773
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000774 unsigned ChildNo = 0;
775 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000776 Record *OperandNode = Inst.getOperand(i);
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000777
Evan Chenga9559392007-07-06 01:05:26 +0000778 // If the instruction expects a predicate or optional def operand, we
779 // codegen this by setting the operand to it's default value if it has a
780 // non-empty DefaultOps field.
781 if ((OperandNode->isSubClassOf("PredicateOperand") ||
782 OperandNode->isSubClassOf("OptionalDefOperand")) &&
783 !ISE.getDefaultOperand(OperandNode).DefaultOps.empty())
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000784 continue;
785
786 // Verify that we didn't run out of provided operands.
787 if (ChildNo >= getNumChildren())
788 TP.error("Instruction '" + getOperator()->getName() +
789 "' expects more operands than were provided.");
790
Nate Begemanddb39542005-12-01 00:06:14 +0000791 MVT::ValueType VT;
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000792 TreePatternNode *Child = getChild(ChildNo++);
Nate Begemanddb39542005-12-01 00:06:14 +0000793 if (OperandNode->isSubClassOf("RegisterClass")) {
794 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000795 ISE.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000796 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000797 } else if (OperandNode->isSubClassOf("Operand")) {
798 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000799 MadeChange |= Child->UpdateNodeType(VT, TP);
Chris Lattner646085d2006-11-14 21:18:40 +0000800 } else if (OperandNode->getName() == "ptr_rc") {
801 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000802 } else {
803 assert(0 && "Unknown operand type!");
804 abort();
805 }
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000806 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000807 }
Chris Lattnerdfdaeb22006-11-04 01:35:50 +0000808
809 if (ChildNo != getNumChildren())
810 TP.error("Instruction '" + getOperator()->getName() +
811 "' was provided too many operands!");
812
Chris Lattnera28aec12005-09-15 22:23:50 +0000813 return MadeChange;
814 } else {
815 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
816
Evan Chengf26ba692006-03-20 08:09:17 +0000817 // Node transforms always take one operand.
Chris Lattnera28aec12005-09-15 22:23:50 +0000818 if (getNumChildren() != 1)
819 TP.error("Node transform '" + getOperator()->getName() +
820 "' requires one operand!");
Chris Lattner4e2f54d2006-03-21 06:42:58 +0000821
822 // If either the output or input of the xform does not have exact
823 // type info. We assume they must be the same. Otherwise, it is perfectly
824 // legal to transform from one type to a completely different type.
825 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Evan Chengf26ba692006-03-20 08:09:17 +0000826 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
827 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
828 return MadeChange;
829 }
830 return false;
Chris Lattner32707602005-09-08 23:22:48 +0000831 }
Chris Lattner32707602005-09-08 23:22:48 +0000832}
833
Chris Lattnerce6e84c2006-09-21 20:46:13 +0000834/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
835/// RHS of a commutative operation, not the on LHS.
836static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
837 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
838 return true;
839 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
840 return true;
841 return false;
842}
843
844
Chris Lattnere97603f2005-09-28 19:27:25 +0000845/// canPatternMatch - If it is impossible for this pattern to match on this
846/// target, fill in Reason and return false. Otherwise, return true. This is
847/// used as a santity check for .td files (to prevent people from writing stuff
848/// that can never possibly work), and to prevent the pattern permuter from
849/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000850bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000851 if (isLeaf()) return true;
852
853 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
854 if (!getChild(i)->canPatternMatch(Reason, ISE))
855 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000856
Chris Lattner550525e2006-03-24 21:48:51 +0000857 // If this is an intrinsic, handle cases that would make it not match. For
858 // example, if an operand is required to be an immediate.
859 if (getOperator()->isSubClassOf("Intrinsic")) {
860 // TODO:
861 return true;
862 }
863
Chris Lattnere97603f2005-09-28 19:27:25 +0000864 // If this node is a commutative operator, check that the LHS isn't an
865 // immediate.
866 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
Evan Cheng94b30402006-10-11 21:02:01 +0000867 if (NodeInfo.hasProperty(SDNPCommutative)) {
Chris Lattnere97603f2005-09-28 19:27:25 +0000868 // Scan all of the operands of the node and make sure that only the last one
Chris Lattner7905c552006-09-14 23:54:24 +0000869 // is a constant node, unless the RHS also is.
Chris Lattnerce6e84c2006-09-21 20:46:13 +0000870 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Chris Lattner7905c552006-09-14 23:54:24 +0000871 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
Chris Lattnerce6e84c2006-09-21 20:46:13 +0000872 if (OnlyOnRHSOfCommutative(getChild(i))) {
Chris Lattner64906972006-09-21 18:28:27 +0000873 Reason="Immediate value must be on the RHS of commutative operators!";
Chris Lattner7905c552006-09-14 23:54:24 +0000874 return false;
875 }
876 }
Chris Lattnere97603f2005-09-28 19:27:25 +0000877 }
878
879 return true;
880}
Chris Lattner32707602005-09-08 23:22:48 +0000881
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000882//===----------------------------------------------------------------------===//
883// TreePattern implementation
884//
885
Chris Lattneredbd8712005-10-21 01:19:59 +0000886TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000887 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000888 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000889 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
890 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000891}
892
Chris Lattneredbd8712005-10-21 01:19:59 +0000893TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000894 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000895 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000896 Trees.push_back(ParseTreePattern(Pat));
897}
898
Chris Lattneredbd8712005-10-21 01:19:59 +0000899TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +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 Trees.push_back(Pat);
903}
904
905
906
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000907void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000908 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000909 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000910}
911
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000912TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
Chris Lattner8c063182006-03-30 22:50:40 +0000913 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
914 if (!OpDef) error("Pattern has unexpected operator type!");
915 Record *Operator = OpDef->getDef();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000916
917 if (Operator->isSubClassOf("ValueType")) {
918 // If the operator is a ValueType, then this must be "type cast" of a leaf
919 // node.
920 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000921 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000922
923 Init *Arg = Dag->getArg(0);
924 TreePatternNode *New;
925 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000926 Record *R = DI->getDef();
927 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000928 Dag->setArg(0, new DagInit(DI,
Chris Lattner72fe91c2005-09-24 00:40:24 +0000929 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000930 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000931 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000932 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000933 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
934 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000935 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
936 New = new TreePatternNode(II);
937 if (!Dag->getArgName(0).empty())
938 error("Constant int argument should not have a name!");
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000939 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
940 // Turn this into an IntInit.
941 Init *II = BI->convertInitializerTo(new IntRecTy());
942 if (II == 0 || !dynamic_cast<IntInit*>(II))
943 error("Bits value must be constants!");
944
945 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
946 if (!Dag->getArgName(0).empty())
947 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000948 } else {
949 Arg->dump();
950 error("Unknown leaf value for tree pattern!");
951 return 0;
952 }
953
Chris Lattner32707602005-09-08 23:22:48 +0000954 // Apply the type cast.
955 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000956 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000957 return New;
958 }
959
960 // Verify that this is something that makes sense for an operator.
961 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000962 !Operator->isSubClassOf("Instruction") &&
963 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner550525e2006-03-24 21:48:51 +0000964 !Operator->isSubClassOf("Intrinsic") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000965 Operator->getName() != "set")
966 error("Unrecognized node '" + Operator->getName() + "'!");
967
Chris Lattneredbd8712005-10-21 01:19:59 +0000968 // Check to see if this is something that is illegal in an input pattern.
969 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
Chris Lattner5a1df382006-03-24 23:10:39 +0000970 Operator->isSubClassOf("SDNodeXForm")))
Chris Lattneredbd8712005-10-21 01:19:59 +0000971 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
972
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000973 std::vector<TreePatternNode*> Children;
974
975 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
976 Init *Arg = Dag->getArg(i);
977 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
978 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000979 if (Children.back()->getName().empty())
980 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000981 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
982 Record *R = DefI->getDef();
983 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
984 // TreePatternNode if its own.
985 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000986 Dag->setArg(i, new DagInit(DefI,
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000987 std::vector<std::pair<Init*, std::string> >()));
988 --i; // Revisit this node...
989 } else {
990 TreePatternNode *Node = new TreePatternNode(DefI);
991 Node->setName(Dag->getArgName(i));
992 Children.push_back(Node);
993
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000994 // Input argument?
995 if (R->getName() == "node") {
996 if (Dag->getArgName(i).empty())
997 error("'node' argument requires a name to match with operand list");
998 Args.push_back(Dag->getArgName(i));
999 }
1000 }
Chris Lattner5d5a0562005-10-19 04:30:56 +00001001 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1002 TreePatternNode *Node = new TreePatternNode(II);
1003 if (!Dag->getArgName(i).empty())
1004 error("Constant int argument should not have a name!");
1005 Children.push_back(Node);
Chris Lattnerffa4fdc2006-03-31 05:25:56 +00001006 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1007 // Turn this into an IntInit.
1008 Init *II = BI->convertInitializerTo(new IntRecTy());
1009 if (II == 0 || !dynamic_cast<IntInit*>(II))
1010 error("Bits value must be constants!");
1011
1012 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1013 if (!Dag->getArgName(i).empty())
1014 error("Constant int argument should not have a name!");
1015 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001016 } else {
Bill Wendlingf5da1332006-12-07 22:21:48 +00001017 cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001018 Arg->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00001019 cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001020 error("Unknown leaf value for tree pattern!");
1021 }
1022 }
1023
Chris Lattner5a1df382006-03-24 23:10:39 +00001024 // If the operator is an intrinsic, then this is just syntactic sugar for for
1025 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1026 // convert the intrinsic name to a number.
1027 if (Operator->isSubClassOf("Intrinsic")) {
1028 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
1029 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
1030
1031 // If this intrinsic returns void, it must have side-effects and thus a
1032 // chain.
1033 if (Int.ArgVTs[0] == MVT::isVoid) {
1034 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
1035 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1036 // Has side-effects, requires chain.
1037 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
1038 } else {
1039 // Otherwise, no chain.
1040 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
1041 }
1042
1043 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1044 Children.insert(Children.begin(), IIDNode);
1045 }
1046
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001047 return new TreePatternNode(Operator, Children);
1048}
1049
Chris Lattner32707602005-09-08 23:22:48 +00001050/// InferAllTypes - Infer/propagate as many types throughout the expression
1051/// patterns as possible. Return true if all types are infered, false
1052/// otherwise. Throw an exception if a type contradiction is found.
1053bool TreePattern::InferAllTypes() {
1054 bool MadeChange = true;
1055 while (MadeChange) {
1056 MadeChange = false;
1057 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001058 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +00001059 }
1060
1061 bool HasUnresolvedTypes = false;
1062 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1063 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1064 return !HasUnresolvedTypes;
1065}
1066
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001067void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001068 OS << getRecord()->getName();
1069 if (!Args.empty()) {
1070 OS << "(" << Args[0];
1071 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1072 OS << ", " << Args[i];
1073 OS << ")";
1074 }
1075 OS << ": ";
1076
1077 if (Trees.size() > 1)
1078 OS << "[\n";
1079 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1080 OS << "\t";
1081 Trees[i]->print(OS);
1082 OS << "\n";
1083 }
1084
1085 if (Trees.size() > 1)
1086 OS << "]\n";
1087}
1088
Bill Wendlingf5da1332006-12-07 22:21:48 +00001089void TreePattern::dump() const { print(*cerr.stream()); }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001090
1091
1092
1093//===----------------------------------------------------------------------===//
1094// DAGISelEmitter implementation
1095//
1096
Chris Lattnerca559d02005-09-08 21:03:01 +00001097// Parse all of the SDNode definitions for the target, populating SDNodes.
1098void DAGISelEmitter::ParseNodeInfo() {
1099 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1100 while (!Nodes.empty()) {
1101 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1102 Nodes.pop_back();
1103 }
Chris Lattner5a1df382006-03-24 23:10:39 +00001104
1105 // Get the buildin intrinsic nodes.
1106 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1107 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1108 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
Chris Lattnerca559d02005-09-08 21:03:01 +00001109}
1110
Chris Lattner24eeeb82005-09-13 21:51:00 +00001111/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1112/// map, and emit them to the file as functions.
1113void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1114 OS << "\n// Node transformations.\n";
1115 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1116 while (!Xforms.empty()) {
1117 Record *XFormNode = Xforms.back();
1118 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1119 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1120 SDNodeXForms.insert(std::make_pair(XFormNode,
1121 std::make_pair(SDNode, Code)));
1122
Chris Lattner1048b7a2005-09-13 22:03:37 +00001123 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +00001124 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1125 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1126
Chris Lattner1048b7a2005-09-13 22:03:37 +00001127 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +00001128 << "(SDNode *" << C2 << ") {\n";
1129 if (ClassName != "SDNode")
1130 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1131 OS << Code << "\n}\n";
1132 }
1133
1134 Xforms.pop_back();
1135 }
1136}
1137
Evan Cheng0fc71982005-12-08 02:00:36 +00001138void DAGISelEmitter::ParseComplexPatterns() {
1139 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1140 while (!AMs.empty()) {
1141 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1142 AMs.pop_back();
1143 }
1144}
Chris Lattner24eeeb82005-09-13 21:51:00 +00001145
1146
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001147/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1148/// file, building up the PatternFragments map. After we've collected them all,
1149/// inline fragments together as necessary, so that there are no references left
1150/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001151///
1152/// This also emits all of the predicate functions to the output file.
1153///
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001154void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001155 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1156
1157 // First step, parse all of the fragments and emit predicate functions.
1158 OS << "\n// Predicate functions.\n";
1159 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001160 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +00001161 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001162 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +00001163
1164 // Validate the argument list, converting it to map, to discard duplicates.
1165 std::vector<std::string> &Args = P->getArgList();
1166 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1167
1168 if (OperandsMap.count(""))
1169 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1170
1171 // Parse the operands list.
1172 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Chris Lattner8c063182006-03-30 22:50:40 +00001173 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
Evan Cheng64d80e32007-07-19 01:14:50 +00001174 // Special cases: ops == outs == ins. Different names are used to
1175 // improve readibility.
1176 if (!OpsOp ||
1177 (OpsOp->getDef()->getName() != "ops" &&
1178 OpsOp->getDef()->getName() != "outs" &&
1179 OpsOp->getDef()->getName() != "ins"))
Chris Lattneree9f0c32005-09-13 21:20:49 +00001180 P->error("Operands list should start with '(ops ... '!");
1181
1182 // Copy over the arguments.
1183 Args.clear();
1184 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1185 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1186 static_cast<DefInit*>(OpsList->getArg(j))->
1187 getDef()->getName() != "node")
1188 P->error("Operands list should all be 'node' values.");
1189 if (OpsList->getArgName(j).empty())
1190 P->error("Operands list should have names for each operand!");
1191 if (!OperandsMap.count(OpsList->getArgName(j)))
1192 P->error("'" + OpsList->getArgName(j) +
1193 "' does not occur in pattern or was multiply specified!");
1194 OperandsMap.erase(OpsList->getArgName(j));
1195 Args.push_back(OpsList->getArgName(j));
1196 }
1197
1198 if (!OperandsMap.empty())
1199 P->error("Operands list does not contain an entry for operand '" +
1200 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001201
1202 // If there is a code init for this fragment, emit the predicate code and
1203 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +00001204 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1205 if (!Code.empty()) {
Evan Chengd46bd602006-09-19 19:08:04 +00001206 if (P->getOnlyTree()->isLeaf())
1207 OS << "inline bool Predicate_" << Fragments[i]->getName()
1208 << "(SDNode *N) {\n";
1209 else {
1210 std::string ClassName =
1211 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1212 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001213
Evan Chengd46bd602006-09-19 19:08:04 +00001214 OS << "inline bool Predicate_" << Fragments[i]->getName()
1215 << "(SDNode *" << C2 << ") {\n";
1216 if (ClassName != "SDNode")
1217 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1218 }
Chris Lattner24eeeb82005-09-13 21:51:00 +00001219 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +00001220 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001221 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001222
1223 // If there is a node transformation corresponding to this, keep track of
1224 // it.
1225 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1226 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001227 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001228 }
1229
1230 OS << "\n\n";
1231
1232 // Now that we've parsed all of the tree fragments, do a closure on them so
1233 // that there are not references to PatFrags left inside of them.
1234 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1235 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001236 TreePattern *ThePat = I->second;
1237 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001238
Chris Lattner32707602005-09-08 23:22:48 +00001239 // Infer as many types as possible. Don't worry about it if we don't infer
1240 // all of them, some may depend on the inputs of the pattern.
1241 try {
1242 ThePat->InferAllTypes();
1243 } catch (...) {
1244 // If this pattern fragment is not supported by this target (no types can
1245 // satisfy its constraints), just ignore it. If the bogus pattern is
1246 // actually used by instructions, the type consistency error will be
1247 // reported there.
1248 }
1249
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001250 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001251 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001252 }
1253}
1254
Evan Chenga9559392007-07-06 01:05:26 +00001255void DAGISelEmitter::ParseDefaultOperands() {
1256 std::vector<Record*> DefaultOps[2];
1257 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1258 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001259
1260 // Find some SDNode.
1261 assert(!SDNodes.empty() && "No SDNodes parsed?");
1262 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1263
Evan Chenga9559392007-07-06 01:05:26 +00001264 for (unsigned iter = 0; iter != 2; ++iter) {
1265 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1266 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001267
Evan Chenga9559392007-07-06 01:05:26 +00001268 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1269 // SomeSDnode so that we can parse this.
1270 std::vector<std::pair<Init*, std::string> > Ops;
1271 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1272 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1273 DefaultInfo->getArgName(op)));
1274 DagInit *DI = new DagInit(SomeSDNode, Ops);
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001275
Evan Chenga9559392007-07-06 01:05:26 +00001276 // Create a TreePattern to parse this.
1277 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1278 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001279
Evan Chenga9559392007-07-06 01:05:26 +00001280 // Copy the operands over into a DAGDefaultOperand.
1281 DAGDefaultOperand DefaultOpInfo;
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001282
Evan Chenga9559392007-07-06 01:05:26 +00001283 TreePatternNode *T = P.getTree(0);
1284 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1285 TreePatternNode *TPN = T->getChild(op);
1286 while (TPN->ApplyTypeConstraints(P, false))
1287 /* Resolve all types */;
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001288
Evan Chenga9559392007-07-06 01:05:26 +00001289 if (TPN->ContainsUnresolvedType())
1290 if (iter == 0)
1291 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1292 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1293 else
1294 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1295 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001296
Evan Chenga9559392007-07-06 01:05:26 +00001297 DefaultOpInfo.DefaultOps.push_back(TPN);
1298 }
1299
1300 // Insert it into the DefaultOperands map so we can find it later.
1301 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001302 }
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00001303 }
1304}
1305
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001306/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001307/// instruction input. Return true if this is a real use.
1308static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001309 std::map<std::string, TreePatternNode*> &InstInputs,
1310 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001311 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001312 if (Pat->getName().empty()) {
1313 if (Pat->isLeaf()) {
1314 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1315 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1316 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001317 else if (DI && DI->getDef()->isSubClassOf("Register"))
1318 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001319 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001320 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001321 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001322
1323 Record *Rec;
1324 if (Pat->isLeaf()) {
1325 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1326 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1327 Rec = DI->getDef();
1328 } else {
1329 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1330 Rec = Pat->getOperator();
1331 }
1332
Evan Cheng01f318b2005-12-14 02:21:57 +00001333 // SRCVALUE nodes are ignored.
1334 if (Rec->getName() == "srcvalue")
1335 return false;
1336
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001337 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1338 if (!Slot) {
1339 Slot = Pat;
1340 } else {
1341 Record *SlotRec;
1342 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001343 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001344 } else {
1345 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1346 SlotRec = Slot->getOperator();
1347 }
1348
1349 // Ensure that the inputs agree if we've already seen this input.
1350 if (Rec != SlotRec)
1351 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001352 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001353 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1354 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001355 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001356}
1357
1358/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1359/// part of "I", the instruction), computing the set of inputs and outputs of
1360/// the pattern. Report errors if we see anything naughty.
1361void DAGISelEmitter::
1362FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1363 std::map<std::string, TreePatternNode*> &InstInputs,
Chris Lattner947604b2006-03-24 21:52:20 +00001364 std::map<std::string, TreePatternNode*>&InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001365 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001366 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001367 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001368 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001369 if (!isUse && Pat->getTransformFn())
1370 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001371 return;
1372 } else if (Pat->getOperator()->getName() != "set") {
1373 // If this is not a set, verify that the children nodes are not void typed,
1374 // and recurse.
1375 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001376 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001377 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001378 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001379 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001380 }
1381
1382 // If this is a non-leaf node with no children, treat it basically as if
1383 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001384 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001385 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001386 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001387
Chris Lattnerf1311842005-09-14 23:05:13 +00001388 if (!isUse && Pat->getTransformFn())
1389 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001390 return;
1391 }
1392
1393 // Otherwise, this is a set, validate and collect instruction results.
1394 if (Pat->getNumChildren() == 0)
1395 I->error("set requires operands!");
1396 else if (Pat->getNumChildren() & 1)
1397 I->error("set requires an even number of operands");
1398
Chris Lattnerf1311842005-09-14 23:05:13 +00001399 if (Pat->getTransformFn())
1400 I->error("Cannot specify a transform function on a set node!");
1401
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001402 // Check the set destinations.
1403 unsigned NumValues = Pat->getNumChildren()/2;
1404 for (unsigned i = 0; i != NumValues; ++i) {
1405 TreePatternNode *Dest = Pat->getChild(i);
1406 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001407 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001408
1409 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1410 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001411 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001412
Chris Lattner646085d2006-11-14 21:18:40 +00001413 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1414 Val->getDef()->getName() == "ptr_rc") {
Evan Chengbcecf332005-12-17 01:19:28 +00001415 if (Dest->getName().empty())
1416 I->error("set destination must have a name!");
1417 if (InstResults.count(Dest->getName()))
1418 I->error("cannot set '" + Dest->getName() +"' multiple times");
Evan Cheng420132e2006-03-20 06:04:09 +00001419 InstResults[Dest->getName()] = Dest;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001420 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001421 InstImpResults.push_back(Val->getDef());
1422 } else {
1423 I->error("set destination should be a register!");
1424 }
1425
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001426 // Verify and collect info from the computation.
1427 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001428 InstInputs, InstResults,
1429 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001430 }
1431}
1432
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001433/// ParseInstructions - Parse all of the instructions, inlining and resolving
1434/// any fragments involved. This populates the Instructions list with fully
1435/// resolved instructions.
1436void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001437 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1438
1439 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001440 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001441
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001442 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1443 LI = Instrs[i]->getValueAsListInit("Pattern");
1444
1445 // If there is no pattern, only collect minimal information about the
1446 // instruction for its operand list. We have to assume that there is one
1447 // result, as we have no detailed info.
1448 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001449 std::vector<Record*> Results;
1450 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001451
1452 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001453
Evan Cheng3a217f32005-12-22 02:35:21 +00001454 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001455 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001456 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001457 // These produce no results
1458 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1459 Operands.push_back(InstInfo.OperandList[j].Rec);
1460 } else {
1461 // Assume the first operand is the result.
1462 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001463
Evan Cheng3a217f32005-12-22 02:35:21 +00001464 // The rest are inputs.
1465 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1466 Operands.push_back(InstInfo.OperandList[j].Rec);
1467 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001468 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001469
1470 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001471 std::vector<Record*> ImpResults;
1472 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001473 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001474 DAGInstruction(0, Results, Operands, ImpResults,
1475 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001476 continue; // no pattern.
1477 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001478
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001479 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001480 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001481 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001482 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001483
Chris Lattner95f6b762005-09-08 23:26:30 +00001484 // Infer as many types as possible. If we cannot infer all of them, we can
1485 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001486 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001487 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001488
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001489 // InstInputs - Keep track of all of the inputs of the instruction, along
1490 // with the record they are declared as.
1491 std::map<std::string, TreePatternNode*> InstInputs;
1492
1493 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001494 // in the instruction, including what reg class they are.
Evan Cheng420132e2006-03-20 06:04:09 +00001495 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001496
1497 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001498 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001499
Chris Lattner1f39e292005-09-14 00:09:24 +00001500 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001501 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001502 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1503 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001504 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001505 I->error("Top-level forms in instruction pattern should have"
1506 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001507
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001508 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001509 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001510 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001511 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001512
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001513 // Now that we have inputs and outputs of the pattern, inspect the operands
1514 // list for the instruction. This determines the order that operands are
1515 // added to the machine instruction the node corresponds to.
1516 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001517
1518 // Parse the operands list from the (ops) list, validating it.
Chris Lattner20c2b352007-06-19 06:40:46 +00001519 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001520 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1521
1522 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001523 std::vector<Record*> Results;
Evan Cheng420132e2006-03-20 06:04:09 +00001524 TreePatternNode *Res0Node = NULL;
Chris Lattner39e8af92005-09-14 18:19:25 +00001525 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001526 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001527 I->error("'" + InstResults.begin()->first +
1528 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001529 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001530
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001531 // Check that it exists in InstResults.
Evan Cheng420132e2006-03-20 06:04:09 +00001532 TreePatternNode *RNode = InstResults[OpName];
Chris Lattner5c4c7742006-03-25 22:12:44 +00001533 if (RNode == 0)
1534 I->error("Operand $" + OpName + " does not exist in operand list!");
1535
Evan Cheng420132e2006-03-20 06:04:09 +00001536 if (i == 0)
1537 Res0Node = RNode;
1538 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner39e8af92005-09-14 18:19:25 +00001539 if (R == 0)
1540 I->error("Operand $" + OpName + " should be a set destination: all "
1541 "outputs must occur before inputs in operand list!");
1542
1543 if (CGI.OperandList[i].Rec != R)
1544 I->error("Operand $" + OpName + " class mismatch!");
1545
Chris Lattnerae6d8282005-09-15 21:51:12 +00001546 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001547 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001548
Chris Lattner39e8af92005-09-14 18:19:25 +00001549 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001550 InstResults.erase(OpName);
1551 }
1552
Chris Lattner0b592252005-09-14 21:59:34 +00001553 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1554 // the copy while we're checking the inputs.
1555 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001556
1557 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001558 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001559 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001560 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1561 const std::string &OpName = Op.Name;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001562 if (OpName.empty())
1563 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1564
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001565 if (!InstInputsCheck.count(OpName)) {
Evan Chenga9559392007-07-06 01:05:26 +00001566 // If this is an predicate operand or optional def operand with an
1567 // DefaultOps set filled in, we can ignore this. When we codegen it,
1568 // we will do so as always executed.
1569 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1570 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1571 // Does it have a non-empty DefaultOps field? If so, ignore this
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001572 // operand.
Evan Chenga9559392007-07-06 01:05:26 +00001573 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001574 continue;
1575 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001576 I->error("Operand $" + OpName +
1577 " does not appear in the instruction pattern");
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001578 }
Chris Lattner0b592252005-09-14 21:59:34 +00001579 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001580 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001581
1582 if (InVal->isLeaf() &&
1583 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1584 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001585 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001586 I->error("Operand $" + OpName + "'s register class disagrees"
1587 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001588 }
Chris Lattnerdfdaeb22006-11-04 01:35:50 +00001589 Operands.push_back(Op.Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001590
Chris Lattner2175c182005-09-14 23:01:59 +00001591 // Construct the result for the dest-pattern operand list.
1592 TreePatternNode *OpNode = InVal->clone();
1593
1594 // No predicate is useful on the result.
1595 OpNode->setPredicateFn("");
1596
1597 // Promote the xform function to be an explicit node if set.
1598 if (Record *Xform = OpNode->getTransformFn()) {
1599 OpNode->setTransformFn(0);
1600 std::vector<TreePatternNode*> Children;
1601 Children.push_back(OpNode);
1602 OpNode = new TreePatternNode(Xform, Children);
1603 }
1604
1605 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001606 }
1607
Chris Lattner0b592252005-09-14 21:59:34 +00001608 if (!InstInputsCheck.empty())
1609 I->error("Input operand $" + InstInputsCheck.begin()->first +
1610 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001611
1612 TreePatternNode *ResultPattern =
1613 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Evan Cheng420132e2006-03-20 06:04:09 +00001614 // Copy fully inferred output node type to instruction result pattern.
1615 if (NumResults > 0)
1616 ResultPattern->setTypes(Res0Node->getExtTypes());
Chris Lattnera28aec12005-09-15 22:23:50 +00001617
1618 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001619 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001620 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1621
1622 // Use a temporary tree pattern to infer all types and make sure that the
1623 // constructed result is correct. This depends on the instruction already
1624 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001625 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001626 Temp.InferAllTypes();
1627
1628 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1629 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001630
Chris Lattner32707602005-09-08 23:22:48 +00001631 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001632 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001633
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001634 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001635 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1636 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001637 DAGInstruction &TheInst = II->second;
1638 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001639 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001640
Chris Lattner1f39e292005-09-14 00:09:24 +00001641 if (I->getNumTrees() != 1) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00001642 cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
Chris Lattner1f39e292005-09-14 00:09:24 +00001643 continue;
1644 }
1645 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001646 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001647 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001648 if (Pattern->getNumChildren() != 2)
1649 continue; // Not a set of a single value (not handled so far)
1650
1651 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001652 } else{
1653 // Not a set (store or something?)
1654 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001655 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001656
1657 std::string Reason;
1658 if (!SrcPattern->canPatternMatch(Reason, *this))
1659 I->error("Instruction can never match: " + Reason);
1660
Evan Cheng58e84a62005-12-14 22:02:59 +00001661 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001662 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001663 PatternsToMatch.
1664 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
Evan Cheng59413202006-04-19 18:07:24 +00001665 SrcPattern, DstPattern,
Evan Chengc81d2a02006-04-19 20:36:09 +00001666 Instr->getValueAsInt("AddedComplexity")));
Chris Lattner1f39e292005-09-14 00:09:24 +00001667 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001668}
1669
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001670void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001671 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001672
Chris Lattnerabbb6052005-09-15 21:42:00 +00001673 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001674 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001675 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001676
Chris Lattnerabbb6052005-09-15 21:42:00 +00001677 // Inline pattern fragments into it.
1678 Pattern->InlinePatternFragments();
1679
Chris Lattnera3548492006-06-20 00:18:02 +00001680 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1681 if (LI->getSize() == 0) continue; // no pattern.
1682
1683 // Parse the instruction.
1684 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1685
1686 // Inline pattern fragments into it.
1687 Result->InlinePatternFragments();
Chris Lattner09c03392005-11-17 17:43:52 +00001688
Chris Lattnera3548492006-06-20 00:18:02 +00001689 if (Result->getNumTrees() != 1)
1690 Result->error("Cannot handle instructions producing instructions "
1691 "with temporaries yet!");
1692
1693 bool IterateInference;
Chris Lattner186fb7d2006-06-20 00:31:27 +00001694 bool InferredAllPatternTypes, InferredAllResultTypes;
Chris Lattnera3548492006-06-20 00:18:02 +00001695 do {
1696 // Infer as many types as possible. If we cannot infer all of them, we
1697 // can never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001698 InferredAllPatternTypes = Pattern->InferAllTypes();
Chris Lattnera3548492006-06-20 00:18:02 +00001699
Chris Lattner64906972006-09-21 18:28:27 +00001700 // Infer as many types as possible. If we cannot infer all of them, we
1701 // can never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001702 InferredAllResultTypes = Result->InferAllTypes();
1703
Chris Lattnera3548492006-06-20 00:18:02 +00001704 // Apply the type of the result to the source pattern. This helps us
1705 // resolve cases where the input type is known to be a pointer type (which
1706 // is considered resolved), but the result knows it needs to be 32- or
1707 // 64-bits. Infer the other way for good measure.
1708 IterateInference = Pattern->getOnlyTree()->
1709 UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1710 IterateInference |= Result->getOnlyTree()->
1711 UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1712 } while (IterateInference);
Chris Lattner186fb7d2006-06-20 00:31:27 +00001713
1714 // Verify that we inferred enough types that we can do something with the
1715 // pattern and result. If these fire the user has to add type casts.
1716 if (!InferredAllPatternTypes)
1717 Pattern->error("Could not infer all types in pattern!");
1718 if (!InferredAllResultTypes)
1719 Result->error("Could not infer all types in pattern result!");
Chris Lattnera3548492006-06-20 00:18:02 +00001720
Chris Lattner09c03392005-11-17 17:43:52 +00001721 // Validate that the input pattern is correct.
1722 {
1723 std::map<std::string, TreePatternNode*> InstInputs;
Evan Cheng420132e2006-03-20 06:04:09 +00001724 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001725 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001726 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001727 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001728 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001729 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001730 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001731
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001732 // Promote the xform function to be an explicit node if set.
1733 std::vector<TreePatternNode*> ResultNodeOperands;
1734 TreePatternNode *DstPattern = Result->getOnlyTree();
1735 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1736 TreePatternNode *OpNode = DstPattern->getChild(ii);
1737 if (Record *Xform = OpNode->getTransformFn()) {
1738 OpNode->setTransformFn(0);
1739 std::vector<TreePatternNode*> Children;
1740 Children.push_back(OpNode);
1741 OpNode = new TreePatternNode(Xform, Children);
1742 }
1743 ResultNodeOperands.push_back(OpNode);
1744 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00001745 DstPattern = Result->getOnlyTree();
1746 if (!DstPattern->isLeaf())
1747 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1748 ResultNodeOperands);
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001749 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1750 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1751 Temp.InferAllTypes();
1752
Chris Lattnere97603f2005-09-28 19:27:25 +00001753 std::string Reason;
1754 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1755 Pattern->error("Pattern can never match: " + Reason);
1756
Evan Cheng58e84a62005-12-14 22:02:59 +00001757 PatternsToMatch.
1758 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1759 Pattern->getOnlyTree(),
Evan Cheng59413202006-04-19 18:07:24 +00001760 Temp.getOnlyTree(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001761 Patterns[i]->getValueAsInt("AddedComplexity")));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001762 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001763}
1764
Chris Lattnere46e17b2005-09-29 19:28:10 +00001765/// CombineChildVariants - Given a bunch of permutations of each child of the
1766/// 'operator' node, put them together in all possible ways.
1767static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001768 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001769 std::vector<TreePatternNode*> &OutVariants,
1770 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001771 // Make sure that each operand has at least one variant to choose from.
1772 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1773 if (ChildVariants[i].empty())
1774 return;
1775
Chris Lattnere46e17b2005-09-29 19:28:10 +00001776 // The end result is an all-pairs construction of the resultant pattern.
1777 std::vector<unsigned> Idxs;
1778 Idxs.resize(ChildVariants.size());
1779 bool NotDone = true;
1780 while (NotDone) {
1781 // Create the variant and add it to the output list.
1782 std::vector<TreePatternNode*> NewChildren;
1783 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1784 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1785 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1786
1787 // Copy over properties.
1788 R->setName(Orig->getName());
1789 R->setPredicateFn(Orig->getPredicateFn());
1790 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001791 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001792
1793 // If this pattern cannot every match, do not include it as a variant.
1794 std::string ErrString;
1795 if (!R->canPatternMatch(ErrString, ISE)) {
1796 delete R;
1797 } else {
1798 bool AlreadyExists = false;
1799
1800 // Scan to see if this pattern has already been emitted. We can get
1801 // duplication due to things like commuting:
1802 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1803 // which are the same pattern. Ignore the dups.
1804 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1805 if (R->isIsomorphicTo(OutVariants[i])) {
1806 AlreadyExists = true;
1807 break;
1808 }
1809
1810 if (AlreadyExists)
1811 delete R;
1812 else
1813 OutVariants.push_back(R);
1814 }
1815
1816 // Increment indices to the next permutation.
1817 NotDone = false;
1818 // Look for something we can increment without causing a wrap-around.
1819 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1820 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1821 NotDone = true; // Found something to increment.
1822 break;
1823 }
1824 Idxs[IdxsIdx] = 0;
1825 }
1826 }
1827}
1828
Chris Lattneraf302912005-09-29 22:36:54 +00001829/// CombineChildVariants - A helper function for binary operators.
1830///
1831static void CombineChildVariants(TreePatternNode *Orig,
1832 const std::vector<TreePatternNode*> &LHS,
1833 const std::vector<TreePatternNode*> &RHS,
1834 std::vector<TreePatternNode*> &OutVariants,
1835 DAGISelEmitter &ISE) {
1836 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1837 ChildVariants.push_back(LHS);
1838 ChildVariants.push_back(RHS);
1839 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1840}
1841
1842
1843static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1844 std::vector<TreePatternNode *> &Children) {
1845 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1846 Record *Operator = N->getOperator();
1847
1848 // Only permit raw nodes.
1849 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1850 N->getTransformFn()) {
1851 Children.push_back(N);
1852 return;
1853 }
1854
1855 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1856 Children.push_back(N->getChild(0));
1857 else
1858 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1859
1860 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1861 Children.push_back(N->getChild(1));
1862 else
1863 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1864}
1865
Chris Lattnere46e17b2005-09-29 19:28:10 +00001866/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1867/// the (potentially recursive) pattern by using algebraic laws.
1868///
1869static void GenerateVariantsOf(TreePatternNode *N,
1870 std::vector<TreePatternNode*> &OutVariants,
1871 DAGISelEmitter &ISE) {
1872 // We cannot permute leaves.
1873 if (N->isLeaf()) {
1874 OutVariants.push_back(N);
1875 return;
1876 }
1877
1878 // Look up interesting info about the node.
Chris Lattner5a1df382006-03-24 23:10:39 +00001879 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001880
1881 // If this node is associative, reassociate.
Evan Cheng94b30402006-10-11 21:02:01 +00001882 if (NodeInfo.hasProperty(SDNPAssociative)) {
Chris Lattneraf302912005-09-29 22:36:54 +00001883 // Reassociate by pulling together all of the linked operators
1884 std::vector<TreePatternNode*> MaximalChildren;
1885 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1886
1887 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1888 // permutations.
1889 if (MaximalChildren.size() == 3) {
1890 // Find the variants of all of our maximal children.
1891 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1892 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1893 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1894 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1895
1896 // There are only two ways we can permute the tree:
1897 // (A op B) op C and A op (B op C)
1898 // Within these forms, we can also permute A/B/C.
1899
1900 // Generate legal pair permutations of A/B/C.
1901 std::vector<TreePatternNode*> ABVariants;
1902 std::vector<TreePatternNode*> BAVariants;
1903 std::vector<TreePatternNode*> ACVariants;
1904 std::vector<TreePatternNode*> CAVariants;
1905 std::vector<TreePatternNode*> BCVariants;
1906 std::vector<TreePatternNode*> CBVariants;
1907 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1908 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1909 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1910 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1911 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1912 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1913
1914 // Combine those into the result: (x op x) op x
1915 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1916 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1917 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1918 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1919 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1920 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1921
1922 // Combine those into the result: x op (x op x)
1923 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1924 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1925 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1926 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1927 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1928 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1929 return;
1930 }
1931 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001932
1933 // Compute permutations of all children.
1934 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1935 ChildVariants.resize(N->getNumChildren());
1936 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1937 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1938
1939 // Build all permutations based on how the children were formed.
1940 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1941
1942 // If this node is commutative, consider the commuted order.
Evan Cheng94b30402006-10-11 21:02:01 +00001943 if (NodeInfo.hasProperty(SDNPCommutative)) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001944 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattner706d2d32006-08-09 16:44:44 +00001945 // Don't count children which are actually register references.
1946 unsigned NC = 0;
1947 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1948 TreePatternNode *Child = N->getChild(i);
1949 if (Child->isLeaf())
1950 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1951 Record *RR = DI->getDef();
1952 if (RR->isSubClassOf("Register"))
1953 continue;
1954 }
1955 NC++;
1956 }
Chris Lattneraf302912005-09-29 22:36:54 +00001957 // Consider the commuted order.
Chris Lattner706d2d32006-08-09 16:44:44 +00001958 if (NC == 2)
1959 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1960 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001961 }
1962}
1963
1964
Chris Lattnere97603f2005-09-28 19:27:25 +00001965// GenerateVariants - Generate variants. For example, commutative patterns can
1966// match multiple ways. Add them to PatternsToMatch as well.
1967void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001968
Bill Wendlingf5da1332006-12-07 22:21:48 +00001969 DOUT << "Generating instruction variants.\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00001970
1971 // Loop over all of the patterns we've collected, checking to see if we can
1972 // generate variants of the instruction, through the exploitation of
1973 // identities. This permits the target to provide agressive matching without
1974 // the .td file having to contain tons of variants of instructions.
1975 //
1976 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1977 // intentionally do not reconsider these. Any variants of added patterns have
1978 // already been added.
1979 //
1980 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1981 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001982 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001983
1984 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001985 Variants.erase(Variants.begin()); // Remove the original pattern.
1986
1987 if (Variants.empty()) // No variants for this pattern.
1988 continue;
1989
Bill Wendlingf5da1332006-12-07 22:21:48 +00001990 DOUT << "FOUND VARIANTS OF: ";
1991 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
1992 DOUT << "\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00001993
1994 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1995 TreePatternNode *Variant = Variants[v];
1996
Bill Wendlingf5da1332006-12-07 22:21:48 +00001997 DOUT << " VAR#" << v << ": ";
1998 DEBUG(Variant->dump());
1999 DOUT << "\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00002000
2001 // Scan to see if an instruction or explicit pattern already matches this.
2002 bool AlreadyExists = false;
2003 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2004 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00002005 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00002006 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00002007 AlreadyExists = true;
2008 break;
2009 }
2010 }
2011 // If we already have it, ignore the variant.
2012 if (AlreadyExists) continue;
2013
2014 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00002015 PatternsToMatch.
2016 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
Evan Cheng59413202006-04-19 18:07:24 +00002017 Variant, PatternsToMatch[i].getDstPattern(),
Evan Chengc81d2a02006-04-19 20:36:09 +00002018 PatternsToMatch[i].getAddedComplexity()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00002019 }
2020
Bill Wendlingf5da1332006-12-07 22:21:48 +00002021 DOUT << "\n";
Chris Lattnere46e17b2005-09-29 19:28:10 +00002022 }
Chris Lattnere97603f2005-09-28 19:27:25 +00002023}
2024
Evan Cheng0fc71982005-12-08 02:00:36 +00002025// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
2026// ComplexPattern.
2027static bool NodeIsComplexPattern(TreePatternNode *N)
2028{
2029 return (N->isLeaf() &&
2030 dynamic_cast<DefInit*>(N->getLeafValue()) &&
2031 static_cast<DefInit*>(N->getLeafValue())->getDef()->
2032 isSubClassOf("ComplexPattern"));
2033}
2034
2035// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
2036// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
2037static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
2038 DAGISelEmitter &ISE)
2039{
2040 if (N->isLeaf() &&
2041 dynamic_cast<DefInit*>(N->getLeafValue()) &&
2042 static_cast<DefInit*>(N->getLeafValue())->getDef()->
2043 isSubClassOf("ComplexPattern")) {
2044 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
2045 ->getDef());
2046 }
2047 return NULL;
2048}
2049
Chris Lattner05814af2005-09-28 17:57:56 +00002050/// getPatternSize - Return the 'size' of this pattern. We want to match large
2051/// patterns before small ones. This is used to determine the size of a
2052/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00002053static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng2618d072006-05-17 20:37:59 +00002054 assert((isExtIntegerInVTs(P->getExtTypes()) ||
2055 isExtFloatingPointInVTs(P->getExtTypes()) ||
2056 P->getExtTypeNum(0) == MVT::isVoid ||
2057 P->getExtTypeNum(0) == MVT::Flag ||
2058 P->getExtTypeNum(0) == MVT::iPTR) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +00002059 "Not a valid pattern node to size!");
Evan Cheng6cec34e2006-09-08 07:26:39 +00002060 unsigned Size = 3; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00002061 // If the root node is a ConstantSDNode, increases its size.
2062 // e.g. (set R32:$dst, 0).
2063 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +00002064 Size += 2;
Evan Cheng0fc71982005-12-08 02:00:36 +00002065
2066 // FIXME: This is a hack to statically increase the priority of patterns
2067 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
2068 // Later we can allow complexity / cost for each pattern to be (optionally)
2069 // specified. To get best possible pattern match we'll need to dynamically
2070 // calculate the complexity of all patterns a dag can potentially map to.
2071 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
2072 if (AM)
Evan Cheng6cec34e2006-09-08 07:26:39 +00002073 Size += AM->getNumOperands() * 3;
Chris Lattner3e179802006-02-03 18:06:02 +00002074
2075 // If this node has some predicate function that must match, it adds to the
2076 // complexity of this node.
2077 if (!P->getPredicateFn().empty())
2078 ++Size;
2079
Chris Lattner05814af2005-09-28 17:57:56 +00002080 // Count children in the count if they are also nodes.
2081 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
2082 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00002083 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00002084 Size += getPatternSize(Child, ISE);
2085 else if (Child->isLeaf()) {
2086 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +00002087 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Evan Cheng4a7c2842006-01-06 22:19:44 +00002088 else if (NodeIsComplexPattern(Child))
2089 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00002090 else if (!Child->getPredicateFn().empty())
2091 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00002092 }
Chris Lattner05814af2005-09-28 17:57:56 +00002093 }
2094
2095 return Size;
2096}
2097
2098/// getResultPatternCost - Compute the number of instructions for this pattern.
2099/// This is a temporary hack. We should really include the instruction
2100/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00002101static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00002102 if (P->isLeaf()) return 0;
2103
Evan Chengfbad7082006-02-18 02:33:09 +00002104 unsigned Cost = 0;
2105 Record *Op = P->getOperator();
2106 if (Op->isSubClassOf("Instruction")) {
2107 Cost++;
2108 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
2109 if (II.usesCustomDAGSchedInserter)
2110 Cost += 10;
2111 }
Chris Lattner05814af2005-09-28 17:57:56 +00002112 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00002113 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00002114 return Cost;
2115}
2116
Evan Chenge6f32032006-07-19 00:24:41 +00002117/// getResultPatternCodeSize - Compute the code size of instructions for this
2118/// pattern.
2119static unsigned getResultPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
2120 if (P->isLeaf()) return 0;
2121
2122 unsigned Cost = 0;
2123 Record *Op = P->getOperator();
2124 if (Op->isSubClassOf("Instruction")) {
2125 Cost += Op->getValueAsInt("CodeSize");
2126 }
2127 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2128 Cost += getResultPatternSize(P->getChild(i), ISE);
2129 return Cost;
2130}
2131
Chris Lattner05814af2005-09-28 17:57:56 +00002132// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
2133// In particular, we want to match maximal patterns first and lowest cost within
2134// a particular complexity first.
2135struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00002136 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
2137 DAGISelEmitter &ISE;
2138
Evan Cheng58e84a62005-12-14 22:02:59 +00002139 bool operator()(PatternToMatch *LHS,
2140 PatternToMatch *RHS) {
2141 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
2142 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Evan Chengc81d2a02006-04-19 20:36:09 +00002143 LHSSize += LHS->getAddedComplexity();
2144 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +00002145 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
2146 if (LHSSize < RHSSize) return false;
2147
2148 // If the patterns have equal complexity, compare generated instruction cost
Evan Chenge6f32032006-07-19 00:24:41 +00002149 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), ISE);
2150 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), ISE);
2151 if (LHSCost < RHSCost) return true;
2152 if (LHSCost > RHSCost) return false;
2153
2154 return getResultPatternSize(LHS->getDstPattern(), ISE) <
2155 getResultPatternSize(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00002156 }
2157};
2158
Nate Begeman6510b222005-12-01 04:51:06 +00002159/// getRegisterValueType - Look up and return the first ValueType of specified
2160/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00002161static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00002162 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2163 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00002164 return MVT::Other;
2165}
2166
Chris Lattner72fe91c2005-09-24 00:40:24 +00002167
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002168/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2169/// type information from it.
2170static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00002171 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002172 if (!N->isLeaf())
2173 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2174 RemoveAllTypes(N->getChild(i));
2175}
Chris Lattner72fe91c2005-09-24 00:40:24 +00002176
Chris Lattner0614b622005-11-02 06:49:14 +00002177Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2178 Record *N = Records.getDef(Name);
Chris Lattner5a1df382006-03-24 23:10:39 +00002179 if (!N || !N->isSubClassOf("SDNode")) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00002180 cerr << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner5a1df382006-03-24 23:10:39 +00002181 exit(1);
2182 }
Chris Lattner0614b622005-11-02 06:49:14 +00002183 return N;
2184}
2185
Evan Cheng51fecc82006-01-09 18:27:06 +00002186/// NodeHasProperty - return true if TreePatternNode has the specified
2187/// property.
Evan Cheng94b30402006-10-11 21:02:01 +00002188static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
Evan Cheng51fecc82006-01-09 18:27:06 +00002189 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002190{
Evan Cheng94b30402006-10-11 21:02:01 +00002191 if (N->isLeaf()) {
2192 const ComplexPattern *CP = NodeGetComplexPattern(N, ISE);
2193 if (CP)
2194 return CP->hasProperty(Property);
2195 return false;
2196 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002197 Record *Operator = N->getOperator();
2198 if (!Operator->isSubClassOf("SDNode")) return false;
2199
2200 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00002201 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002202}
2203
Evan Cheng94b30402006-10-11 21:02:01 +00002204static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
Evan Cheng51fecc82006-01-09 18:27:06 +00002205 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002206{
Evan Cheng51fecc82006-01-09 18:27:06 +00002207 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00002208 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00002209
2210 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2211 TreePatternNode *Child = N->getChild(i);
2212 if (PatternHasProperty(Child, Property, ISE))
2213 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002214 }
2215
2216 return false;
2217}
2218
Evan Chengb915f312005-12-09 22:45:35 +00002219class PatternCodeEmitter {
2220private:
2221 DAGISelEmitter &ISE;
2222
Evan Cheng58e84a62005-12-14 22:02:59 +00002223 // Predicates.
2224 ListInit *Predicates;
Evan Cheng59413202006-04-19 18:07:24 +00002225 // Pattern cost.
2226 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +00002227 // Instruction selector pattern.
2228 TreePatternNode *Pattern;
2229 // Matched instruction.
2230 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002231
Evan Chengb915f312005-12-09 22:45:35 +00002232 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00002233 std::map<std::string, std::string> VariableMap;
2234 // Node to operator mapping
2235 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00002236 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002237 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Cheng4326ef52006-10-12 02:08:53 +00002238 // Original input chain(s).
2239 std::vector<std::pair<std::string, std::string> > OrigChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00002240 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +00002241
Evan Cheng676d7312006-08-26 00:59:04 +00002242 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +00002243 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +00002244 /// tested, and if true, the match fails) [when 1], or normal code to emit
2245 /// [when 0], or initialization code to emit [when 2].
2246 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002247 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2248 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +00002249 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +00002250 /// TargetOpcodes - The target specific opcodes used by the resulting
2251 /// instructions.
2252 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +00002253 std::vector<std::string> &TargetVTs;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002254
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002255 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002256 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +00002257 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +00002258 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002259
2260 void emitCheck(const std::string &S) {
2261 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +00002262 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002263 }
2264 void emitCode(const std::string &S) {
2265 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +00002266 GeneratedCode.push_back(std::make_pair(0, S));
2267 }
2268 void emitInit(const std::string &S) {
2269 if (!S.empty())
2270 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002271 }
Evan Chengf5493192006-08-26 01:02:19 +00002272 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002273 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +00002274 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +00002275 }
Evan Chengfceb57a2006-07-15 08:45:20 +00002276 void emitOpcode(const std::string &Opc) {
2277 TargetOpcodes.push_back(Opc);
2278 OpcNo++;
2279 }
Evan Chengf8729402006-07-16 06:12:52 +00002280 void emitVT(const std::string &VT) {
2281 TargetVTs.push_back(VT);
2282 VTNo++;
2283 }
Evan Chengb915f312005-12-09 22:45:35 +00002284public:
Evan Cheng58e84a62005-12-14 22:02:59 +00002285 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2286 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +00002287 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +00002288 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +00002289 std::vector<std::string> &to,
Chris Lattner706d2d32006-08-09 16:44:44 +00002290 std::vector<std::string> &tv)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002291 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +00002292 GeneratedCode(gc), GeneratedDecl(gd),
2293 TargetOpcodes(to), TargetVTs(tv),
Chris Lattner706d2d32006-08-09 16:44:44 +00002294 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00002295
2296 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2297 /// if the match fails. At this point, we already know that the opcode for N
2298 /// matches, and the SDNode for the result has the RootName specified name.
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002299 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2300 const std::string &RootName, const std::string &ChainSuffix,
2301 bool &FoundChain) {
Evan Chenge41bf822006-02-05 06:43:12 +00002302 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00002303 // Emit instruction predicates. Each predicate is just a string for now.
2304 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002305 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00002306 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2307 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2308 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002309 if (!Def->isSubClassOf("Predicate")) {
Jim Laskey16d42c62006-07-11 18:25:13 +00002310#ifndef NDEBUG
2311 Def->dump();
2312#endif
Evan Cheng58e84a62005-12-14 22:02:59 +00002313 assert(0 && "Unknown predicate type!");
2314 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002315 if (!PredicateCheck.empty())
Chris Lattnerbc7fa522006-09-19 00:41:36 +00002316 PredicateCheck += " && ";
Chris Lattner67a202b2006-01-28 20:43:52 +00002317 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00002318 }
2319 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002320
2321 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00002322 }
2323
Evan Chengb915f312005-12-09 22:45:35 +00002324 if (N->isLeaf()) {
2325 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002326 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00002327 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002328 return;
2329 } else if (!NodeIsComplexPattern(N)) {
2330 assert(0 && "Cannot match this as a leaf value!");
2331 abort();
2332 }
2333 }
2334
Chris Lattner488580c2006-01-28 19:06:51 +00002335 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002336 // we already saw this in the pattern, emit code to verify dagness.
2337 if (!N->getName().empty()) {
2338 std::string &VarMapEntry = VariableMap[N->getName()];
2339 if (VarMapEntry.empty()) {
2340 VarMapEntry = RootName;
2341 } else {
2342 // If we get here, this is a second reference to a specific name. Since
2343 // we already have checked that the first reference is valid, we don't
2344 // have to recursively match it, just check that it's the same as the
2345 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002346 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00002347 return;
2348 }
Evan Chengf805c2e2006-01-12 19:35:54 +00002349
2350 if (!N->isLeaf())
2351 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00002352 }
2353
2354
2355 // Emit code to load the child nodes and match their contents recursively.
2356 unsigned OpNo = 0;
Evan Cheng94b30402006-10-11 21:02:01 +00002357 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, ISE);
2358 bool HasChain = PatternHasProperty(N, SDNPHasChain, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00002359 bool EmittedUseCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00002360 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00002361 if (NodeHasChain)
2362 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00002363 if (!isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002364 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002365 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00002366 EmittedUseCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00002367 if (NodeHasChain) {
Evan Chenge41bf822006-02-05 06:43:12 +00002368 // If the immediate use can somehow reach this node through another
2369 // path, then can't fold it either or it will create a cycle.
2370 // e.g. In the following diagram, XX can reach ld through YY. If
2371 // ld is folded into XX, then YY is both a predecessor and a successor
2372 // of XX.
2373 //
2374 // [ld]
2375 // ^ ^
2376 // | |
2377 // / \---
2378 // / [YY]
2379 // | ^
2380 // [XX]-------|
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002381 bool NeedCheck = false;
2382 if (P != Pattern)
2383 NeedCheck = true;
2384 else {
2385 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2386 NeedCheck =
2387 P->getOperator() == ISE.get_intrinsic_void_sdnode() ||
2388 P->getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
2389 P->getOperator() == ISE.get_intrinsic_wo_chain_sdnode() ||
Evan Chengce1381a2006-10-14 08:30:15 +00002390 PInfo.getNumOperands() > 1 ||
Evan Cheng94b30402006-10-11 21:02:01 +00002391 PInfo.hasProperty(SDNPHasChain) ||
2392 PInfo.hasProperty(SDNPInFlag) ||
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002393 PInfo.hasProperty(SDNPOptInFlag);
2394 }
2395
2396 if (NeedCheck) {
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002397 std::string ParentName(RootName.begin(), RootName.end()-1);
Chris Lattner706d2d32006-08-09 16:44:44 +00002398 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
Evan Chengce1381a2006-10-14 08:30:15 +00002399 ".Val, N.Val)");
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002400 }
Evan Chenge41bf822006-02-05 06:43:12 +00002401 }
Evan Chengb915f312005-12-09 22:45:35 +00002402 }
Evan Chenge41bf822006-02-05 06:43:12 +00002403
Evan Chengc15d18c2006-01-27 22:13:45 +00002404 if (NodeHasChain) {
Evan Cheng4326ef52006-10-12 02:08:53 +00002405 if (FoundChain) {
2406 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
2407 "IsChainCompatible(" + ChainName + ".Val, " +
2408 RootName + ".Val))");
2409 OrigChains.push_back(std::make_pair(ChainName, RootName));
2410 } else
Evan Chenge6389932006-07-21 22:19:51 +00002411 FoundChain = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002412 ChainName = "Chain" + ChainSuffix;
Evan Cheng676d7312006-08-26 00:59:04 +00002413 emitInit("SDOperand " + ChainName + " = " + RootName +
Evan Chenge6389932006-07-21 22:19:51 +00002414 ".getOperand(0);");
Evan Cheng1cf6db22006-01-06 00:41:12 +00002415 }
Evan Chengb915f312005-12-09 22:45:35 +00002416 }
2417
Evan Cheng54597732006-01-26 00:22:25 +00002418 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002419 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002420 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002421 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2422 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002423 if (!isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002424 (PatternHasProperty(N, SDNPInFlag, ISE) ||
2425 PatternHasProperty(N, SDNPOptInFlag, ISE) ||
2426 PatternHasProperty(N, SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002427 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002428 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002429 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002430 }
2431 }
2432
Evan Chengd3eea902006-10-09 21:02:17 +00002433 // If there is a node predicate for this, emit the call.
2434 if (!N->getPredicateFn().empty())
2435 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2436
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002437
Chris Lattner39e73f72006-10-11 04:05:55 +00002438 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
2439 // a constant without a predicate fn that has more that one bit set, handle
2440 // this as a special case. This is usually for targets that have special
2441 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
2442 // handling stuff). Using these instructions is often far more efficient
2443 // than materializing the constant. Unfortunately, both the instcombiner
2444 // and the dag combiner can often infer that bits are dead, and thus drop
2445 // them from the mask in the dag. For example, it might turn 'AND X, 255'
2446 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
2447 // to handle this.
2448 if (!N->isLeaf() &&
2449 (N->getOperator()->getName() == "and" ||
2450 N->getOperator()->getName() == "or") &&
2451 N->getChild(1)->isLeaf() &&
2452 N->getChild(1)->getPredicateFn().empty()) {
2453 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
2454 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
2455 emitInit("SDOperand " + RootName + "0" + " = " +
2456 RootName + ".getOperand(" + utostr(0) + ");");
2457 emitInit("SDOperand " + RootName + "1" + " = " +
2458 RootName + ".getOperand(" + utostr(1) + ");");
2459
2460 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
2461 const char *MaskPredicate = N->getOperator()->getName() == "or"
2462 ? "CheckOrMask(" : "CheckAndMask(";
2463 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
2464 RootName + "1), " + itostr(II->getValue()) + ")");
2465
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002466 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
Chris Lattner39e73f72006-10-11 04:05:55 +00002467 ChainSuffix + utostr(0), FoundChain);
2468 return;
2469 }
2470 }
2471 }
2472
Evan Chengb915f312005-12-09 22:45:35 +00002473 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng676d7312006-08-26 00:59:04 +00002474 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002475 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002476
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002477 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002478 ChainSuffix + utostr(OpNo), FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002479 }
2480
Evan Cheng676d7312006-08-26 00:59:04 +00002481 // Handle cases when root is a complex pattern.
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002482 const ComplexPattern *CP;
Evan Cheng676d7312006-08-26 00:59:04 +00002483 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2484 std::string Fn = CP->getSelectFunc();
2485 unsigned NumOps = CP->getNumOperands();
2486 for (unsigned i = 0; i < NumOps; ++i) {
2487 emitDecl("CPTmp" + utostr(i));
2488 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2489 }
Evan Cheng94b30402006-10-11 21:02:01 +00002490 if (CP->hasProperty(SDNPHasChain)) {
2491 emitDecl("CPInChain");
2492 emitDecl("Chain" + ChainSuffix);
2493 emitCode("SDOperand CPInChain;");
2494 emitCode("SDOperand Chain" + ChainSuffix + ";");
2495 }
Evan Cheng676d7312006-08-26 00:59:04 +00002496
Evan Cheng811731e2006-11-08 20:31:10 +00002497 std::string Code = Fn + "(" + RootName + ", " + RootName;
Evan Cheng676d7312006-08-26 00:59:04 +00002498 for (unsigned i = 0; i < NumOps; i++)
2499 Code += ", CPTmp" + utostr(i);
Evan Cheng94b30402006-10-11 21:02:01 +00002500 if (CP->hasProperty(SDNPHasChain)) {
2501 ChainName = "Chain" + ChainSuffix;
2502 Code += ", CPInChain, Chain" + ChainSuffix;
2503 }
Evan Cheng676d7312006-08-26 00:59:04 +00002504 emitCheck(Code + ")");
2505 }
Evan Chengb915f312005-12-09 22:45:35 +00002506 }
Chris Lattner39e73f72006-10-11 04:05:55 +00002507
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002508 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
2509 const std::string &RootName,
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002510 const std::string &ChainSuffix, bool &FoundChain) {
2511 if (!Child->isLeaf()) {
2512 // If it's not a leaf, recursively match.
2513 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2514 emitCheck(RootName + ".getOpcode() == " +
2515 CInfo.getEnumName());
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002516 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
Evan Cheng94b30402006-10-11 21:02:01 +00002517 if (NodeHasProperty(Child, SDNPHasChain, ISE))
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002518 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
2519 } else {
2520 // If this child has a name associated with it, capture it in VarMap. If
2521 // we already saw this in the pattern, emit code to verify dagness.
2522 if (!Child->getName().empty()) {
2523 std::string &VarMapEntry = VariableMap[Child->getName()];
2524 if (VarMapEntry.empty()) {
2525 VarMapEntry = RootName;
2526 } else {
2527 // If we get here, this is a second reference to a specific name.
2528 // Since we already have checked that the first reference is valid,
2529 // we don't have to recursively match it, just check that it's the
2530 // same as the previously named thing.
2531 emitCheck(VarMapEntry + " == " + RootName);
2532 Duplicates.insert(RootName);
2533 return;
2534 }
2535 }
2536
2537 // Handle leaves of various types.
2538 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2539 Record *LeafRec = DI->getDef();
Chris Lattner646085d2006-11-14 21:18:40 +00002540 if (LeafRec->isSubClassOf("RegisterClass") ||
2541 LeafRec->getName() == "ptr_rc") {
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002542 // Handle register references. Nothing to do here.
2543 } else if (LeafRec->isSubClassOf("Register")) {
2544 // Handle register references.
2545 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2546 // Handle complex pattern.
2547 const ComplexPattern *CP = NodeGetComplexPattern(Child, ISE);
2548 std::string Fn = CP->getSelectFunc();
2549 unsigned NumOps = CP->getNumOperands();
2550 for (unsigned i = 0; i < NumOps; ++i) {
2551 emitDecl("CPTmp" + utostr(i));
2552 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2553 }
Evan Cheng94b30402006-10-11 21:02:01 +00002554 if (CP->hasProperty(SDNPHasChain)) {
2555 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(Parent->getOperator());
2556 FoldedChains.push_back(std::make_pair("CPInChain",
2557 PInfo.getNumResults()));
2558 ChainName = "Chain" + ChainSuffix;
2559 emitDecl("CPInChain");
2560 emitDecl(ChainName);
2561 emitCode("SDOperand CPInChain;");
2562 emitCode("SDOperand " + ChainName + ";");
2563 }
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002564
Evan Cheng811731e2006-11-08 20:31:10 +00002565 std::string Code = Fn + "(N, ";
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002566 if (CP->hasProperty(SDNPHasChain)) {
2567 std::string ParentName(RootName.begin(), RootName.end()-1);
Evan Cheng811731e2006-11-08 20:31:10 +00002568 Code += ParentName + ", ";
Evan Cheng13e9e9c2006-10-16 06:33:44 +00002569 }
2570 Code += RootName;
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002571 for (unsigned i = 0; i < NumOps; i++)
2572 Code += ", CPTmp" + utostr(i);
Evan Cheng94b30402006-10-11 21:02:01 +00002573 if (CP->hasProperty(SDNPHasChain))
2574 Code += ", CPInChain, Chain" + ChainSuffix;
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002575 emitCheck(Code + ")");
2576 } else if (LeafRec->getName() == "srcvalue") {
2577 // Place holder for SRCVALUE nodes. Nothing to do here.
2578 } else if (LeafRec->isSubClassOf("ValueType")) {
2579 // Make sure this is the specified value type.
2580 emitCheck("cast<VTSDNode>(" + RootName +
2581 ")->getVT() == MVT::" + LeafRec->getName());
2582 } else if (LeafRec->isSubClassOf("CondCode")) {
2583 // Make sure this is the specified cond code.
2584 emitCheck("cast<CondCodeSDNode>(" + RootName +
2585 ")->get() == ISD::" + LeafRec->getName());
2586 } else {
2587#ifndef NDEBUG
2588 Child->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00002589 cerr << " ";
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002590#endif
2591 assert(0 && "Unknown leaf type!");
2592 }
2593
2594 // If there is a node predicate for this, emit the call.
2595 if (!Child->getPredicateFn().empty())
2596 emitCheck(Child->getPredicateFn() + "(" + RootName +
2597 ".Val)");
2598 } else if (IntInit *II =
2599 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2600 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
2601 unsigned CTmp = TmpNo++;
2602 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2603 RootName + ")->getSignExtended();");
2604
2605 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2606 } else {
2607#ifndef NDEBUG
2608 Child->dump();
2609#endif
2610 assert(0 && "Unknown leaf type!");
2611 }
2612 }
2613 }
Evan Chengb915f312005-12-09 22:45:35 +00002614
2615 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2616 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +00002617 std::vector<std::string>
2618 EmitResultCode(TreePatternNode *N, bool RetSelected,
2619 bool InFlagDecled, bool ResNodeDecled,
2620 bool LikeLeaf = false, bool isRoot = false) {
2621 // List of arguments of getTargetNode() or SelectNodeTo().
2622 std::vector<std::string> NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002623 // This is something selected from the pattern we matched.
2624 if (!N->getName().empty()) {
Evan Chengb915f312005-12-09 22:45:35 +00002625 std::string &Val = VariableMap[N->getName()];
2626 assert(!Val.empty() &&
2627 "Variable referenced but not defined and not caught earlier!");
2628 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2629 // Already selected this operand, just return the tmpval.
Evan Cheng676d7312006-08-26 00:59:04 +00002630 NodeOps.push_back(Val);
2631 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002632 }
2633
2634 const ComplexPattern *CP;
2635 unsigned ResNo = TmpNo++;
Evan Chengb915f312005-12-09 22:45:35 +00002636 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002637 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002638 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002639 switch (N->getTypeNum(0)) {
Chris Lattnerd8a17282007-01-17 07:45:12 +00002640 default:
2641 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
2642 << " type as an immediate constant. Aborting\n";
2643 abort();
Chris Lattner78593132006-01-29 20:01:35 +00002644 case MVT::i1: CastType = "bool"; break;
2645 case MVT::i8: CastType = "unsigned char"; break;
2646 case MVT::i16: CastType = "unsigned short"; break;
2647 case MVT::i32: CastType = "unsigned"; break;
2648 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002649 }
Evan Cheng676d7312006-08-26 00:59:04 +00002650 emitCode("SDOperand Tmp" + utostr(ResNo) +
Evan Chengfceb57a2006-07-15 08:45:20 +00002651 " = CurDAG->getTargetConstant(((" + CastType +
2652 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2653 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002654 NodeOps.push_back("Tmp" + utostr(ResNo));
2655 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2656 // value if used multiple times by this pattern result.
2657 Val = "Tmp"+utostr(ResNo);
Evan Chengbb48e332006-01-12 07:54:57 +00002658 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002659 Record *Op = OperatorMap[N->getName()];
2660 // Transform ExternalSymbol to TargetExternalSymbol
2661 if (Op && Op->getName() == "externalsym") {
Evan Cheng676d7312006-08-26 00:59:04 +00002662 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002663 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002664 Val + ")->getSymbol(), " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002665 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002666 NodeOps.push_back("Tmp" + utostr(ResNo));
Chris Lattner64906972006-09-21 18:28:27 +00002667 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2668 // this value if used multiple times by this pattern result.
Evan Cheng676d7312006-08-26 00:59:04 +00002669 Val = "Tmp"+utostr(ResNo);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002670 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002671 NodeOps.push_back(Val);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002672 }
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00002673 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
2674 || N->getOperator()->getName() == "tglobaltlsaddr")) {
Evan Chengf805c2e2006-01-12 19:35:54 +00002675 Record *Op = OperatorMap[N->getName()];
2676 // Transform GlobalAddress to TargetGlobalAddress
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00002677 if (Op && (Op->getName() == "globaladdr" ||
2678 Op->getName() == "globaltlsaddr")) {
Evan Cheng676d7312006-08-26 00:59:04 +00002679 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002680 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
Evan Cheng2618d072006-05-17 20:37:59 +00002681 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002682 ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002683 NodeOps.push_back("Tmp" + utostr(ResNo));
Chris Lattner64906972006-09-21 18:28:27 +00002684 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2685 // this value if used multiple times by this pattern result.
Evan Cheng676d7312006-08-26 00:59:04 +00002686 Val = "Tmp"+utostr(ResNo);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002687 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002688 NodeOps.push_back(Val);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002689 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002690 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng676d7312006-08-26 00:59:04 +00002691 NodeOps.push_back(Val);
2692 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2693 // value if used multiple times by this pattern result.
2694 Val = "Tmp"+utostr(ResNo);
Evan Chengbb48e332006-01-12 07:54:57 +00002695 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng676d7312006-08-26 00:59:04 +00002696 NodeOps.push_back(Val);
2697 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2698 // value if used multiple times by this pattern result.
2699 Val = "Tmp"+utostr(ResNo);
Evan Chengb915f312005-12-09 22:45:35 +00002700 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
Evan Cheng676d7312006-08-26 00:59:04 +00002701 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
2702 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
2703 NodeOps.push_back("CPTmp" + utostr(i));
Evan Chengb0793f92006-05-25 00:21:44 +00002704 }
Evan Chengb915f312005-12-09 22:45:35 +00002705 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002706 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
Evan Cheng863bf5a2006-03-20 22:53:06 +00002707 // node even if it isn't one. Don't select it.
Evan Cheng676d7312006-08-26 00:59:04 +00002708 if (!LikeLeaf) {
2709 emitCode("AddToISelQueue(" + Val + ");");
Chris Lattner706d2d32006-08-09 16:44:44 +00002710 if (isRoot && N->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +00002711 emitCode("ReplaceUses(N, " + Val + ");");
Evan Cheng06d64702006-08-11 08:59:35 +00002712 emitCode("return NULL;");
Chris Lattner706d2d32006-08-09 16:44:44 +00002713 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00002714 }
Evan Cheng676d7312006-08-26 00:59:04 +00002715 NodeOps.push_back(Val);
Evan Chengb915f312005-12-09 22:45:35 +00002716 }
Evan Cheng676d7312006-08-26 00:59:04 +00002717 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002718 }
Evan Chengb915f312005-12-09 22:45:35 +00002719 if (N->isLeaf()) {
2720 // If this is an explicit register reference, handle it.
2721 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2722 unsigned ResNo = TmpNo++;
2723 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng676d7312006-08-26 00:59:04 +00002724 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002725 ISE.getQualifiedName(DI->getDef()) + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002726 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002727 NodeOps.push_back("Tmp" + utostr(ResNo));
2728 return NodeOps;
Evan Cheng7774be42007-07-05 07:19:45 +00002729 } else if (DI->getDef()->getName() == "zero_reg") {
2730 emitCode("SDOperand Tmp" + utostr(ResNo) +
2731 " = CurDAG->getRegister(0, " +
2732 getEnumName(N->getTypeNum(0)) + ");");
2733 NodeOps.push_back("Tmp" + utostr(ResNo));
2734 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002735 }
2736 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2737 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002738 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng676d7312006-08-26 00:59:04 +00002739 emitCode("SDOperand Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002740 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
Evan Cheng2618d072006-05-17 20:37:59 +00002741 ", " + getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002742 NodeOps.push_back("Tmp" + utostr(ResNo));
2743 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002744 }
2745
Jim Laskey16d42c62006-07-11 18:25:13 +00002746#ifndef NDEBUG
2747 N->dump();
2748#endif
Evan Chengb915f312005-12-09 22:45:35 +00002749 assert(0 && "Unknown leaf type!");
Evan Cheng676d7312006-08-26 00:59:04 +00002750 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002751 }
2752
2753 Record *Op = N->getOperator();
2754 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002755 const CodeGenTarget &CGT = ISE.getTargetInfo();
2756 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002757 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng045953c2006-05-10 00:05:46 +00002758 TreePattern *InstPat = Inst.getPattern();
2759 TreePatternNode *InstPatNode =
2760 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2761 : (InstPat ? InstPat->getOnlyTree() : NULL);
2762 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2763 InstPatNode = InstPatNode->getChild(1);
2764 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002765 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
Evan Cheng045953c2006-05-10 00:05:46 +00002766 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2767 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2768 bool NodeHasOptInFlag = isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002769 PatternHasProperty(Pattern, SDNPOptInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002770 bool NodeHasInFlag = isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002771 PatternHasProperty(Pattern, SDNPInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002772 bool NodeHasOutFlag = HasImpResults || (isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002773 PatternHasProperty(Pattern, SDNPOutFlag, ISE));
Evan Cheng045953c2006-05-10 00:05:46 +00002774 bool NodeHasChain = InstPatNode &&
Evan Cheng94b30402006-10-11 21:02:01 +00002775 PatternHasProperty(InstPatNode, SDNPHasChain, ISE);
Evan Cheng3eff89b2006-05-10 02:47:57 +00002776 bool InputHasChain = isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002777 NodeHasProperty(Pattern, SDNPHasChain, ISE);
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002778 unsigned NumResults = Inst.getNumResults();
Evan Cheng4fba2812005-12-20 07:37:41 +00002779
Evan Chengfceb57a2006-07-15 08:45:20 +00002780 if (NodeHasOptInFlag) {
Evan Cheng676d7312006-08-26 00:59:04 +00002781 emitCode("bool HasInFlag = "
Evan Chengf8729402006-07-16 06:12:52 +00002782 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
Evan Chengfceb57a2006-07-15 08:45:20 +00002783 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002784 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +00002785 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
Evan Cheng4fba2812005-12-20 07:37:41 +00002786
Evan Cheng823b7522006-01-19 21:57:10 +00002787 // How many results is this pattern expected to produce?
Evan Chenged66e852006-03-09 08:19:11 +00002788 unsigned PatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +00002789 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2790 MVT::ValueType VT = Pattern->getTypeNum(i);
2791 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Chenged66e852006-03-09 08:19:11 +00002792 PatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +00002793 }
2794
Evan Cheng4326ef52006-10-12 02:08:53 +00002795 if (OrigChains.size() > 0) {
2796 // The original input chain is being ignored. If it is not just
2797 // pointing to the op that's being folded, we should create a
2798 // TokenFactor with it and the chain of the folded op as the new chain.
2799 // We could potentially be doing multiple levels of folding, in that
2800 // case, the TokenFactor can have more operands.
2801 emitCode("SmallVector<SDOperand, 8> InChains;");
2802 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
2803 emitCode("if (" + OrigChains[i].first + ".Val != " +
2804 OrigChains[i].second + ".Val) {");
2805 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
2806 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
2807 emitCode("}");
2808 }
2809 emitCode("AddToISelQueue(" + ChainName + ");");
2810 emitCode("InChains.push_back(" + ChainName + ");");
2811 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
2812 "&InChains[0], InChains.size());");
2813 }
2814
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002815 // Loop over all of the operands of the instruction pattern, emitting code
2816 // to fill them all in. The node 'N' usually has number children equal to
2817 // the number of input operands of the instruction. However, in cases
2818 // where there are predicate operands for an instruction, we need to fill
2819 // in the 'execute always' values. Match up the node operands to the
2820 // instruction operands to do this.
Evan Cheng676d7312006-08-26 00:59:04 +00002821 std::vector<std::string> AllOps;
Evan Cheng39376d02007-05-15 01:19:51 +00002822 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002823 for (unsigned ChildNo = 0, InstOpNo = NumResults;
2824 InstOpNo != II.OperandList.size(); ++InstOpNo) {
2825 std::vector<std::string> Ops;
2826
Evan Cheng59039632007-05-08 21:04:07 +00002827 // If this is a normal operand or a predicate operand without
2828 // 'execute always', emit it.
2829 Record *OperandNode = II.OperandList[InstOpNo].Rec;
Evan Chenga9559392007-07-06 01:05:26 +00002830 if ((!OperandNode->isSubClassOf("PredicateOperand") &&
2831 !OperandNode->isSubClassOf("OptionalDefOperand")) ||
2832 ISE.getDefaultOperand(OperandNode).DefaultOps.empty()) {
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002833 Ops = EmitResultCode(N->getChild(ChildNo), RetSelected,
2834 InFlagDecled, ResNodeDecled);
2835 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
2836 ++ChildNo;
2837 } else {
Evan Chenga9559392007-07-06 01:05:26 +00002838 // Otherwise, this is a predicate or optional def operand, emit the
2839 // 'default ops' operands.
2840 const DAGDefaultOperand &DefaultOp =
2841 ISE.getDefaultOperand(II.OperandList[InstOpNo].Rec);
2842 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
2843 Ops = EmitResultCode(DefaultOp.DefaultOps[i], RetSelected,
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002844 InFlagDecled, ResNodeDecled);
2845 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
Evan Cheng39376d02007-05-15 01:19:51 +00002846 NumEAInputs += Ops.size();
Chris Lattnerefe9f4a2006-11-04 05:12:02 +00002847 }
2848 }
Evan Chengb915f312005-12-09 22:45:35 +00002849 }
2850
Evan Chengb915f312005-12-09 22:45:35 +00002851 // Emit all the chain and CopyToReg stuff.
Evan Cheng045953c2006-05-10 00:05:46 +00002852 bool ChainEmitted = NodeHasChain;
2853 if (NodeHasChain)
Evan Cheng676d7312006-08-26 00:59:04 +00002854 emitCode("AddToISelQueue(" + ChainName + ");");
Evan Chengbc6b86a2006-06-14 19:27:50 +00002855 if (NodeHasInFlag || HasImpInputs)
Evan Cheng676d7312006-08-26 00:59:04 +00002856 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
2857 InFlagDecled, ResNodeDecled, true);
Evan Chengf037ca62006-08-27 08:11:28 +00002858 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
Evan Cheng676d7312006-08-26 00:59:04 +00002859 if (!InFlagDecled) {
2860 emitCode("SDOperand InFlag(0, 0);");
2861 InFlagDecled = true;
2862 }
Evan Chengf037ca62006-08-27 08:11:28 +00002863 if (NodeHasOptInFlag) {
2864 emitCode("if (HasInFlag) {");
2865 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
2866 emitCode(" AddToISelQueue(InFlag);");
2867 emitCode("}");
2868 }
Evan Chengbc6b86a2006-06-14 19:27:50 +00002869 }
Evan Chengb915f312005-12-09 22:45:35 +00002870
Evan Chengb915f312005-12-09 22:45:35 +00002871 unsigned ResNo = TmpNo++;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002872 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2873 NodeHasOptInFlag) {
Evan Chenge945f4d2006-06-14 22:22:20 +00002874 std::string Code;
2875 std::string Code2;
2876 std::string NodeName;
2877 if (!isRoot) {
2878 NodeName = "Tmp" + utostr(ResNo);
Evan Cheng676d7312006-08-26 00:59:04 +00002879 Code2 = "SDOperand " + NodeName + " = SDOperand(";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002880 } else {
Evan Chenge945f4d2006-06-14 22:22:20 +00002881 NodeName = "ResNode";
Lauro Ramos Venancio195c6c22007-04-26 17:03:22 +00002882 if (!ResNodeDecled) {
Evan Cheng676d7312006-08-26 00:59:04 +00002883 Code2 = "SDNode *" + NodeName + " = ";
Lauro Ramos Venancio195c6c22007-04-26 17:03:22 +00002884 ResNodeDecled = true;
2885 } else
Evan Cheng676d7312006-08-26 00:59:04 +00002886 Code2 = NodeName + " = ";
Evan Chengbcecf332005-12-17 01:19:28 +00002887 }
Evan Chengf037ca62006-08-27 08:11:28 +00002888
Evan Chengfceb57a2006-07-15 08:45:20 +00002889 Code = "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
Evan Chengf037ca62006-08-27 08:11:28 +00002890 unsigned OpsNo = OpcNo;
Evan Chengfceb57a2006-07-15 08:45:20 +00002891 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
Evan Chenge945f4d2006-06-14 22:22:20 +00002892
2893 // Output order: results, chain, flags
2894 // Result types.
Evan Chengf8729402006-07-16 06:12:52 +00002895 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
2896 Code += ", VT" + utostr(VTNo);
2897 emitVT(getEnumName(N->getTypeNum(0)));
2898 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002899 if (NodeHasChain)
2900 Code += ", MVT::Other";
2901 if (NodeHasOutFlag)
2902 Code += ", MVT::Flag";
2903
Chris Lattner7c3a96b2006-11-14 18:41:38 +00002904 // Figure out how many fixed inputs the node has. This is important to
2905 // know which inputs are the variable ones if present.
2906 unsigned NumInputs = AllOps.size();
2907 NumInputs += NodeHasChain;
2908
Evan Chenge945f4d2006-06-14 22:22:20 +00002909 // Inputs.
Evan Chengf037ca62006-08-27 08:11:28 +00002910 if (HasVarOps) {
2911 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
2912 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
2913 AllOps.clear();
Evan Chenge945f4d2006-06-14 22:22:20 +00002914 }
2915
2916 if (HasVarOps) {
Chris Lattner7c3a96b2006-11-14 18:41:38 +00002917 // Figure out whether any operands at the end of the op list are not
2918 // part of the variable section.
2919 std::string EndAdjust;
Evan Chenge945f4d2006-06-14 22:22:20 +00002920 if (NodeHasInFlag || HasImpInputs)
Chris Lattner7c3a96b2006-11-14 18:41:38 +00002921 EndAdjust = "-1"; // Always has one flag.
2922 else if (NodeHasOptInFlag)
2923 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
2924
Evan Cheng39376d02007-05-15 01:19:51 +00002925 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
Chris Lattner7c3a96b2006-11-14 18:41:38 +00002926 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
2927
Evan Cheng676d7312006-08-26 00:59:04 +00002928 emitCode(" AddToISelQueue(N.getOperand(i));");
Evan Chengf037ca62006-08-27 08:11:28 +00002929 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
Evan Chenge945f4d2006-06-14 22:22:20 +00002930 emitCode("}");
2931 }
2932
2933 if (NodeHasChain) {
2934 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +00002935 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
Evan Chenge945f4d2006-06-14 22:22:20 +00002936 else
Evan Chengf037ca62006-08-27 08:11:28 +00002937 AllOps.push_back(ChainName);
Evan Chenge945f4d2006-06-14 22:22:20 +00002938 }
2939
Evan Chengf037ca62006-08-27 08:11:28 +00002940 if (HasVarOps) {
2941 if (NodeHasInFlag || HasImpInputs)
2942 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2943 else if (NodeHasOptInFlag) {
2944 emitCode("if (HasInFlag)");
2945 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2946 }
2947 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
2948 ".size()";
2949 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2950 AllOps.push_back("InFlag");
Evan Chenge945f4d2006-06-14 22:22:20 +00002951
Evan Chengf037ca62006-08-27 08:11:28 +00002952 unsigned NumOps = AllOps.size();
2953 if (NumOps) {
2954 if (!NodeHasOptInFlag && NumOps < 4) {
2955 for (unsigned i = 0; i != NumOps; ++i)
2956 Code += ", " + AllOps[i];
2957 } else {
2958 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
2959 for (unsigned i = 0; i != NumOps; ++i) {
2960 OpsCode += AllOps[i];
2961 if (i != NumOps-1)
2962 OpsCode += ", ";
2963 }
2964 emitCode(OpsCode + " };");
2965 Code += ", Ops" + utostr(OpsNo) + ", ";
2966 if (NodeHasOptInFlag) {
2967 Code += "HasInFlag ? ";
2968 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
2969 } else
2970 Code += utostr(NumOps);
2971 }
2972 }
2973
Evan Chenge945f4d2006-06-14 22:22:20 +00002974 if (!isRoot)
2975 Code += "), 0";
2976 emitCode(Code2 + Code + ");");
2977
2978 if (NodeHasChain)
2979 // Remember which op produces the chain.
2980 if (!isRoot)
2981 emitCode(ChainName + " = SDOperand(" + NodeName +
2982 ".Val, " + utostr(PatResults) + ");");
2983 else
2984 emitCode(ChainName + " = SDOperand(" + NodeName +
2985 ", " + utostr(PatResults) + ");");
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002986
Evan Cheng676d7312006-08-26 00:59:04 +00002987 if (!isRoot) {
2988 NodeOps.push_back("Tmp" + utostr(ResNo));
2989 return NodeOps;
2990 }
Evan Cheng045953c2006-05-10 00:05:46 +00002991
Evan Cheng06d64702006-08-11 08:59:35 +00002992 bool NeedReplace = false;
Evan Cheng676d7312006-08-26 00:59:04 +00002993 if (NodeHasOutFlag) {
2994 if (!InFlagDecled) {
2995 emitCode("SDOperand InFlag = SDOperand(ResNode, " +
2996 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2997 InFlagDecled = true;
2998 } else
2999 emitCode("InFlag = SDOperand(ResNode, " +
3000 utostr(NumResults + (unsigned)NodeHasChain) + ");");
3001 }
Evan Cheng4fba2812005-12-20 07:37:41 +00003002
Evan Cheng676d7312006-08-26 00:59:04 +00003003 if (HasImpResults && EmitCopyFromRegs(N, ResNodeDecled, ChainEmitted)) {
Chris Lattner706d2d32006-08-09 16:44:44 +00003004 emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));");
Evan Chenged66e852006-03-09 08:19:11 +00003005 NumResults = 1;
Evan Cheng97938882005-12-22 02:24:50 +00003006 }
Evan Cheng4fba2812005-12-20 07:37:41 +00003007
Evan Cheng97938882005-12-22 02:24:50 +00003008 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00003009 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00003010 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Chris Lattner706d2d32006-08-09 16:44:44 +00003011 emitCode("ReplaceUses(SDOperand(" +
Evan Cheng67212a02006-02-09 22:12:27 +00003012 FoldedChains[j].first + ".Val, " +
Chris Lattner706d2d32006-08-09 16:44:44 +00003013 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
3014 utostr(NumResults) + "));");
Evan Cheng06d64702006-08-11 08:59:35 +00003015 NeedReplace = true;
Evan Chengb915f312005-12-09 22:45:35 +00003016 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00003017
Evan Cheng06d64702006-08-11 08:59:35 +00003018 if (NodeHasOutFlag) {
Chris Lattner706d2d32006-08-09 16:44:44 +00003019 emitCode("ReplaceUses(SDOperand(N.Val, " +
3020 utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);");
Evan Cheng06d64702006-08-11 08:59:35 +00003021 NeedReplace = true;
3022 }
3023
3024 if (NeedReplace) {
3025 for (unsigned i = 0; i < NumResults; i++)
3026 emitCode("ReplaceUses(SDOperand(N.Val, " +
3027 utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));");
3028 if (InputHasChain)
3029 emitCode("ReplaceUses(SDOperand(N.Val, " +
Chris Lattner64906972006-09-21 18:28:27 +00003030 utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, "
3031 + ChainName + ".ResNo" + "));");
Evan Chengf037ca62006-08-27 08:11:28 +00003032 } else
Evan Cheng06d64702006-08-11 08:59:35 +00003033 RetSelected = true;
Evan Cheng97938882005-12-22 02:24:50 +00003034
Evan Chenged66e852006-03-09 08:19:11 +00003035 // User does not expect the instruction would produce a chain!
Evan Cheng06d64702006-08-11 08:59:35 +00003036 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
Evan Cheng9ade2182006-08-26 05:34:46 +00003037 ;
Evan Cheng3eff89b2006-05-10 02:47:57 +00003038 } else if (InputHasChain && !NodeHasChain) {
3039 // One of the inner node produces a chain.
Evan Cheng9ade2182006-08-26 05:34:46 +00003040 if (NodeHasOutFlag)
Evan Cheng06d64702006-08-11 08:59:35 +00003041 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults+1) +
3042 "), SDOperand(ResNode, N.ResNo-1));");
Evan Cheng06d64702006-08-11 08:59:35 +00003043 for (unsigned i = 0; i < PatResults; ++i)
3044 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(i) +
3045 "), SDOperand(ResNode, " + utostr(i) + "));");
3046 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults) +
3047 "), " + ChainName + ");");
3048 RetSelected = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00003049 }
Evan Cheng06d64702006-08-11 08:59:35 +00003050
3051 if (RetSelected)
Evan Cheng9ade2182006-08-26 05:34:46 +00003052 emitCode("return ResNode;");
Evan Cheng06d64702006-08-11 08:59:35 +00003053 else
3054 emitCode("return NULL;");
Evan Chengb915f312005-12-09 22:45:35 +00003055 } else {
Evan Cheng9ade2182006-08-26 05:34:46 +00003056 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
Evan Chengfceb57a2006-07-15 08:45:20 +00003057 utostr(OpcNo);
Nate Begemanb73628b2005-12-30 00:12:56 +00003058 if (N->getTypeNum(0) != MVT::isVoid)
Evan Chengf8729402006-07-16 06:12:52 +00003059 Code += ", VT" + utostr(VTNo);
Evan Cheng54597732006-01-26 00:22:25 +00003060 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00003061 Code += ", MVT::Flag";
Evan Chengf037ca62006-08-27 08:11:28 +00003062
3063 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
3064 AllOps.push_back("InFlag");
3065
3066 unsigned NumOps = AllOps.size();
3067 if (NumOps) {
3068 if (!NodeHasOptInFlag && NumOps < 4) {
3069 for (unsigned i = 0; i != NumOps; ++i)
3070 Code += ", " + AllOps[i];
3071 } else {
3072 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
3073 for (unsigned i = 0; i != NumOps; ++i) {
3074 OpsCode += AllOps[i];
3075 if (i != NumOps-1)
3076 OpsCode += ", ";
3077 }
3078 emitCode(OpsCode + " };");
3079 Code += ", Ops" + utostr(OpcNo) + ", ";
3080 Code += utostr(NumOps);
3081 }
3082 }
Evan Cheng95514ba2006-08-26 08:00:10 +00003083 emitCode(Code + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00003084 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
3085 if (N->getTypeNum(0) != MVT::isVoid)
3086 emitVT(getEnumName(N->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00003087 }
Evan Cheng4fba2812005-12-20 07:37:41 +00003088
Evan Cheng676d7312006-08-26 00:59:04 +00003089 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00003090 } else if (Op->isSubClassOf("SDNodeXForm")) {
3091 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng863bf5a2006-03-20 22:53:06 +00003092 // PatLeaf node - the operand may or may not be a leaf node. But it should
3093 // behave like one.
Evan Cheng676d7312006-08-26 00:59:04 +00003094 std::vector<std::string> Ops =
3095 EmitResultCode(N->getChild(0), RetSelected, InFlagDecled,
3096 ResNodeDecled, true);
Evan Chengb915f312005-12-09 22:45:35 +00003097 unsigned ResNo = TmpNo++;
Evan Cheng676d7312006-08-26 00:59:04 +00003098 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
3099 + "(" + Ops.back() + ".Val);");
3100 NodeOps.push_back("Tmp" + utostr(ResNo));
Evan Cheng9ade2182006-08-26 05:34:46 +00003101 if (isRoot)
3102 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00003103 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00003104 } else {
3105 N->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00003106 cerr << "\n";
Chris Lattner7893f132006-01-11 01:33:49 +00003107 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00003108 }
3109 }
3110
Chris Lattner488580c2006-01-28 19:06:51 +00003111 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
3112 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00003113 /// 'Pat' may be missing types. If we find an unresolved type to add a check
3114 /// for, this returns true otherwise false if Pat has all types.
3115 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +00003116 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00003117 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +00003118 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +00003119 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00003120 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +00003121 // The top level node type is checked outside of the select function.
3122 if (!isRoot)
3123 emitCheck(Prefix + ".Val->getValueType(0) == " +
3124 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00003125 return true;
Evan Chengb915f312005-12-09 22:45:35 +00003126 }
3127
Evan Cheng51fecc82006-01-09 18:27:06 +00003128 unsigned OpNo =
Evan Cheng94b30402006-10-11 21:02:01 +00003129 (unsigned) NodeHasProperty(Pat, SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00003130 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
3131 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
3132 Prefix + utostr(OpNo)))
3133 return true;
3134 return false;
3135 }
3136
3137private:
Evan Cheng54597732006-01-26 00:22:25 +00003138 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00003139 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00003140 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +00003141 bool &ChainEmitted, bool &InFlagDecled,
3142 bool &ResNodeDecled, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00003143 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00003144 unsigned OpNo =
Evan Cheng94b30402006-10-11 21:02:01 +00003145 (unsigned) NodeHasProperty(N, SDNPHasChain, ISE);
3146 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00003147 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
3148 TreePatternNode *Child = N->getChild(i);
3149 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +00003150 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
3151 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +00003152 } else {
3153 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00003154 if (!Child->getName().empty()) {
3155 std::string Name = RootName + utostr(OpNo);
3156 if (Duplicates.find(Name) != Duplicates.end())
3157 // A duplicate! Do not emit a copy for this node.
3158 continue;
3159 }
3160
Evan Chengb915f312005-12-09 22:45:35 +00003161 Record *RR = DI->getDef();
3162 if (RR->isSubClassOf("Register")) {
3163 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00003164 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +00003165 if (!InFlagDecled) {
3166 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
3167 InFlagDecled = true;
3168 } else
3169 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
3170 emitCode("AddToISelQueue(InFlag);");
Evan Chengb2c6d492006-01-11 22:16:13 +00003171 } else {
3172 if (!ChainEmitted) {
Evan Cheng676d7312006-08-26 00:59:04 +00003173 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00003174 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00003175 ChainEmitted = true;
3176 }
Evan Cheng676d7312006-08-26 00:59:04 +00003177 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
3178 if (!InFlagDecled) {
3179 emitCode("SDOperand InFlag(0, 0);");
3180 InFlagDecled = true;
3181 }
3182 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
3183 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Cheng7a33db02006-08-26 07:39:28 +00003184 ", " + ISE.getQualifiedName(RR) +
3185 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00003186 ResNodeDecled = true;
Evan Cheng67212a02006-02-09 22:12:27 +00003187 emitCode(ChainName + " = SDOperand(ResNode, 0);");
3188 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00003189 }
3190 }
3191 }
3192 }
3193 }
Evan Cheng54597732006-01-26 00:22:25 +00003194
Evan Cheng676d7312006-08-26 00:59:04 +00003195 if (HasInFlag) {
3196 if (!InFlagDecled) {
3197 emitCode("SDOperand InFlag = " + RootName +
3198 ".getOperand(" + utostr(OpNo) + ");");
3199 InFlagDecled = true;
3200 } else
3201 emitCode("InFlag = " + RootName +
3202 ".getOperand(" + utostr(OpNo) + ");");
3203 emitCode("AddToISelQueue(InFlag);");
3204 }
Evan Chengb915f312005-12-09 22:45:35 +00003205 }
Evan Cheng4fba2812005-12-20 07:37:41 +00003206
3207 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00003208 /// as specified by the instruction. It returns true if any copy is
3209 /// emitted.
Evan Cheng676d7312006-08-26 00:59:04 +00003210 bool EmitCopyFromRegs(TreePatternNode *N, bool &ResNodeDecled,
3211 bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00003212 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00003213 Record *Op = N->getOperator();
3214 if (Op->isSubClassOf("Instruction")) {
3215 const DAGInstruction &Inst = ISE.getInstruction(Op);
3216 const CodeGenTarget &CGT = ISE.getTargetInfo();
Evan Cheng4fba2812005-12-20 07:37:41 +00003217 unsigned NumImpResults = Inst.getNumImpResults();
3218 for (unsigned i = 0; i < NumImpResults; i++) {
3219 Record *RR = Inst.getImpResult(i);
3220 if (RR->isSubClassOf("Register")) {
3221 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
3222 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00003223 if (!ChainEmitted) {
Evan Cheng676d7312006-08-26 00:59:04 +00003224 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00003225 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00003226 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00003227 }
Evan Cheng676d7312006-08-26 00:59:04 +00003228 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
3229 emitCode(Decl + "ResNode = CurDAG->getCopyFromReg(" + ChainName +
Evan Chengfceb57a2006-07-15 08:45:20 +00003230 ", " + ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
Evan Chengd7805a72006-02-09 07:16:09 +00003231 ", InFlag).Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00003232 ResNodeDecled = true;
Evan Chengd7805a72006-02-09 07:16:09 +00003233 emitCode(ChainName + " = SDOperand(ResNode, 1);");
3234 emitCode("InFlag = SDOperand(ResNode, 2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00003235 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00003236 }
3237 }
3238 }
3239 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00003240 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00003241 }
Evan Chengb915f312005-12-09 22:45:35 +00003242};
3243
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00003244/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
3245/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00003246/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00003247void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00003248 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00003249 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00003250 std::vector<std::string> &TargetOpcodes,
Evan Chengf5493192006-08-26 01:02:19 +00003251 std::vector<std::string> &TargetVTs) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003252 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
3253 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00003254 GeneratedCode, GeneratedDecl,
Chris Lattner706d2d32006-08-09 16:44:44 +00003255 TargetOpcodes, TargetVTs);
Evan Chengb915f312005-12-09 22:45:35 +00003256
Chris Lattner8fc35682005-09-23 23:16:51 +00003257 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00003258 bool FoundChain = false;
Evan Cheng13e9e9c2006-10-16 06:33:44 +00003259 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00003260
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003261 // TP - Get *SOME* tree pattern, we don't care which.
3262 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00003263
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003264 // At this point, we know that we structurally match the pattern, but the
3265 // types of the nodes may not match. Figure out the fewest number of type
3266 // comparisons we need to emit. For example, if there is only one integer
3267 // type supported by a target, there should be no type comparisons at all for
3268 // integer patterns!
3269 //
3270 // To figure out the fewest number of type checks needed, clone the pattern,
3271 // remove the types, then perform type inference on the pattern as a whole.
3272 // If there are unresolved types, emit an explicit check for those types,
3273 // apply the type to the tree, then rerun type inference. Iterate until all
3274 // types are resolved.
3275 //
Evan Cheng58e84a62005-12-14 22:02:59 +00003276 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003277 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00003278
3279 do {
3280 // Resolve/propagate as many types as possible.
3281 try {
3282 bool MadeChange = true;
3283 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00003284 MadeChange = Pat->ApplyTypeConstraints(TP,
3285 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00003286 } catch (...) {
3287 assert(0 && "Error: could not find consistent types for something we"
3288 " already decided was ok!");
3289 abort();
3290 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003291
Chris Lattner7e82f132005-10-15 21:34:21 +00003292 // Insert a check for an unresolved type and add it to the tree. If we find
3293 // an unresolved type to add a check for, this returns true and we iterate,
3294 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00003295 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00003296
Evan Cheng676d7312006-08-26 00:59:04 +00003297 Emitter.EmitResultCode(Pattern.getDstPattern(),
3298 false, false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003299 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00003300}
3301
Chris Lattner24e00a42006-01-29 04:41:05 +00003302/// EraseCodeLine - Erase one code line from all of the patterns. If removing
3303/// a line causes any of them to be empty, remove them and return true when
3304/// done.
3305static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00003306 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00003307 &Patterns) {
3308 bool ErasedPatterns = false;
3309 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3310 Patterns[i].second.pop_back();
3311 if (Patterns[i].second.empty()) {
3312 Patterns.erase(Patterns.begin()+i);
3313 --i; --e;
3314 ErasedPatterns = true;
3315 }
3316 }
3317 return ErasedPatterns;
3318}
3319
Chris Lattner8bc74722006-01-29 04:25:26 +00003320/// EmitPatterns - Emit code for at least one pattern, but try to group common
3321/// code together between the patterns.
3322void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00003323 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00003324 &Patterns, unsigned Indent,
3325 std::ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00003326 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00003327 typedef std::vector<CodeLine> CodeList;
3328 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3329
3330 if (Patterns.empty()) return;
3331
Chris Lattner24e00a42006-01-29 04:41:05 +00003332 // Figure out how many patterns share the next code line. Explicitly copy
3333 // FirstCodeLine so that we don't invalidate a reference when changing
3334 // Patterns.
3335 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00003336 unsigned LastMatch = Patterns.size()-1;
3337 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3338 --LastMatch;
3339
3340 // If not all patterns share this line, split the list into two pieces. The
3341 // first chunk will use this line, the second chunk won't.
3342 if (LastMatch != 0) {
3343 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3344 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3345
3346 // FIXME: Emit braces?
3347 if (Shared.size() == 1) {
3348 PatternToMatch &Pattern = *Shared.back().first;
3349 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3350 Pattern.getSrcPattern()->print(OS);
3351 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3352 Pattern.getDstPattern()->print(OS);
3353 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003354 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003355 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003356 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003357 << " cost = "
Evan Chenge6f32032006-07-19 00:24:41 +00003358 << getResultPatternCost(Pattern.getDstPattern(), *this)
3359 << " size = "
3360 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003361 }
Evan Cheng676d7312006-08-26 00:59:04 +00003362 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00003363 OS << std::string(Indent, ' ') << "{\n";
3364 Indent += 2;
3365 }
3366 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00003367 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00003368 Indent -= 2;
3369 OS << std::string(Indent, ' ') << "}\n";
3370 }
3371
3372 if (Other.size() == 1) {
3373 PatternToMatch &Pattern = *Other.back().first;
3374 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3375 Pattern.getSrcPattern()->print(OS);
3376 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3377 Pattern.getDstPattern()->print(OS);
3378 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003379 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003380 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003381 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003382 << " cost = "
Chris Lattner706d2d32006-08-09 16:44:44 +00003383 << getResultPatternCost(Pattern.getDstPattern(), *this)
3384 << " size = "
3385 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003386 }
3387 EmitPatterns(Other, Indent, OS);
3388 return;
3389 }
3390
Chris Lattner24e00a42006-01-29 04:41:05 +00003391 // Remove this code from all of the patterns that share it.
3392 bool ErasedPatterns = EraseCodeLine(Patterns);
3393
Evan Cheng676d7312006-08-26 00:59:04 +00003394 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00003395
3396 // Otherwise, every pattern in the list has this line. Emit it.
3397 if (!isPredicate) {
3398 // Normal code.
3399 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3400 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00003401 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3402
3403 // If the next code line is another predicate, and if all of the pattern
3404 // in this group share the same next line, emit it inline now. Do this
3405 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00003406 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Chris Lattner24e00a42006-01-29 04:41:05 +00003407 // Check that all of fhe patterns in Patterns end with the same predicate.
3408 bool AllEndWithSamePredicate = true;
3409 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3410 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3411 AllEndWithSamePredicate = false;
3412 break;
3413 }
3414 // If all of the predicates aren't the same, we can't share them.
3415 if (!AllEndWithSamePredicate) break;
3416
3417 // Otherwise we can. Emit it shared now.
3418 OS << " &&\n" << std::string(Indent+4, ' ')
3419 << Patterns.back().second.back().second;
3420 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00003421 }
Chris Lattner24e00a42006-01-29 04:41:05 +00003422
3423 OS << ") {\n";
3424 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00003425 }
3426
3427 EmitPatterns(Patterns, Indent, OS);
3428
3429 if (isPredicate)
3430 OS << std::string(Indent-2, ' ') << "}\n";
3431}
3432
Evan Cheng892aaf82006-11-08 23:01:03 +00003433static std::string getOpcodeName(Record *Op, DAGISelEmitter &ISE) {
3434 const SDNodeInfo &OpcodeInfo = ISE.getSDNodeInfo(Op);
3435 return OpcodeInfo.getEnumName();
3436}
Chris Lattner8bc74722006-01-29 04:25:26 +00003437
Evan Cheng892aaf82006-11-08 23:01:03 +00003438static std::string getLegalCName(std::string OpName) {
3439 std::string::size_type pos = OpName.find("::");
3440 if (pos != std::string::npos)
3441 OpName.replace(pos, 2, "_");
3442 return OpName;
Chris Lattner37481472005-09-26 21:59:35 +00003443}
3444
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003445void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerf7560ed2006-11-20 18:54:33 +00003446 // Get the namespace to insert instructions into. Make sure not to pick up
3447 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
3448 // instruction or something.
3449 std::string InstNS;
3450 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
3451 e = Target.inst_end(); i != e; ++i) {
3452 InstNS = i->second.Namespace;
3453 if (InstNS != "TargetInstrInfo")
3454 break;
3455 }
3456
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003457 if (!InstNS.empty()) InstNS += "::";
3458
Chris Lattner602f6922006-01-04 00:25:00 +00003459 // Group the patterns by their top-level opcodes.
Evan Cheng892aaf82006-11-08 23:01:03 +00003460 std::map<std::string, std::vector<PatternToMatch*> > PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00003461 // All unique target node emission functions.
3462 std::map<std::string, unsigned> EmitFunctions;
Chris Lattner602f6922006-01-04 00:25:00 +00003463 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3464 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3465 if (!Node->isLeaf()) {
Evan Cheng892aaf82006-11-08 23:01:03 +00003466 PatternsByOpcode[getOpcodeName(Node->getOperator(), *this)].
3467 push_back(&PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003468 } else {
3469 const ComplexPattern *CP;
Chris Lattner9c5d4de2006-11-03 01:11:05 +00003470 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Evan Cheng892aaf82006-11-08 23:01:03 +00003471 PatternsByOpcode[getOpcodeName(getSDNodeNamed("imm"), *this)].
3472 push_back(&PatternsToMatch[i]);
Reid Spencer63fd6ad2006-11-02 21:07:40 +00003473 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
Chris Lattner602f6922006-01-04 00:25:00 +00003474 std::vector<Record*> OpNodes = CP->getRootNodes();
3475 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Evan Cheng892aaf82006-11-08 23:01:03 +00003476 PatternsByOpcode[getOpcodeName(OpNodes[j], *this)]
3477 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], *this)].begin(),
3478 &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003479 }
3480 } else {
Bill Wendlingf5da1332006-12-07 22:21:48 +00003481 cerr << "Unrecognized opcode '";
Chris Lattner602f6922006-01-04 00:25:00 +00003482 Node->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00003483 cerr << "' on tree pattern '";
3484 cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3485 cerr << "'!\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003486 exit(1);
3487 }
3488 }
3489 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003490
3491 // For each opcode, there might be multiple select functions, one per
3492 // ValueType of the node (or its first operand if it doesn't produce a
3493 // non-chain result.
3494 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
3495
Chris Lattner602f6922006-01-04 00:25:00 +00003496 // Emit one Select_* method for each top-level opcode. We do this instead of
3497 // emitting one giant switch statement to support compilers where this will
3498 // result in the recursive functions taking less stack space.
Evan Cheng892aaf82006-11-08 23:01:03 +00003499 for (std::map<std::string, std::vector<PatternToMatch*> >::iterator
3500 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
3501 PBOI != E; ++PBOI) {
3502 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00003503 std::vector<PatternToMatch*> &PatternsOfOp = PBOI->second;
3504 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
3505
Chris Lattner602f6922006-01-04 00:25:00 +00003506 // We want to emit all of the matching code now. However, we want to emit
3507 // the matches in order of minimal cost. Sort the patterns so the least
3508 // cost one is at the start.
Chris Lattner706d2d32006-08-09 16:44:44 +00003509 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
Chris Lattner602f6922006-01-04 00:25:00 +00003510 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00003511
Chris Lattner706d2d32006-08-09 16:44:44 +00003512 // Split them into groups by type.
3513 std::map<MVT::ValueType, std::vector<PatternToMatch*> > PatternsByType;
3514 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
3515 PatternToMatch *Pat = PatternsOfOp[i];
3516 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner706d2d32006-08-09 16:44:44 +00003517 MVT::ValueType VT = SrcPat->getTypeNum(0);
3518 std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator TI =
3519 PatternsByType.find(VT);
3520 if (TI != PatternsByType.end())
3521 TI->second.push_back(Pat);
3522 else {
3523 std::vector<PatternToMatch*> PVec;
3524 PVec.push_back(Pat);
3525 PatternsByType.insert(std::make_pair(VT, PVec));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003526 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003527 }
3528
3529 for (std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator
3530 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
3531 ++II) {
3532 MVT::ValueType OpVT = II->first;
3533 std::vector<PatternToMatch*> &Patterns = II->second;
Chris Lattner64906972006-09-21 18:28:27 +00003534 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
3535 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00003536
3537 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3538 std::vector<std::vector<std::string> > PatternOpcodes;
3539 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00003540 std::vector<std::set<std::string> > PatternDecls;
Chris Lattner706d2d32006-08-09 16:44:44 +00003541 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3542 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00003543 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00003544 std::vector<std::string> TargetOpcodes;
3545 std::vector<std::string> TargetVTs;
3546 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3547 TargetOpcodes, TargetVTs);
Chris Lattner706d2d32006-08-09 16:44:44 +00003548 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3549 PatternDecls.push_back(GeneratedDecl);
3550 PatternOpcodes.push_back(TargetOpcodes);
3551 PatternVTs.push_back(TargetVTs);
3552 }
3553
3554 // Scan the code to see if all of the patterns are reachable and if it is
3555 // possible that the last one might not match.
3556 bool mightNotMatch = true;
3557 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3558 CodeList &GeneratedCode = CodeForPatterns[i].second;
3559 mightNotMatch = false;
3560
3561 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
Evan Cheng676d7312006-08-26 00:59:04 +00003562 if (GeneratedCode[j].first == 1) { // predicate.
Chris Lattner706d2d32006-08-09 16:44:44 +00003563 mightNotMatch = true;
3564 break;
3565 }
3566 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003567
Chris Lattner706d2d32006-08-09 16:44:44 +00003568 // If this pattern definitely matches, and if it isn't the last one, the
3569 // patterns after it CANNOT ever match. Error out.
3570 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00003571 cerr << "Pattern '";
3572 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
3573 cerr << "' is impossible to select!\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003574 exit(1);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003575 }
3576 }
3577
Chris Lattner706d2d32006-08-09 16:44:44 +00003578 // Factor target node emission code (emitted by EmitResultCode) into
3579 // separate functions. Uniquing and share them among all instruction
3580 // selection routines.
3581 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3582 CodeList &GeneratedCode = CodeForPatterns[i].second;
3583 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
3584 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00003585 std::set<std::string> Decls = PatternDecls[i];
Evan Cheng676d7312006-08-26 00:59:04 +00003586 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00003587 int CodeSize = (int)GeneratedCode.size();
3588 int LastPred = -1;
3589 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00003590 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00003591 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00003592 else if (LastPred != -1 && GeneratedCode[j].first == 2)
3593 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00003594 }
3595
Evan Cheng9ade2182006-08-26 05:34:46 +00003596 std::string CalleeCode = "(const SDOperand &N";
3597 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00003598 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3599 CalleeCode += ", unsigned Opc" + utostr(j);
3600 CallerCode += ", " + TargetOpcodes[j];
3601 }
3602 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
3603 CalleeCode += ", MVT::ValueType VT" + utostr(j);
3604 CallerCode += ", " + TargetVTs[j];
3605 }
Evan Chengf5493192006-08-26 01:02:19 +00003606 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00003607 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00003608 std::string Name = *I;
Evan Cheng676d7312006-08-26 00:59:04 +00003609 CalleeCode += ", SDOperand &" + Name;
3610 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00003611 }
3612 CallerCode += ");";
3613 CalleeCode += ") ";
3614 // Prevent emission routines from being inlined to reduce selection
3615 // routines stack frame sizes.
Chris Lattner8dc728e2006-08-27 13:16:24 +00003616 CalleeCode += "DISABLE_INLINE ";
Evan Cheng676d7312006-08-26 00:59:04 +00003617 CalleeCode += "{\n";
3618
3619 for (std::vector<std::string>::const_reverse_iterator
3620 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
3621 CalleeCode += " " + *I + "\n";
3622
Evan Chengf5493192006-08-26 01:02:19 +00003623 for (int j = LastPred+1; j < CodeSize; ++j)
3624 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003625 for (int j = LastPred+1; j < CodeSize; ++j)
3626 GeneratedCode.pop_back();
3627 CalleeCode += "}\n";
3628
3629 // Uniquing the emission routines.
3630 unsigned EmitFuncNum;
3631 std::map<std::string, unsigned>::iterator EFI =
3632 EmitFunctions.find(CalleeCode);
3633 if (EFI != EmitFunctions.end()) {
3634 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003635 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00003636 EmitFuncNum = EmitFunctions.size();
3637 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Evan Cheng06d64702006-08-11 08:59:35 +00003638 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003639 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003640
Chris Lattner706d2d32006-08-09 16:44:44 +00003641 // Replace the emission code within selection routines with calls to the
3642 // emission functions.
Evan Cheng06d64702006-08-11 08:59:35 +00003643 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
Chris Lattner706d2d32006-08-09 16:44:44 +00003644 GeneratedCode.push_back(std::make_pair(false, CallerCode));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003645 }
3646
Chris Lattner706d2d32006-08-09 16:44:44 +00003647 // Print function.
Chris Lattnerab51ddd2006-11-14 21:32:01 +00003648 std::string OpVTStr;
Chris Lattner33a40042006-11-14 22:17:10 +00003649 if (OpVT == MVT::iPTR) {
3650 OpVTStr = "_iPTR";
3651 } else if (OpVT == MVT::isVoid) {
3652 // Nodes with a void result actually have a first result type of either
3653 // Other (a chain) or Flag. Since there is no one-to-one mapping from
3654 // void to this case, we handle it specially here.
3655 } else {
3656 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
3657 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003658 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3659 OpcodeVTMap.find(OpName);
3660 if (OpVTI == OpcodeVTMap.end()) {
3661 std::vector<std::string> VTSet;
3662 VTSet.push_back(OpVTStr);
3663 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
3664 } else
3665 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003666
Evan Cheng892aaf82006-11-08 23:01:03 +00003667 OS << "SDNode *Select_" << getLegalCName(OpName)
Chris Lattner33a40042006-11-14 22:17:10 +00003668 << OpVTStr << "(const SDOperand &N) {\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003669
Chris Lattner706d2d32006-08-09 16:44:44 +00003670 // Loop through and reverse all of the CodeList vectors, as we will be
3671 // accessing them from their logical front, but accessing the end of a
3672 // vector is more efficient.
3673 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3674 CodeList &GeneratedCode = CodeForPatterns[i].second;
3675 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003676 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003677
3678 // Next, reverse the list of patterns itself for the same reason.
3679 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3680
3681 // Emit all of the patterns now, grouped together to share code.
3682 EmitPatterns(CodeForPatterns, 2, OS);
3683
Chris Lattner64906972006-09-21 18:28:27 +00003684 // If the last pattern has predicates (which could fail) emit code to
3685 // catch the case where nothing handles a pattern.
Chris Lattner706d2d32006-08-09 16:44:44 +00003686 if (mightNotMatch) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00003687 OS << " cerr << \"Cannot yet select: \";\n";
Evan Cheng892aaf82006-11-08 23:01:03 +00003688 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
3689 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
3690 OpName != "ISD::INTRINSIC_VOID") {
Chris Lattner706d2d32006-08-09 16:44:44 +00003691 OS << " N.Val->dump(CurDAG);\n";
3692 } else {
3693 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3694 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00003695 << " cerr << \"intrinsic %\"<< "
Chris Lattner706d2d32006-08-09 16:44:44 +00003696 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3697 }
Bill Wendlingf5da1332006-12-07 22:21:48 +00003698 OS << " cerr << '\\n';\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003699 << " abort();\n"
3700 << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003701 }
3702 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003703 }
Chris Lattner602f6922006-01-04 00:25:00 +00003704 }
3705
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003706 // Emit boilerplate.
Evan Cheng9ade2182006-08-26 05:34:46 +00003707 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003708 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Chris Lattner4ef9b112007-05-15 01:36:44 +00003709 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
3710
3711 << " // Ensure that the asm operands are themselves selected.\n"
3712 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
3713 << " AddToISelQueue(Ops[j]);\n\n"
3714
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003715 << " std::vector<MVT::ValueType> VTs;\n"
3716 << " VTs.push_back(MVT::Other);\n"
3717 << " VTs.push_back(MVT::Flag);\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00003718 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
3719 "Ops.size());\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00003720 << " return New.Val;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003721 << "}\n\n";
3722
Jim Laskeya683f9b2007-01-26 17:29:20 +00003723 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
3724 << " SDOperand Chain = N.getOperand(0);\n"
3725 << " SDOperand N1 = N.getOperand(1);\n"
Jim Laskey844b8922007-01-26 23:00:54 +00003726 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
3727 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00003728 << " AddToISelQueue(Chain);\n"
3729 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
Jim Laskey844b8922007-01-26 23:00:54 +00003730 << " MVT::Other, Tmp, Chain);\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00003731 << "}\n\n";
3732
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003733 OS << "// The main instruction selector code.\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00003734 << "SDNode *SelectCode(SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003735 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003736 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003737 << "INSTRUCTION_LIST_END)) {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003738 << " return NULL; // Already selected.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003739 << " }\n\n"
Evan Cheng892aaf82006-11-08 23:01:03 +00003740 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003741 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003742 << " default: break;\n"
3743 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003744 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003745 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003746 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003747 << " case ISD::TargetConstant:\n"
3748 << " case ISD::TargetConstantPool:\n"
3749 << " case ISD::TargetFrameIndex:\n"
Chris Lattner4ef9b112007-05-15 01:36:44 +00003750 << " case ISD::TargetExternalSymbol:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00003751 << " case ISD::TargetJumpTable:\n"
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00003752 << " case ISD::TargetGlobalTLSAddress:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003753 << " case ISD::TargetGlobalAddress: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003754 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003755 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003756 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003757 << " case ISD::AssertZext: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003758 << " AddToISelQueue(N.getOperand(0));\n"
3759 << " ReplaceUses(N, N.getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003760 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003761 << " }\n"
3762 << " case ISD::TokenFactor:\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00003763 << " case ISD::CopyFromReg:\n"
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003764 << " case ISD::CopyToReg: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003765 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
3766 << " AddToISelQueue(N.getOperand(i));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003767 << " return NULL;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003768 << " }\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00003769 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
3770 << " case ISD::LABEL: return Select_LABEL(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003771
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003772
Chris Lattner602f6922006-01-04 00:25:00 +00003773 // Loop over all of the case statements, emiting a call to each method we
3774 // emitted above.
Evan Cheng892aaf82006-11-08 23:01:03 +00003775 for (std::map<std::string, std::vector<PatternToMatch*> >::iterator
3776 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
3777 PBOI != E; ++PBOI) {
3778 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00003779 // Potentially multiple versions of select for this opcode. One for each
3780 // ValueType of the node (or its first true operand if it doesn't produce a
3781 // result.
3782 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3783 OpcodeVTMap.find(OpName);
3784 std::vector<std::string> &OpVTs = OpVTI->second;
Evan Cheng892aaf82006-11-08 23:01:03 +00003785 OS << " case " << OpName << ": {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003786 if (OpVTs.size() == 1) {
3787 std::string &VTStr = OpVTs[0];
Evan Cheng892aaf82006-11-08 23:01:03 +00003788 OS << " return Select_" << getLegalCName(OpName)
Chris Lattner33a40042006-11-14 22:17:10 +00003789 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003790 } else {
Chris Lattner717a6112006-11-14 21:50:27 +00003791 // Keep track of whether we see a pattern that has an iPtr result.
3792 bool HasPtrPattern = false;
Chris Lattner33a40042006-11-14 22:17:10 +00003793 bool HasDefaultPattern = false;
Chris Lattner717a6112006-11-14 21:50:27 +00003794
Evan Cheng06d64702006-08-11 08:59:35 +00003795 OS << " switch (NVT) {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003796 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
3797 std::string &VTStr = OpVTs[i];
Chris Lattner33a40042006-11-14 22:17:10 +00003798 if (VTStr.empty()) {
3799 HasDefaultPattern = true;
3800 continue;
3801 }
Chris Lattner717a6112006-11-14 21:50:27 +00003802
3803 // If this is a match on iPTR: don't emit it directly, we need special
3804 // code.
Chris Lattner33a40042006-11-14 22:17:10 +00003805 if (VTStr == "_iPTR") {
Chris Lattner717a6112006-11-14 21:50:27 +00003806 HasPtrPattern = true;
3807 continue;
3808 }
Chris Lattner33a40042006-11-14 22:17:10 +00003809 OS << " case MVT::" << VTStr.substr(1) << ":\n"
Evan Cheng892aaf82006-11-08 23:01:03 +00003810 << " return Select_" << getLegalCName(OpName)
Chris Lattner33a40042006-11-14 22:17:10 +00003811 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003812 }
Evan Cheng06d64702006-08-11 08:59:35 +00003813 OS << " default:\n";
Chris Lattner717a6112006-11-14 21:50:27 +00003814
3815 // If there is an iPTR result version of this pattern, emit it here.
3816 if (HasPtrPattern) {
3817 OS << " if (NVT == TLI.getPointerTy())\n";
3818 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
3819 }
Chris Lattner33a40042006-11-14 22:17:10 +00003820 if (HasDefaultPattern) {
3821 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
3822 }
Chris Lattner0d1bb132006-11-14 21:41:35 +00003823 OS << " break;\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003824 OS << " }\n";
3825 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003826 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003827 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00003828 }
Chris Lattner81303322005-09-23 19:36:15 +00003829
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003830 OS << " } // end of big switch.\n\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00003831 << " cerr << \"Cannot yet select: \";\n"
Chris Lattnerb026e702006-03-28 00:41:33 +00003832 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3833 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3834 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003835 << " N.Val->dump(CurDAG);\n"
3836 << " } else {\n"
3837 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3838 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00003839 << " cerr << \"intrinsic %\"<< "
3840 "Intrinsic::getName((Intrinsic::ID)iid);\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003841 << " }\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00003842 << " cerr << '\\n';\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003843 << " abort();\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003844 << " return NULL;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003845 << "}\n";
3846}
3847
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003848void DAGISelEmitter::run(std::ostream &OS) {
3849 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3850 " target", OS);
3851
Chris Lattner1f39e292005-09-14 00:09:24 +00003852 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3853 << "// *** instruction selector class. These functions are really "
3854 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003855
Chris Lattner8dc728e2006-08-27 13:16:24 +00003856 OS << "#include \"llvm/Support/Compiler.h\"\n";
Evan Cheng233baf12006-07-26 23:06:27 +00003857
Chris Lattner706d2d32006-08-09 16:44:44 +00003858 OS << "// Instruction selector priority queue:\n"
3859 << "std::vector<SDNode*> ISelQueue;\n";
3860 OS << "/// Keep track of nodes which have already been added to queue.\n"
3861 << "unsigned char *ISelQueued;\n";
3862 OS << "/// Keep track of nodes which have already been selected.\n"
3863 << "unsigned char *ISelSelected;\n";
3864 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
3865 << "std::vector<SDNode*> ISelKilled;\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003866
Evan Cheng4326ef52006-10-12 02:08:53 +00003867 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
3868 OS << "/// not reach Op.\n";
3869 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
3870 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
3871 OS << " return true;\n";
3872 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
3873 OS << " return false;\n";
3874 OS << " else if (Chain->getNumOperands() > 0) {\n";
3875 OS << " SDOperand C0 = Chain->getOperand(0);\n";
3876 OS << " if (C0.getValueType() == MVT::Other)\n";
3877 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
3878 OS << " }\n";
3879 OS << " return true;\n";
3880 OS << "}\n";
3881
Chris Lattner706d2d32006-08-09 16:44:44 +00003882 OS << "/// Sorting functions for the selection queue.\n"
3883 << "struct isel_sort : public std::binary_function"
3884 << "<SDNode*, SDNode*, bool> {\n"
3885 << " bool operator()(const SDNode* left, const SDNode* right) "
3886 << "const {\n"
3887 << " return (left->getNodeId() > right->getNodeId());\n"
3888 << " }\n"
3889 << "};\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003890
Chris Lattner706d2d32006-08-09 16:44:44 +00003891 OS << "inline void setQueued(int Id) {\n";
3892 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003893 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003894 OS << "inline bool isQueued(int Id) {\n";
3895 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003896 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003897 OS << "inline void setSelected(int Id) {\n";
3898 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003899 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003900 OS << "inline bool isSelected(int Id) {\n";
3901 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
3902 OS << "}\n\n";
Evan Cheng9bdca032006-08-07 22:17:58 +00003903
Chris Lattner8dc728e2006-08-27 13:16:24 +00003904 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003905 OS << " int Id = N.Val->getNodeId();\n";
3906 OS << " if (Id != -1 && !isQueued(Id)) {\n";
3907 OS << " ISelQueue.push_back(N.Val);\n";
3908 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3909 OS << " setQueued(Id);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003910 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003911 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003912
Chris Lattner706d2d32006-08-09 16:44:44 +00003913 OS << "inline void RemoveKilled() {\n";
3914OS << " unsigned NumKilled = ISelKilled.size();\n";
3915 OS << " if (NumKilled) {\n";
3916 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
3917 OS << " SDNode *Temp = ISelKilled[i];\n";
Evan Cheng4f776162006-10-12 23:18:52 +00003918 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
3919 << "Temp), ISelQueue.end());\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003920 OS << " };\n";
3921 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3922 OS << " ISelKilled.clear();\n";
3923 OS << " }\n";
3924 OS << "}\n\n";
3925
Chris Lattner8dc728e2006-08-27 13:16:24 +00003926 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003927 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n";
3928 OS << " setSelected(F.Val->getNodeId());\n";
3929 OS << " RemoveKilled();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003930 OS << "}\n";
3931 OS << "inline void ReplaceUses(SDNode *F, SDNode *T) {\n";
3932 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
3933 OS << " setSelected(F->getNodeId());\n";
3934 OS << " RemoveKilled();\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003935 OS << "}\n\n";
3936
Evan Chenge41bf822006-02-05 06:43:12 +00003937 OS << "// SelectRoot - Top level entry to DAG isel.\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003938 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
3939 OS << " SelectRootInit();\n";
3940 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
3941 OS << " ISelQueued = new unsigned char[NumBytes];\n";
3942 OS << " ISelSelected = new unsigned char[NumBytes];\n";
3943 OS << " memset(ISelQueued, 0, NumBytes);\n";
3944 OS << " memset(ISelSelected, 0, NumBytes);\n";
3945 OS << "\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00003946 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
3947 << " // a reference to the root node, preventing it from being deleted,\n"
3948 << " // and tracking any changes of the root.\n"
3949 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
3950 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003951 OS << " while (!ISelQueue.empty()) {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003952 OS << " SDNode *Node = ISelQueue.front();\n";
3953 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3954 OS << " ISelQueue.pop_back();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003955 OS << " if (!isSelected(Node->getNodeId())) {\n";
Evan Cheng9ade2182006-08-26 05:34:46 +00003956 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
Evan Cheng966fd372006-09-11 02:24:43 +00003957 OS << " if (ResNode != Node) {\n";
3958 OS << " if (ResNode)\n";
3959 OS << " ReplaceUses(Node, ResNode);\n";
Evan Cheng1fae00f2006-10-12 20:35:19 +00003960 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
3961 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
3962 OS << " RemoveKilled();\n";
3963 OS << " }\n";
Evan Cheng966fd372006-09-11 02:24:43 +00003964 OS << " }\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003965 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003966 OS << " }\n";
3967 OS << "\n";
3968 OS << " delete[] ISelQueued;\n";
3969 OS << " ISelQueued = NULL;\n";
3970 OS << " delete[] ISelSelected;\n";
3971 OS << " ISelSelected = NULL;\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00003972 OS << " return Dummy.getValue();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003973 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003974
Chris Lattner550525e2006-03-24 21:48:51 +00003975 Intrinsics = LoadIntrinsics(Records);
Chris Lattnerca559d02005-09-08 21:03:01 +00003976 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003977 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003978 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003979 ParsePatternFragments(OS);
Evan Chenga9559392007-07-06 01:05:26 +00003980 ParseDefaultOperands();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003981 ParseInstructions();
3982 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003983
Chris Lattnere97603f2005-09-28 19:27:25 +00003984 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003985 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003986 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003987
Bill Wendlingf5da1332006-12-07 22:21:48 +00003988 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
3989 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3990 DOUT << "PATTERN: "; DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
3991 DOUT << "\nRESULT: "; DEBUG(PatternsToMatch[i].getDstPattern()->dump());
3992 DOUT << "\n";
3993 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00003994
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003995 // At this point, we have full information about the 'Patterns' we need to
3996 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003997 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003998 EmitInstructionSelector(OS);
3999
4000 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
4001 E = PatternFragments.end(); I != E; ++I)
4002 delete I->second;
4003 PatternFragments.clear();
4004
Chris Lattner54cb8fd2005-09-07 23:44:43 +00004005 Instructions.clear();
4006}