blob: 4b8ea20e27282a9a7af787e2758d48d487f5459b [file] [log] [blame]
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Support/Debug.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000018#include <algorithm>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000019#include <set>
20using namespace llvm;
21
Chris Lattnerca559d02005-09-08 21:03:01 +000022//===----------------------------------------------------------------------===//
Chris Lattner3c7e18d2005-10-14 06:12:03 +000023// Helpers for working with extended types.
24
25/// FilterVTs - Filter a list of VT's according to a predicate.
26///
27template<typename T>
28static std::vector<MVT::ValueType>
29FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
32 if (Filter(InVTs[i]))
33 Result.push_back(InVTs[i]);
34 return Result;
35}
36
Nate Begemanb73628b2005-12-30 00:12:56 +000037template<typename T>
38static std::vector<unsigned char>
39FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40 std::vector<unsigned char> Result;
41 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42 if (Filter((MVT::ValueType)InVTs[i]))
43 Result.push_back(InVTs[i]);
44 return Result;
Chris Lattner3c7e18d2005-10-14 06:12:03 +000045}
46
Nate Begemanb73628b2005-12-30 00:12:56 +000047static std::vector<unsigned char>
48ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49 std::vector<unsigned char> Result;
50 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51 Result.push_back(InVTs[i]);
52 return Result;
53}
54
55static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56 const std::vector<unsigned char> &RHS) {
57 if (LHS.size() > RHS.size()) return false;
58 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
Duraid Madinad47ae092005-12-30 16:41:48 +000059 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
Nate Begemanb73628b2005-12-30 00:12:56 +000060 return false;
61 return true;
62}
63
64/// isExtIntegerVT - Return true if the specified extended value type vector
65/// contains isInt or an integer value type.
Chris Lattner697f8842006-03-20 05:39:48 +000066static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000067 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
69}
70
71/// isExtFloatingPointVT - Return true if the specified extended value type
72/// vector contains isFP or a FP value type.
Chris Lattner697f8842006-03-20 05:39:48 +000073static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000074 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
Chris Lattner488580c2006-01-28 19:06:51 +000075 return EVTs[0] == MVT::isFP ||
76 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
Chris Lattner3c7e18d2005-10-14 06:12:03 +000077}
78
79//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000080// SDTypeConstraint implementation
81//
82
83SDTypeConstraint::SDTypeConstraint(Record *R) {
84 OperandNo = R->getValueAsInt("OperandNum");
85
86 if (R->isSubClassOf("SDTCisVT")) {
87 ConstraintType = SDTCisVT;
88 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattner5b21be72005-12-09 22:57:42 +000089 } else if (R->isSubClassOf("SDTCisPtrTy")) {
90 ConstraintType = SDTCisPtrTy;
Chris Lattner33c92e92005-09-08 21:27:15 +000091 } else if (R->isSubClassOf("SDTCisInt")) {
92 ConstraintType = SDTCisInt;
93 } else if (R->isSubClassOf("SDTCisFP")) {
94 ConstraintType = SDTCisFP;
95 } else if (R->isSubClassOf("SDTCisSameAs")) {
96 ConstraintType = SDTCisSameAs;
97 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
98 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
99 ConstraintType = SDTCisVTSmallerThanOp;
100 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
101 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +0000102 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
103 ConstraintType = SDTCisOpSmallerThanOp;
104 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
105 R->getValueAsInt("BigOperandNum");
Chris Lattner697f8842006-03-20 05:39:48 +0000106 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
107 ConstraintType = SDTCisIntVectorOfSameSize;
108 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
109 R->getValueAsInt("OtherOpNum");
Chris Lattner33c92e92005-09-08 21:27:15 +0000110 } else {
111 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
112 exit(1);
113 }
114}
115
Chris Lattner32707602005-09-08 23:22:48 +0000116/// getOperandNum - Return the node corresponding to operand #OpNo in tree
117/// N, which has NumResults results.
118TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
119 TreePatternNode *N,
120 unsigned NumResults) const {
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000121 assert(NumResults <= 1 &&
122 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000123
124 if (OpNo < NumResults)
125 return N; // FIXME: need value #
126 else
127 return N->getChild(OpNo-NumResults);
128}
129
130/// ApplyTypeConstraint - Given a node in a pattern, apply this type
131/// constraint to the nodes operands. This returns true if it makes a
132/// change, false otherwise. If a type contradiction is found, throw an
133/// exception.
134bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
135 const SDNodeInfo &NodeInfo,
136 TreePattern &TP) const {
137 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000138 assert(NumResults <= 1 &&
139 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000140
141 // Check that the number of operands is sane.
142 if (NodeInfo.getNumOperands() >= 0) {
143 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
144 TP.error(N->getOperator()->getName() + " node requires exactly " +
145 itostr(NodeInfo.getNumOperands()) + " operands!");
146 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000147
148 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000149
150 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
151
152 switch (ConstraintType) {
153 default: assert(0 && "Unknown constraint type!");
154 case SDTCisVT:
155 // Operand must be a particular type.
156 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000157 case SDTCisPtrTy: {
158 // Operand must be same as target pointer type.
159 return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
160 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000161 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000162 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000163 std::vector<MVT::ValueType> IntVTs =
164 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000165
166 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000167 if (IntVTs.size() == 1)
168 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000169 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000170 }
171 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000172 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000173 std::vector<MVT::ValueType> FPVTs =
174 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000175
176 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000177 if (FPVTs.size() == 1)
178 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000179 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000180 }
Chris Lattner32707602005-09-08 23:22:48 +0000181 case SDTCisSameAs: {
182 TreePatternNode *OtherNode =
183 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Nate Begemanb73628b2005-12-30 00:12:56 +0000184 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
185 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000186 }
187 case SDTCisVTSmallerThanOp: {
188 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
189 // have an integer type that is smaller than the VT.
190 if (!NodeToApply->isLeaf() ||
191 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
192 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
193 ->isSubClassOf("ValueType"))
194 TP.error(N->getOperator()->getName() + " expects a VT operand!");
195 MVT::ValueType VT =
196 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
197 if (!MVT::isInteger(VT))
198 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
199
200 TreePatternNode *OtherNode =
201 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000202
203 // It must be integer.
204 bool MadeChange = false;
205 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
206
Nate Begemanb73628b2005-12-30 00:12:56 +0000207 // This code only handles nodes that have one type set. Assert here so
208 // that we can change this if we ever need to deal with multiple value
209 // types at this point.
210 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
211 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000212 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
213 return false;
214 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000215 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000216 TreePatternNode *BigOperand =
217 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
218
219 // Both operands must be integer or FP, but we don't care which.
220 bool MadeChange = false;
221
Nate Begemanb73628b2005-12-30 00:12:56 +0000222 // This code does not currently handle nodes which have multiple types,
223 // where some types are integer, and some are fp. Assert that this is not
224 // the case.
225 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
226 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
227 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
228 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
229 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
230 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000231 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000232 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000233 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000234 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000235 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000236 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000237 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
238
239 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
240
Nate Begemanb73628b2005-12-30 00:12:56 +0000241 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000242 VTs = FilterVTs(VTs, MVT::isInteger);
Nate Begemanb73628b2005-12-30 00:12:56 +0000243 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000244 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
245 } else {
246 VTs.clear();
247 }
248
249 switch (VTs.size()) {
250 default: // Too many VT's to pick from.
251 case 0: break; // No info yet.
252 case 1:
253 // Only one VT of this flavor. Cannot ever satisify the constraints.
254 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
255 case 2:
256 // If we have exactly two possible types, the little operand must be the
257 // small one, the big operand should be the big one. Common with
258 // float/double for example.
259 assert(VTs[0] < VTs[1] && "Should be sorted!");
260 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
261 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
262 break;
263 }
264 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000265 }
Chris Lattner697f8842006-03-20 05:39:48 +0000266 case SDTCisIntVectorOfSameSize: {
267 TreePatternNode *OtherOperand =
268 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
269 N, NumResults);
270 if (OtherOperand->hasTypeSet()) {
271 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
272 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
273 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
274 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
275 return NodeToApply->UpdateNodeType(IVT, TP);
276 }
277 return false;
278 }
Chris Lattner32707602005-09-08 23:22:48 +0000279 }
280 return false;
281}
282
283
Chris Lattner33c92e92005-09-08 21:27:15 +0000284//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000285// SDNodeInfo implementation
286//
287SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
288 EnumName = R->getValueAsString("Opcode");
289 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000290 Record *TypeProfile = R->getValueAsDef("TypeProfile");
291 NumResults = TypeProfile->getValueAsInt("NumResults");
292 NumOperands = TypeProfile->getValueAsInt("NumOperands");
293
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000294 // Parse the properties.
295 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000296 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000297 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
298 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000299 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000300 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000301 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000302 } else if (PropList[i]->getName() == "SDNPHasChain") {
303 Properties |= 1 << SDNPHasChain;
Evan Cheng51fecc82006-01-09 18:27:06 +0000304 } else if (PropList[i]->getName() == "SDNPOutFlag") {
305 Properties |= 1 << SDNPOutFlag;
306 } else if (PropList[i]->getName() == "SDNPInFlag") {
307 Properties |= 1 << SDNPInFlag;
308 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
309 Properties |= 1 << SDNPOptInFlag;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000310 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000311 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000312 << "' on node '" << R->getName() << "'!\n";
313 exit(1);
314 }
315 }
316
317
Chris Lattner33c92e92005-09-08 21:27:15 +0000318 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000319 std::vector<Record*> ConstraintList =
320 TypeProfile->getValueAsListOfDefs("Constraints");
321 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000322}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000323
324//===----------------------------------------------------------------------===//
325// TreePatternNode implementation
326//
327
328TreePatternNode::~TreePatternNode() {
329#if 0 // FIXME: implement refcounted tree nodes!
330 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
331 delete getChild(i);
332#endif
333}
334
Chris Lattner32707602005-09-08 23:22:48 +0000335/// UpdateNodeType - Set the node type of N to VT if VT contains
336/// information. If N already contains a conflicting type, then throw an
337/// exception. This returns true if any information was updated.
338///
Nate Begemanb73628b2005-12-30 00:12:56 +0000339bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
340 TreePattern &TP) {
341 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
342
343 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
344 return false;
345 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
346 setTypes(ExtVTs);
Chris Lattner32707602005-09-08 23:22:48 +0000347 return true;
348 }
349
Nate Begemanb73628b2005-12-30 00:12:56 +0000350 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
351 assert(hasTypeSet() && "should be handled above!");
352 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
353 if (getExtTypes() == FVTs)
354 return false;
355 setTypes(FVTs);
356 return true;
357 }
358 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
359 assert(hasTypeSet() && "should be handled above!");
Chris Lattner488580c2006-01-28 19:06:51 +0000360 std::vector<unsigned char> FVTs =
361 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
Nate Begemanb73628b2005-12-30 00:12:56 +0000362 if (getExtTypes() == FVTs)
363 return false;
364 setTypes(FVTs);
365 return true;
366 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000367
368 // If we know this is an int or fp type, and we are told it is a specific one,
369 // take the advice.
Nate Begemanb73628b2005-12-30 00:12:56 +0000370 //
371 // Similarly, we should probably set the type here to the intersection of
372 // {isInt|isFP} and ExtVTs
373 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
374 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
375 setTypes(ExtVTs);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000376 return true;
377 }
378
Chris Lattner1531f202005-10-26 16:59:37 +0000379 if (isLeaf()) {
380 dump();
Evan Chengbcecf332005-12-17 01:19:28 +0000381 std::cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000382 TP.error("Type inference contradiction found in node!");
383 } else {
384 TP.error("Type inference contradiction found in node " +
385 getOperator()->getName() + "!");
386 }
Chris Lattner32707602005-09-08 23:22:48 +0000387 return true; // unreachable
388}
389
390
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000391void TreePatternNode::print(std::ostream &OS) const {
392 if (isLeaf()) {
393 OS << *getLeafValue();
394 } else {
395 OS << "(" << getOperator()->getName();
396 }
397
Nate Begemanb73628b2005-12-30 00:12:56 +0000398 // FIXME: At some point we should handle printing all the value types for
399 // nodes that are multiply typed.
400 switch (getExtTypeNum(0)) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000401 case MVT::Other: OS << ":Other"; break;
402 case MVT::isInt: OS << ":isInt"; break;
403 case MVT::isFP : OS << ":isFP"; break;
404 case MVT::isUnknown: ; /*OS << ":?";*/ break;
Nate Begemanb73628b2005-12-30 00:12:56 +0000405 default: OS << ":" << getTypeNum(0); break;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000406 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000407
408 if (!isLeaf()) {
409 if (getNumChildren() != 0) {
410 OS << " ";
411 getChild(0)->print(OS);
412 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
413 OS << ", ";
414 getChild(i)->print(OS);
415 }
416 }
417 OS << ")";
418 }
419
420 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000421 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000422 if (TransformFn)
423 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000424 if (!getName().empty())
425 OS << ":$" << getName();
426
427}
428void TreePatternNode::dump() const {
429 print(std::cerr);
430}
431
Chris Lattnere46e17b2005-09-29 19:28:10 +0000432/// isIsomorphicTo - Return true if this node is recursively isomorphic to
433/// the specified node. For this comparison, all of the state of the node
434/// is considered, except for the assigned name. Nodes with differing names
435/// that are otherwise identical are considered isomorphic.
436bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
437 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000438 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000439 getPredicateFn() != N->getPredicateFn() ||
440 getTransformFn() != N->getTransformFn())
441 return false;
442
443 if (isLeaf()) {
444 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
445 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
446 return DI->getDef() == NDI->getDef();
447 return getLeafValue() == N->getLeafValue();
448 }
449
450 if (N->getOperator() != getOperator() ||
451 N->getNumChildren() != getNumChildren()) return false;
452 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
453 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
454 return false;
455 return true;
456}
457
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000458/// clone - Make a copy of this tree and all of its children.
459///
460TreePatternNode *TreePatternNode::clone() const {
461 TreePatternNode *New;
462 if (isLeaf()) {
463 New = new TreePatternNode(getLeafValue());
464 } else {
465 std::vector<TreePatternNode*> CChildren;
466 CChildren.reserve(Children.size());
467 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
468 CChildren.push_back(getChild(i)->clone());
469 New = new TreePatternNode(getOperator(), CChildren);
470 }
471 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000472 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000473 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000474 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000475 return New;
476}
477
Chris Lattner32707602005-09-08 23:22:48 +0000478/// SubstituteFormalArguments - Replace the formal arguments in this tree
479/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000480void TreePatternNode::
481SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
482 if (isLeaf()) return;
483
484 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
485 TreePatternNode *Child = getChild(i);
486 if (Child->isLeaf()) {
487 Init *Val = Child->getLeafValue();
488 if (dynamic_cast<DefInit*>(Val) &&
489 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
490 // We found a use of a formal argument, replace it with its value.
491 Child = ArgMap[Child->getName()];
492 assert(Child && "Couldn't find formal argument!");
493 setChild(i, Child);
494 }
495 } else {
496 getChild(i)->SubstituteFormalArguments(ArgMap);
497 }
498 }
499}
500
501
502/// InlinePatternFragments - If this pattern refers to any pattern
503/// fragments, inline them into place, giving us a pattern without any
504/// PatFrag references.
505TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
506 if (isLeaf()) return this; // nothing to do.
507 Record *Op = getOperator();
508
509 if (!Op->isSubClassOf("PatFrag")) {
510 // Just recursively inline children nodes.
511 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
512 setChild(i, getChild(i)->InlinePatternFragments(TP));
513 return this;
514 }
515
516 // Otherwise, we found a reference to a fragment. First, look up its
517 // TreePattern record.
518 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
519
520 // Verify that we are passing the right number of operands.
521 if (Frag->getNumArgs() != Children.size())
522 TP.error("'" + Op->getName() + "' fragment requires " +
523 utostr(Frag->getNumArgs()) + " operands!");
524
Chris Lattner37937092005-09-09 01:15:01 +0000525 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000526
527 // Resolve formal arguments to their actual value.
528 if (Frag->getNumArgs()) {
529 // Compute the map of formal to actual arguments.
530 std::map<std::string, TreePatternNode*> ArgMap;
531 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
532 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
533
534 FragTree->SubstituteFormalArguments(ArgMap);
535 }
536
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000537 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000538 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000539
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000540 // Get a new copy of this fragment to stitch into here.
541 //delete this; // FIXME: implement refcounting!
542 return FragTree;
543}
544
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000545/// getIntrinsicType - Check to see if the specified record has an intrinsic
546/// type which should be applied to it. This infer the type of register
547/// references from the register file information, for example.
548///
Nate Begemanb73628b2005-12-30 00:12:56 +0000549static std::vector<unsigned char> getIntrinsicType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000550 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000551 // Some common return values
552 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
553 std::vector<unsigned char> Other(1, MVT::Other);
554
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000555 // Check to see if this is a register or a register class...
556 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000557 if (NotRegisters)
558 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000559 const CodeGenRegisterClass &RC =
560 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000561 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000562 } else if (R->isSubClassOf("PatFrag")) {
563 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000564 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000565 } else if (R->isSubClassOf("Register")) {
Evan Cheng37e90052006-01-15 10:04:45 +0000566 if (NotRegisters)
567 return Unknown;
Chris Lattner22faeab2005-12-05 02:36:37 +0000568 // If the register appears in exactly one regclass, and the regclass has one
569 // value type, use it as the known type.
570 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
571 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
Nate Begemanb73628b2005-12-30 00:12:56 +0000572 return ConvertVTs(RC->getValueTypes());
573 return Unknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000574 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
575 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000576 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000577 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng57c517d2006-01-17 07:36:41 +0000578 if (NotRegisters)
579 return Unknown;
Nate Begemanb73628b2005-12-30 00:12:56 +0000580 std::vector<unsigned char>
581 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
582 return ComplexPat;
Evan Cheng01f318b2005-12-14 02:21:57 +0000583 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000584 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000585 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000586 }
587
588 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000589 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000590}
591
Chris Lattner32707602005-09-08 23:22:48 +0000592/// ApplyTypeConstraints - Apply all of the type constraints relevent to
593/// this node and its children in the tree. This returns true if it makes a
594/// change, false otherwise. If a type contradiction is found, throw an
595/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000596bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
597 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000598 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000599 // If it's a regclass or something else known, include the type.
600 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
601 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000602 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
603 // Int inits are always integers. :)
604 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
605
606 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000607 // At some point, it may make sense for this tree pattern to have
608 // multiple types. Assert here that it does not, so we revisit this
609 // code when appropriate.
610 assert(getExtTypes().size() == 1 && "TreePattern has too many types!");
611
612 unsigned Size = MVT::getSizeInBits(getTypeNum(0));
Chris Lattner465c7372005-11-03 05:46:11 +0000613 // Make sure that the value is representable for this type.
614 if (Size < 32) {
615 int Val = (II->getValue() << (32-Size)) >> (32-Size);
616 if (Val != II->getValue())
617 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
618 "' is out of range for type 'MVT::" +
Nate Begemanb73628b2005-12-30 00:12:56 +0000619 getEnumName(getTypeNum(0)) + "'!");
Chris Lattner465c7372005-11-03 05:46:11 +0000620 }
621 }
622
623 return MadeChange;
624 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000625 return false;
626 }
Chris Lattner32707602005-09-08 23:22:48 +0000627
628 // special handling for set, which isn't really an SDNode.
629 if (getOperator()->getName() == "set") {
630 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000631 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
632 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000633
634 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000635 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
636 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000637 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
638 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000639 } else if (getOperator()->isSubClassOf("SDNode")) {
640 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
641
642 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
643 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000644 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000645 // Branch, etc. do not produce results and top-level forms in instr pattern
646 // must have void types.
647 if (NI.getNumResults() == 0)
648 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000649 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000650 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000651 const DAGInstruction &Inst =
652 TP.getDAGISelEmitter().getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000653 bool MadeChange = false;
654 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000655
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000656 assert(NumResults <= 1 &&
657 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000658 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000659 if (NumResults == 0) {
660 MadeChange = UpdateNodeType(MVT::isVoid, TP);
661 } else {
662 Record *ResultNode = Inst.getResult(0);
663 assert(ResultNode->isSubClassOf("RegisterClass") &&
664 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000665
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000666 const CodeGenRegisterClass &RC =
667 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000668 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000669 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000670
671 if (getNumChildren() != Inst.getNumOperands())
672 TP.error("Instruction '" + getOperator()->getName() + " expects " +
673 utostr(Inst.getNumOperands()) + " operands, not " +
674 utostr(getNumChildren()) + " operands!");
675 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000676 Record *OperandNode = Inst.getOperand(i);
677 MVT::ValueType VT;
678 if (OperandNode->isSubClassOf("RegisterClass")) {
679 const CodeGenRegisterClass &RC =
680 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000681 //VT = RC.getValueTypeNum(0);
682 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
683 TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000684 } else if (OperandNode->isSubClassOf("Operand")) {
685 VT = getValueType(OperandNode->getValueAsDef("Type"));
Nate Begemanb73628b2005-12-30 00:12:56 +0000686 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000687 } else {
688 assert(0 && "Unknown operand type!");
689 abort();
690 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000691 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000692 }
693 return MadeChange;
694 } else {
695 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
696
697 // Node transforms always take one operand, and take and return the same
698 // type.
699 if (getNumChildren() != 1)
700 TP.error("Node transform '" + getOperator()->getName() +
701 "' requires one operand!");
Nate Begemanb73628b2005-12-30 00:12:56 +0000702 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
703 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000704 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000705 }
Chris Lattner32707602005-09-08 23:22:48 +0000706}
707
Chris Lattnere97603f2005-09-28 19:27:25 +0000708/// canPatternMatch - If it is impossible for this pattern to match on this
709/// target, fill in Reason and return false. Otherwise, return true. This is
710/// used as a santity check for .td files (to prevent people from writing stuff
711/// that can never possibly work), and to prevent the pattern permuter from
712/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000713bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000714 if (isLeaf()) return true;
715
716 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
717 if (!getChild(i)->canPatternMatch(Reason, ISE))
718 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000719
Chris Lattnere97603f2005-09-28 19:27:25 +0000720 // If this node is a commutative operator, check that the LHS isn't an
721 // immediate.
722 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
723 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
724 // Scan all of the operands of the node and make sure that only the last one
725 // is a constant node.
726 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
727 if (!getChild(i)->isLeaf() &&
728 getChild(i)->getOperator()->getName() == "imm") {
729 Reason = "Immediate value must be on the RHS of commutative operators!";
730 return false;
731 }
732 }
733
734 return true;
735}
Chris Lattner32707602005-09-08 23:22:48 +0000736
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000737//===----------------------------------------------------------------------===//
738// TreePattern implementation
739//
740
Chris Lattneredbd8712005-10-21 01:19:59 +0000741TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000742 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000743 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000744 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
745 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000746}
747
Chris Lattneredbd8712005-10-21 01:19:59 +0000748TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000749 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000750 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000751 Trees.push_back(ParseTreePattern(Pat));
752}
753
Chris Lattneredbd8712005-10-21 01:19:59 +0000754TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000755 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000756 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000757 Trees.push_back(Pat);
758}
759
760
761
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000762void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000763 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000764 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000765}
766
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000767TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
768 Record *Operator = Dag->getNodeType();
769
770 if (Operator->isSubClassOf("ValueType")) {
771 // If the operator is a ValueType, then this must be "type cast" of a leaf
772 // node.
773 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000774 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000775
776 Init *Arg = Dag->getArg(0);
777 TreePatternNode *New;
778 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000779 Record *R = DI->getDef();
780 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
781 Dag->setArg(0, new DagInit(R,
782 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000783 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000784 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000785 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000786 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
787 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000788 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
789 New = new TreePatternNode(II);
790 if (!Dag->getArgName(0).empty())
791 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000792 } else {
793 Arg->dump();
794 error("Unknown leaf value for tree pattern!");
795 return 0;
796 }
797
Chris Lattner32707602005-09-08 23:22:48 +0000798 // Apply the type cast.
799 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000800 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000801 return New;
802 }
803
804 // Verify that this is something that makes sense for an operator.
805 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000806 !Operator->isSubClassOf("Instruction") &&
807 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000808 Operator->getName() != "set")
809 error("Unrecognized node '" + Operator->getName() + "'!");
810
Chris Lattneredbd8712005-10-21 01:19:59 +0000811 // Check to see if this is something that is illegal in an input pattern.
812 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
813 Operator->isSubClassOf("SDNodeXForm")))
814 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
815
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000816 std::vector<TreePatternNode*> Children;
817
818 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
819 Init *Arg = Dag->getArg(i);
820 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
821 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000822 if (Children.back()->getName().empty())
823 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000824 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
825 Record *R = DefI->getDef();
826 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
827 // TreePatternNode if its own.
828 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
829 Dag->setArg(i, new DagInit(R,
830 std::vector<std::pair<Init*, std::string> >()));
831 --i; // Revisit this node...
832 } else {
833 TreePatternNode *Node = new TreePatternNode(DefI);
834 Node->setName(Dag->getArgName(i));
835 Children.push_back(Node);
836
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000837 // Input argument?
838 if (R->getName() == "node") {
839 if (Dag->getArgName(i).empty())
840 error("'node' argument requires a name to match with operand list");
841 Args.push_back(Dag->getArgName(i));
842 }
843 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000844 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
845 TreePatternNode *Node = new TreePatternNode(II);
846 if (!Dag->getArgName(i).empty())
847 error("Constant int argument should not have a name!");
848 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000849 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000850 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000851 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000852 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000853 error("Unknown leaf value for tree pattern!");
854 }
855 }
856
857 return new TreePatternNode(Operator, Children);
858}
859
Chris Lattner32707602005-09-08 23:22:48 +0000860/// InferAllTypes - Infer/propagate as many types throughout the expression
861/// patterns as possible. Return true if all types are infered, false
862/// otherwise. Throw an exception if a type contradiction is found.
863bool TreePattern::InferAllTypes() {
864 bool MadeChange = true;
865 while (MadeChange) {
866 MadeChange = false;
867 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000868 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000869 }
870
871 bool HasUnresolvedTypes = false;
872 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
873 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
874 return !HasUnresolvedTypes;
875}
876
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000877void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000878 OS << getRecord()->getName();
879 if (!Args.empty()) {
880 OS << "(" << Args[0];
881 for (unsigned i = 1, e = Args.size(); i != e; ++i)
882 OS << ", " << Args[i];
883 OS << ")";
884 }
885 OS << ": ";
886
887 if (Trees.size() > 1)
888 OS << "[\n";
889 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
890 OS << "\t";
891 Trees[i]->print(OS);
892 OS << "\n";
893 }
894
895 if (Trees.size() > 1)
896 OS << "]\n";
897}
898
899void TreePattern::dump() const { print(std::cerr); }
900
901
902
903//===----------------------------------------------------------------------===//
904// DAGISelEmitter implementation
905//
906
Chris Lattnerca559d02005-09-08 21:03:01 +0000907// Parse all of the SDNode definitions for the target, populating SDNodes.
908void DAGISelEmitter::ParseNodeInfo() {
909 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
910 while (!Nodes.empty()) {
911 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
912 Nodes.pop_back();
913 }
914}
915
Chris Lattner24eeeb82005-09-13 21:51:00 +0000916/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
917/// map, and emit them to the file as functions.
918void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
919 OS << "\n// Node transformations.\n";
920 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
921 while (!Xforms.empty()) {
922 Record *XFormNode = Xforms.back();
923 Record *SDNode = XFormNode->getValueAsDef("Opcode");
924 std::string Code = XFormNode->getValueAsCode("XFormFunction");
925 SDNodeXForms.insert(std::make_pair(XFormNode,
926 std::make_pair(SDNode, Code)));
927
Chris Lattner1048b7a2005-09-13 22:03:37 +0000928 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000929 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
930 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
931
Chris Lattner1048b7a2005-09-13 22:03:37 +0000932 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000933 << "(SDNode *" << C2 << ") {\n";
934 if (ClassName != "SDNode")
935 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
936 OS << Code << "\n}\n";
937 }
938
939 Xforms.pop_back();
940 }
941}
942
Evan Cheng0fc71982005-12-08 02:00:36 +0000943void DAGISelEmitter::ParseComplexPatterns() {
944 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
945 while (!AMs.empty()) {
946 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
947 AMs.pop_back();
948 }
949}
Chris Lattner24eeeb82005-09-13 21:51:00 +0000950
951
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000952/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
953/// file, building up the PatternFragments map. After we've collected them all,
954/// inline fragments together as necessary, so that there are no references left
955/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000956///
957/// This also emits all of the predicate functions to the output file.
958///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000959void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000960 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
961
962 // First step, parse all of the fragments and emit predicate functions.
963 OS << "\n// Predicate functions.\n";
964 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000965 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000966 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000967 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000968
969 // Validate the argument list, converting it to map, to discard duplicates.
970 std::vector<std::string> &Args = P->getArgList();
971 std::set<std::string> OperandsMap(Args.begin(), Args.end());
972
973 if (OperandsMap.count(""))
974 P->error("Cannot have unnamed 'node' values in pattern fragment!");
975
976 // Parse the operands list.
977 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
978 if (OpsList->getNodeType()->getName() != "ops")
979 P->error("Operands list should start with '(ops ... '!");
980
981 // Copy over the arguments.
982 Args.clear();
983 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
984 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
985 static_cast<DefInit*>(OpsList->getArg(j))->
986 getDef()->getName() != "node")
987 P->error("Operands list should all be 'node' values.");
988 if (OpsList->getArgName(j).empty())
989 P->error("Operands list should have names for each operand!");
990 if (!OperandsMap.count(OpsList->getArgName(j)))
991 P->error("'" + OpsList->getArgName(j) +
992 "' does not occur in pattern or was multiply specified!");
993 OperandsMap.erase(OpsList->getArgName(j));
994 Args.push_back(OpsList->getArgName(j));
995 }
996
997 if (!OperandsMap.empty())
998 P->error("Operands list does not contain an entry for operand '" +
999 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001000
1001 // If there is a code init for this fragment, emit the predicate code and
1002 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +00001003 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1004 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +00001005 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001006 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +00001007 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001008 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1009
Chris Lattner1048b7a2005-09-13 22:03:37 +00001010 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001011 << "(SDNode *" << C2 << ") {\n";
1012 if (ClassName != "SDNode")
1013 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +00001014 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +00001015 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001016 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001017
1018 // If there is a node transformation corresponding to this, keep track of
1019 // it.
1020 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1021 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001022 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001023 }
1024
1025 OS << "\n\n";
1026
1027 // Now that we've parsed all of the tree fragments, do a closure on them so
1028 // that there are not references to PatFrags left inside of them.
1029 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1030 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001031 TreePattern *ThePat = I->second;
1032 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001033
Chris Lattner32707602005-09-08 23:22:48 +00001034 // Infer as many types as possible. Don't worry about it if we don't infer
1035 // all of them, some may depend on the inputs of the pattern.
1036 try {
1037 ThePat->InferAllTypes();
1038 } catch (...) {
1039 // If this pattern fragment is not supported by this target (no types can
1040 // satisfy its constraints), just ignore it. If the bogus pattern is
1041 // actually used by instructions, the type consistency error will be
1042 // reported there.
1043 }
1044
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001045 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001046 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001047 }
1048}
1049
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001050/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001051/// instruction input. Return true if this is a real use.
1052static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001053 std::map<std::string, TreePatternNode*> &InstInputs,
1054 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001055 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001056 if (Pat->getName().empty()) {
1057 if (Pat->isLeaf()) {
1058 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1059 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1060 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001061 else if (DI && DI->getDef()->isSubClassOf("Register"))
1062 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001063 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001064 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001065 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001066
1067 Record *Rec;
1068 if (Pat->isLeaf()) {
1069 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1070 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1071 Rec = DI->getDef();
1072 } else {
1073 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1074 Rec = Pat->getOperator();
1075 }
1076
Evan Cheng01f318b2005-12-14 02:21:57 +00001077 // SRCVALUE nodes are ignored.
1078 if (Rec->getName() == "srcvalue")
1079 return false;
1080
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001081 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1082 if (!Slot) {
1083 Slot = Pat;
1084 } else {
1085 Record *SlotRec;
1086 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001087 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001088 } else {
1089 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1090 SlotRec = Slot->getOperator();
1091 }
1092
1093 // Ensure that the inputs agree if we've already seen this input.
1094 if (Rec != SlotRec)
1095 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001096 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001097 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1098 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001099 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001100}
1101
1102/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1103/// part of "I", the instruction), computing the set of inputs and outputs of
1104/// the pattern. Report errors if we see anything naughty.
1105void DAGISelEmitter::
1106FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1107 std::map<std::string, TreePatternNode*> &InstInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001108 std::map<std::string, Record*> &InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001109 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001110 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001111 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001112 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001113 if (!isUse && Pat->getTransformFn())
1114 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001115 return;
1116 } else if (Pat->getOperator()->getName() != "set") {
1117 // If this is not a set, verify that the children nodes are not void typed,
1118 // and recurse.
1119 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001120 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001121 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001122 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001123 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001124 }
1125
1126 // If this is a non-leaf node with no children, treat it basically as if
1127 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001128 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001129 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001130 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001131
Chris Lattnerf1311842005-09-14 23:05:13 +00001132 if (!isUse && Pat->getTransformFn())
1133 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001134 return;
1135 }
1136
1137 // Otherwise, this is a set, validate and collect instruction results.
1138 if (Pat->getNumChildren() == 0)
1139 I->error("set requires operands!");
1140 else if (Pat->getNumChildren() & 1)
1141 I->error("set requires an even number of operands");
1142
Chris Lattnerf1311842005-09-14 23:05:13 +00001143 if (Pat->getTransformFn())
1144 I->error("Cannot specify a transform function on a set node!");
1145
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001146 // Check the set destinations.
1147 unsigned NumValues = Pat->getNumChildren()/2;
1148 for (unsigned i = 0; i != NumValues; ++i) {
1149 TreePatternNode *Dest = Pat->getChild(i);
1150 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001151 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001152
1153 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1154 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001155 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001156
Evan Chengbcecf332005-12-17 01:19:28 +00001157 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1158 if (Dest->getName().empty())
1159 I->error("set destination must have a name!");
1160 if (InstResults.count(Dest->getName()))
1161 I->error("cannot set '" + Dest->getName() +"' multiple times");
1162 InstResults[Dest->getName()] = Val->getDef();
Evan Cheng7b05bd52005-12-23 22:11:47 +00001163 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001164 InstImpResults.push_back(Val->getDef());
1165 } else {
1166 I->error("set destination should be a register!");
1167 }
1168
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001169 // Verify and collect info from the computation.
1170 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001171 InstInputs, InstResults,
1172 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001173 }
1174}
1175
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001176/// ParseInstructions - Parse all of the instructions, inlining and resolving
1177/// any fragments involved. This populates the Instructions list with fully
1178/// resolved instructions.
1179void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001180 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1181
1182 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001183 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001184
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001185 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1186 LI = Instrs[i]->getValueAsListInit("Pattern");
1187
1188 // If there is no pattern, only collect minimal information about the
1189 // instruction for its operand list. We have to assume that there is one
1190 // result, as we have no detailed info.
1191 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001192 std::vector<Record*> Results;
1193 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001194
1195 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001196
Evan Cheng3a217f32005-12-22 02:35:21 +00001197 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001198 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001199 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001200 // These produce no results
1201 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1202 Operands.push_back(InstInfo.OperandList[j].Rec);
1203 } else {
1204 // Assume the first operand is the result.
1205 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001206
Evan Cheng3a217f32005-12-22 02:35:21 +00001207 // The rest are inputs.
1208 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1209 Operands.push_back(InstInfo.OperandList[j].Rec);
1210 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001211 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001212
1213 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001214 std::vector<Record*> ImpResults;
1215 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001216 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001217 DAGInstruction(0, Results, Operands, ImpResults,
1218 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001219 continue; // no pattern.
1220 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001221
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001222 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001223 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001224 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001225 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001226
Chris Lattner95f6b762005-09-08 23:26:30 +00001227 // Infer as many types as possible. If we cannot infer all of them, we can
1228 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001229 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001230 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001231
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001232 // InstInputs - Keep track of all of the inputs of the instruction, along
1233 // with the record they are declared as.
1234 std::map<std::string, TreePatternNode*> InstInputs;
1235
1236 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001237 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001238 std::map<std::string, Record*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001239
1240 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001241 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001242
Chris Lattner1f39e292005-09-14 00:09:24 +00001243 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001244 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001245 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1246 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001247 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001248 I->error("Top-level forms in instruction pattern should have"
1249 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001250
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001251 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001252 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001253 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001254 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001255
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001256 // Now that we have inputs and outputs of the pattern, inspect the operands
1257 // list for the instruction. This determines the order that operands are
1258 // added to the machine instruction the node corresponds to.
1259 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001260
1261 // Parse the operands list from the (ops) list, validating it.
1262 std::vector<std::string> &Args = I->getArgList();
1263 assert(Args.empty() && "Args list should still be empty here!");
1264 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1265
1266 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001267 std::vector<Record*> Results;
Chris Lattner39e8af92005-09-14 18:19:25 +00001268 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001269 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001270 I->error("'" + InstResults.begin()->first +
1271 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001272 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001273
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001274 // Check that it exists in InstResults.
1275 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001276 if (R == 0)
1277 I->error("Operand $" + OpName + " should be a set destination: all "
1278 "outputs must occur before inputs in operand list!");
1279
1280 if (CGI.OperandList[i].Rec != R)
1281 I->error("Operand $" + OpName + " class mismatch!");
1282
Chris Lattnerae6d8282005-09-15 21:51:12 +00001283 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001284 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001285
Chris Lattner39e8af92005-09-14 18:19:25 +00001286 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001287 InstResults.erase(OpName);
1288 }
1289
Chris Lattner0b592252005-09-14 21:59:34 +00001290 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1291 // the copy while we're checking the inputs.
1292 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001293
1294 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001295 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001296 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1297 const std::string &OpName = CGI.OperandList[i].Name;
1298 if (OpName.empty())
1299 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1300
Chris Lattner0b592252005-09-14 21:59:34 +00001301 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001302 I->error("Operand $" + OpName +
1303 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001304 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001305 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001306
1307 if (InVal->isLeaf() &&
1308 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1309 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001310 if (CGI.OperandList[i].Rec != InRec &&
1311 !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001312 I->error("Operand $" + OpName + "'s register class disagrees"
1313 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001314 }
1315 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001316
Chris Lattner2175c182005-09-14 23:01:59 +00001317 // Construct the result for the dest-pattern operand list.
1318 TreePatternNode *OpNode = InVal->clone();
1319
1320 // No predicate is useful on the result.
1321 OpNode->setPredicateFn("");
1322
1323 // Promote the xform function to be an explicit node if set.
1324 if (Record *Xform = OpNode->getTransformFn()) {
1325 OpNode->setTransformFn(0);
1326 std::vector<TreePatternNode*> Children;
1327 Children.push_back(OpNode);
1328 OpNode = new TreePatternNode(Xform, Children);
1329 }
1330
1331 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001332 }
1333
Chris Lattner0b592252005-09-14 21:59:34 +00001334 if (!InstInputsCheck.empty())
1335 I->error("Input operand $" + InstInputsCheck.begin()->first +
1336 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001337
1338 TreePatternNode *ResultPattern =
1339 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001340
1341 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001342 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001343 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1344
1345 // Use a temporary tree pattern to infer all types and make sure that the
1346 // constructed result is correct. This depends on the instruction already
1347 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001348 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001349 Temp.InferAllTypes();
1350
1351 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1352 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001353
Chris Lattner32707602005-09-08 23:22:48 +00001354 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001355 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001356
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001357 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001358 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1359 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001360 DAGInstruction &TheInst = II->second;
1361 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001362 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001363
Chris Lattner1f39e292005-09-14 00:09:24 +00001364 if (I->getNumTrees() != 1) {
1365 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1366 continue;
1367 }
1368 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001369 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001370 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001371 if (Pattern->getNumChildren() != 2)
1372 continue; // Not a set of a single value (not handled so far)
1373
1374 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001375 } else{
1376 // Not a set (store or something?)
1377 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001378 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001379
1380 std::string Reason;
1381 if (!SrcPattern->canPatternMatch(Reason, *this))
1382 I->error("Instruction can never match: " + Reason);
1383
Evan Cheng58e84a62005-12-14 22:02:59 +00001384 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001385 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001386 PatternsToMatch.
1387 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1388 SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001389 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001390}
1391
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001392void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001393 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001394
Chris Lattnerabbb6052005-09-15 21:42:00 +00001395 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001396 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001397 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001398
Chris Lattnerabbb6052005-09-15 21:42:00 +00001399 // Inline pattern fragments into it.
1400 Pattern->InlinePatternFragments();
1401
1402 // Infer as many types as possible. If we cannot infer all of them, we can
1403 // never do anything with this pattern: report it to the user.
1404 if (!Pattern->InferAllTypes())
1405 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001406
1407 // Validate that the input pattern is correct.
1408 {
1409 std::map<std::string, TreePatternNode*> InstInputs;
1410 std::map<std::string, Record*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001411 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001412 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001413 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001414 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001415 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001416 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001417
1418 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1419 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001420
1421 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001422 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001423
1424 // Inline pattern fragments into it.
1425 Result->InlinePatternFragments();
1426
1427 // Infer as many types as possible. If we cannot infer all of them, we can
1428 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001429 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001430 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001431
1432 if (Result->getNumTrees() != 1)
1433 Result->error("Cannot handle instructions producing instructions "
1434 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001435
1436 std::string Reason;
1437 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1438 Pattern->error("Pattern can never match: " + Reason);
1439
Evan Cheng58e84a62005-12-14 22:02:59 +00001440 PatternsToMatch.
1441 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1442 Pattern->getOnlyTree(),
1443 Result->getOnlyTree()));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001444 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001445}
1446
Chris Lattnere46e17b2005-09-29 19:28:10 +00001447/// CombineChildVariants - Given a bunch of permutations of each child of the
1448/// 'operator' node, put them together in all possible ways.
1449static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001450 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001451 std::vector<TreePatternNode*> &OutVariants,
1452 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001453 // Make sure that each operand has at least one variant to choose from.
1454 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1455 if (ChildVariants[i].empty())
1456 return;
1457
Chris Lattnere46e17b2005-09-29 19:28:10 +00001458 // The end result is an all-pairs construction of the resultant pattern.
1459 std::vector<unsigned> Idxs;
1460 Idxs.resize(ChildVariants.size());
1461 bool NotDone = true;
1462 while (NotDone) {
1463 // Create the variant and add it to the output list.
1464 std::vector<TreePatternNode*> NewChildren;
1465 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1466 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1467 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1468
1469 // Copy over properties.
1470 R->setName(Orig->getName());
1471 R->setPredicateFn(Orig->getPredicateFn());
1472 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001473 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001474
1475 // If this pattern cannot every match, do not include it as a variant.
1476 std::string ErrString;
1477 if (!R->canPatternMatch(ErrString, ISE)) {
1478 delete R;
1479 } else {
1480 bool AlreadyExists = false;
1481
1482 // Scan to see if this pattern has already been emitted. We can get
1483 // duplication due to things like commuting:
1484 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1485 // which are the same pattern. Ignore the dups.
1486 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1487 if (R->isIsomorphicTo(OutVariants[i])) {
1488 AlreadyExists = true;
1489 break;
1490 }
1491
1492 if (AlreadyExists)
1493 delete R;
1494 else
1495 OutVariants.push_back(R);
1496 }
1497
1498 // Increment indices to the next permutation.
1499 NotDone = false;
1500 // Look for something we can increment without causing a wrap-around.
1501 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1502 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1503 NotDone = true; // Found something to increment.
1504 break;
1505 }
1506 Idxs[IdxsIdx] = 0;
1507 }
1508 }
1509}
1510
Chris Lattneraf302912005-09-29 22:36:54 +00001511/// CombineChildVariants - A helper function for binary operators.
1512///
1513static void CombineChildVariants(TreePatternNode *Orig,
1514 const std::vector<TreePatternNode*> &LHS,
1515 const std::vector<TreePatternNode*> &RHS,
1516 std::vector<TreePatternNode*> &OutVariants,
1517 DAGISelEmitter &ISE) {
1518 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1519 ChildVariants.push_back(LHS);
1520 ChildVariants.push_back(RHS);
1521 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1522}
1523
1524
1525static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1526 std::vector<TreePatternNode *> &Children) {
1527 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1528 Record *Operator = N->getOperator();
1529
1530 // Only permit raw nodes.
1531 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1532 N->getTransformFn()) {
1533 Children.push_back(N);
1534 return;
1535 }
1536
1537 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1538 Children.push_back(N->getChild(0));
1539 else
1540 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1541
1542 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1543 Children.push_back(N->getChild(1));
1544 else
1545 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1546}
1547
Chris Lattnere46e17b2005-09-29 19:28:10 +00001548/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1549/// the (potentially recursive) pattern by using algebraic laws.
1550///
1551static void GenerateVariantsOf(TreePatternNode *N,
1552 std::vector<TreePatternNode*> &OutVariants,
1553 DAGISelEmitter &ISE) {
1554 // We cannot permute leaves.
1555 if (N->isLeaf()) {
1556 OutVariants.push_back(N);
1557 return;
1558 }
1559
1560 // Look up interesting info about the node.
1561 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1562
1563 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001564 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1565 // Reassociate by pulling together all of the linked operators
1566 std::vector<TreePatternNode*> MaximalChildren;
1567 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1568
1569 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1570 // permutations.
1571 if (MaximalChildren.size() == 3) {
1572 // Find the variants of all of our maximal children.
1573 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1574 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1575 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1576 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1577
1578 // There are only two ways we can permute the tree:
1579 // (A op B) op C and A op (B op C)
1580 // Within these forms, we can also permute A/B/C.
1581
1582 // Generate legal pair permutations of A/B/C.
1583 std::vector<TreePatternNode*> ABVariants;
1584 std::vector<TreePatternNode*> BAVariants;
1585 std::vector<TreePatternNode*> ACVariants;
1586 std::vector<TreePatternNode*> CAVariants;
1587 std::vector<TreePatternNode*> BCVariants;
1588 std::vector<TreePatternNode*> CBVariants;
1589 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1590 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1591 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1592 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1593 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1594 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1595
1596 // Combine those into the result: (x op x) op x
1597 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1598 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1599 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1600 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1601 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1602 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1603
1604 // Combine those into the result: x op (x op x)
1605 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1606 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1607 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1608 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1609 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1610 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1611 return;
1612 }
1613 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001614
1615 // Compute permutations of all children.
1616 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1617 ChildVariants.resize(N->getNumChildren());
1618 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1619 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1620
1621 // Build all permutations based on how the children were formed.
1622 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1623
1624 // If this node is commutative, consider the commuted order.
1625 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1626 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001627 // Consider the commuted order.
1628 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1629 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001630 }
1631}
1632
1633
Chris Lattnere97603f2005-09-28 19:27:25 +00001634// GenerateVariants - Generate variants. For example, commutative patterns can
1635// match multiple ways. Add them to PatternsToMatch as well.
1636void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001637
1638 DEBUG(std::cerr << "Generating instruction variants.\n");
1639
1640 // Loop over all of the patterns we've collected, checking to see if we can
1641 // generate variants of the instruction, through the exploitation of
1642 // identities. This permits the target to provide agressive matching without
1643 // the .td file having to contain tons of variants of instructions.
1644 //
1645 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1646 // intentionally do not reconsider these. Any variants of added patterns have
1647 // already been added.
1648 //
1649 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1650 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001651 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001652
1653 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001654 Variants.erase(Variants.begin()); // Remove the original pattern.
1655
1656 if (Variants.empty()) // No variants for this pattern.
1657 continue;
1658
1659 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001660 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001661 std::cerr << "\n");
1662
1663 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1664 TreePatternNode *Variant = Variants[v];
1665
1666 DEBUG(std::cerr << " VAR#" << v << ": ";
1667 Variant->dump();
1668 std::cerr << "\n");
1669
1670 // Scan to see if an instruction or explicit pattern already matches this.
1671 bool AlreadyExists = false;
1672 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1673 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001674 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001675 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1676 AlreadyExists = true;
1677 break;
1678 }
1679 }
1680 // If we already have it, ignore the variant.
1681 if (AlreadyExists) continue;
1682
1683 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001684 PatternsToMatch.
1685 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1686 Variant, PatternsToMatch[i].getDstPattern()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001687 }
1688
1689 DEBUG(std::cerr << "\n");
1690 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001691}
1692
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001693
Evan Cheng0fc71982005-12-08 02:00:36 +00001694// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1695// ComplexPattern.
1696static bool NodeIsComplexPattern(TreePatternNode *N)
1697{
1698 return (N->isLeaf() &&
1699 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1700 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1701 isSubClassOf("ComplexPattern"));
1702}
1703
1704// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1705// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1706static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1707 DAGISelEmitter &ISE)
1708{
1709 if (N->isLeaf() &&
1710 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1711 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1712 isSubClassOf("ComplexPattern")) {
1713 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1714 ->getDef());
1715 }
1716 return NULL;
1717}
1718
Chris Lattner05814af2005-09-28 17:57:56 +00001719/// getPatternSize - Return the 'size' of this pattern. We want to match large
1720/// patterns before small ones. This is used to determine the size of a
1721/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001722static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng4a7c2842006-01-06 22:19:44 +00001723 assert(isExtIntegerInVTs(P->getExtTypes()) ||
1724 isExtFloatingPointInVTs(P->getExtTypes()) ||
1725 P->getExtTypeNum(0) == MVT::isVoid ||
1726 P->getExtTypeNum(0) == MVT::Flag &&
1727 "Not a valid pattern node to size!");
Evan Chenge1050d62006-01-06 02:30:23 +00001728 unsigned Size = 2; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00001729 // If the root node is a ConstantSDNode, increases its size.
1730 // e.g. (set R32:$dst, 0).
1731 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1732 Size++;
Evan Cheng0fc71982005-12-08 02:00:36 +00001733
1734 // FIXME: This is a hack to statically increase the priority of patterns
1735 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1736 // Later we can allow complexity / cost for each pattern to be (optionally)
1737 // specified. To get best possible pattern match we'll need to dynamically
1738 // calculate the complexity of all patterns a dag can potentially map to.
1739 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1740 if (AM)
Evan Cheng4a7c2842006-01-06 22:19:44 +00001741 Size += AM->getNumOperands() * 2;
Chris Lattner3e179802006-02-03 18:06:02 +00001742
1743 // If this node has some predicate function that must match, it adds to the
1744 // complexity of this node.
1745 if (!P->getPredicateFn().empty())
1746 ++Size;
1747
Chris Lattner05814af2005-09-28 17:57:56 +00001748 // Count children in the count if they are also nodes.
1749 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1750 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001751 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001752 Size += getPatternSize(Child, ISE);
1753 else if (Child->isLeaf()) {
1754 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner3e179802006-02-03 18:06:02 +00001755 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
Evan Cheng4a7c2842006-01-06 22:19:44 +00001756 else if (NodeIsComplexPattern(Child))
1757 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00001758 else if (!Child->getPredicateFn().empty())
1759 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00001760 }
Chris Lattner05814af2005-09-28 17:57:56 +00001761 }
1762
1763 return Size;
1764}
1765
1766/// getResultPatternCost - Compute the number of instructions for this pattern.
1767/// This is a temporary hack. We should really include the instruction
1768/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00001769static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00001770 if (P->isLeaf()) return 0;
1771
Evan Chengfbad7082006-02-18 02:33:09 +00001772 unsigned Cost = 0;
1773 Record *Op = P->getOperator();
1774 if (Op->isSubClassOf("Instruction")) {
1775 Cost++;
1776 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1777 if (II.usesCustomDAGSchedInserter)
1778 Cost += 10;
1779 }
Chris Lattner05814af2005-09-28 17:57:56 +00001780 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00001781 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001782 return Cost;
1783}
1784
1785// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1786// In particular, we want to match maximal patterns first and lowest cost within
1787// a particular complexity first.
1788struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001789 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1790 DAGISelEmitter &ISE;
1791
Evan Cheng58e84a62005-12-14 22:02:59 +00001792 bool operator()(PatternToMatch *LHS,
1793 PatternToMatch *RHS) {
1794 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1795 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001796 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1797 if (LHSSize < RHSSize) return false;
1798
1799 // If the patterns have equal complexity, compare generated instruction cost
Evan Chengfbad7082006-02-18 02:33:09 +00001800 return getResultPatternCost(LHS->getDstPattern(), ISE) <
1801 getResultPatternCost(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001802 }
1803};
1804
Nate Begeman6510b222005-12-01 04:51:06 +00001805/// getRegisterValueType - Look up and return the first ValueType of specified
1806/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001807static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001808 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1809 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001810 return MVT::Other;
1811}
1812
Chris Lattner72fe91c2005-09-24 00:40:24 +00001813
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001814/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1815/// type information from it.
1816static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001817 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001818 if (!N->isLeaf())
1819 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1820 RemoveAllTypes(N->getChild(i));
1821}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001822
Chris Lattner0614b622005-11-02 06:49:14 +00001823Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1824 Record *N = Records.getDef(Name);
1825 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1826 return N;
1827}
1828
Evan Cheng51fecc82006-01-09 18:27:06 +00001829/// NodeHasProperty - return true if TreePatternNode has the specified
1830/// property.
1831static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1832 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001833{
1834 if (N->isLeaf()) return false;
1835 Record *Operator = N->getOperator();
1836 if (!Operator->isSubClassOf("SDNode")) return false;
1837
1838 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00001839 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00001840}
1841
Evan Cheng51fecc82006-01-09 18:27:06 +00001842static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1843 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001844{
Evan Cheng51fecc82006-01-09 18:27:06 +00001845 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00001846 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00001847
1848 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1849 TreePatternNode *Child = N->getChild(i);
1850 if (PatternHasProperty(Child, Property, ISE))
1851 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001852 }
1853
1854 return false;
1855}
1856
Evan Chengb915f312005-12-09 22:45:35 +00001857class PatternCodeEmitter {
1858private:
1859 DAGISelEmitter &ISE;
1860
Evan Cheng58e84a62005-12-14 22:02:59 +00001861 // Predicates.
1862 ListInit *Predicates;
1863 // Instruction selector pattern.
1864 TreePatternNode *Pattern;
1865 // Matched instruction.
1866 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001867
Evan Chengb915f312005-12-09 22:45:35 +00001868 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00001869 std::map<std::string, std::string> VariableMap;
1870 // Node to operator mapping
1871 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00001872 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001873 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00001874 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +00001875
Chris Lattner8a0604b2006-01-28 20:31:24 +00001876 /// GeneratedCode - This is the buffer that we emit code to. The first bool
1877 /// indicates whether this is an exit predicate (something that should be
1878 /// tested, and if true, the match fails) [when true] or normal code to emit
1879 /// [when false].
1880 std::vector<std::pair<bool, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00001881 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
1882 /// the set of patterns for each top-level opcode.
Evan Chengd7805a72006-02-09 07:16:09 +00001883 std::set<std::pair<bool, std::string> > &GeneratedDecl;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001884
Evan Chenge4a8a6e2006-02-03 06:22:41 +00001885 std::string ChainName;
Evan Chenged66e852006-03-09 08:19:11 +00001886 bool NewTF;
Evan Chenge41bf822006-02-05 06:43:12 +00001887 bool DoReplace;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001888 unsigned TmpNo;
1889
1890 void emitCheck(const std::string &S) {
1891 if (!S.empty())
1892 GeneratedCode.push_back(std::make_pair(true, S));
1893 }
1894 void emitCode(const std::string &S) {
1895 if (!S.empty())
1896 GeneratedCode.push_back(std::make_pair(false, S));
1897 }
Evan Chengd7805a72006-02-09 07:16:09 +00001898 void emitDecl(const std::string &S, bool isSDNode=false) {
Evan Cheng21ad3922006-02-07 00:37:41 +00001899 assert(!S.empty() && "Invalid declaration");
Evan Chengd7805a72006-02-09 07:16:09 +00001900 GeneratedDecl.insert(std::make_pair(isSDNode, S));
Evan Cheng21ad3922006-02-07 00:37:41 +00001901 }
Evan Chengb915f312005-12-09 22:45:35 +00001902public:
Evan Cheng58e84a62005-12-14 22:02:59 +00001903 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1904 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng21ad3922006-02-07 00:37:41 +00001905 std::vector<std::pair<bool, std::string> > &gc,
Evan Chengd7805a72006-02-09 07:16:09 +00001906 std::set<std::pair<bool, std::string> > &gd,
Evan Cheng21ad3922006-02-07 00:37:41 +00001907 bool dorep)
Chris Lattner8a0604b2006-01-28 20:31:24 +00001908 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Chenged66e852006-03-09 08:19:11 +00001909 GeneratedCode(gc), GeneratedDecl(gd),
1910 NewTF(false), DoReplace(dorep), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00001911
1912 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1913 /// if the match fails. At this point, we already know that the opcode for N
1914 /// matches, and the SDNode for the result has the RootName specified name.
Evan Chenge41bf822006-02-05 06:43:12 +00001915 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
1916 const std::string &RootName, const std::string &ParentName,
1917 const std::string &ChainSuffix, bool &FoundChain) {
1918 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00001919 // Emit instruction predicates. Each predicate is just a string for now.
1920 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00001921 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00001922 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1923 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1924 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00001925 if (!Def->isSubClassOf("Predicate")) {
Evan Cheng58e84a62005-12-14 22:02:59 +00001926 Def->dump();
1927 assert(0 && "Unknown predicate type!");
1928 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00001929 if (!PredicateCheck.empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00001930 PredicateCheck += " || ";
1931 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00001932 }
1933 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00001934
1935 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00001936 }
1937
Evan Chengb915f312005-12-09 22:45:35 +00001938 if (N->isLeaf()) {
1939 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00001940 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00001941 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00001942 return;
1943 } else if (!NodeIsComplexPattern(N)) {
1944 assert(0 && "Cannot match this as a leaf value!");
1945 abort();
1946 }
1947 }
1948
Chris Lattner488580c2006-01-28 19:06:51 +00001949 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00001950 // we already saw this in the pattern, emit code to verify dagness.
1951 if (!N->getName().empty()) {
1952 std::string &VarMapEntry = VariableMap[N->getName()];
1953 if (VarMapEntry.empty()) {
1954 VarMapEntry = RootName;
1955 } else {
1956 // If we get here, this is a second reference to a specific name. Since
1957 // we already have checked that the first reference is valid, we don't
1958 // have to recursively match it, just check that it's the same as the
1959 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00001960 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00001961 return;
1962 }
Evan Chengf805c2e2006-01-12 19:35:54 +00001963
1964 if (!N->isLeaf())
1965 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00001966 }
1967
1968
1969 // Emit code to load the child nodes and match their contents recursively.
1970 unsigned OpNo = 0;
Evan Chenge41bf822006-02-05 06:43:12 +00001971 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
1972 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
1973 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00001974 bool EmittedUseCheck = false;
1975 bool EmittedSlctedCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00001976 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00001977 if (NodeHasChain)
1978 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00001979 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00001980 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattner8a0604b2006-01-28 20:31:24 +00001981 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00001982 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00001983 EmittedUseCheck = true;
1984 // hasOneUse() check is not strong enough. If the original node has
1985 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00001986 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00001987 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00001988 "))");
1989
Evan Cheng1feeeec2006-01-26 19:13:45 +00001990 EmittedSlctedCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00001991 if (NodeHasChain) {
1992 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
1993 // has a chain use.
1994 // This a workaround for this problem:
1995 //
1996 // [ch, r : ld]
1997 // ^ ^
1998 // | |
1999 // [XX]--/ \- [flag : cmp]
2000 // ^ ^
2001 // | |
2002 // \---[br flag]-
2003 //
2004 // cmp + br should be considered as a single node as they are flagged
2005 // together. So, if the ld is folded into the cmp, the XX node in the
2006 // graph is now both an operand and a use of the ld/cmp/br node.
2007 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2008 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2009
2010 // If the immediate use can somehow reach this node through another
2011 // path, then can't fold it either or it will create a cycle.
2012 // e.g. In the following diagram, XX can reach ld through YY. If
2013 // ld is folded into XX, then YY is both a predecessor and a successor
2014 // of XX.
2015 //
2016 // [ld]
2017 // ^ ^
2018 // | |
2019 // / \---
2020 // / [YY]
2021 // | ^
2022 // [XX]-------|
2023 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2024 if (PInfo.getNumOperands() > 1 ||
2025 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2026 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2027 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
Evan Cheng6f8aaf22006-03-07 08:31:27 +00002028 if (PInfo.getNumOperands() > 1) {
2029 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2030 ".Val)");
2031 } else {
2032 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2033 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2034 ".Val))");
2035 }
Evan Chenge41bf822006-02-05 06:43:12 +00002036 }
Evan Chengb915f312005-12-09 22:45:35 +00002037 }
Evan Chenge41bf822006-02-05 06:43:12 +00002038
Evan Chengc15d18c2006-01-27 22:13:45 +00002039 if (NodeHasChain) {
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002040 ChainName = "Chain" + ChainSuffix;
Evan Cheng21ad3922006-02-07 00:37:41 +00002041 emitDecl(ChainName);
Evan Chenged66e852006-03-09 08:19:11 +00002042 if (FoundChain) {
2043 // FIXME: temporary workaround for a common case where chain
2044 // is a TokenFactor and the previous "inner" chain is an operand.
2045 NewTF = true;
2046 emitDecl("OldTF", true);
2047 emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2048 RootName + ".Val, Chain.Val, OldTF)).Val");
2049 } else {
2050 FoundChain = true;
2051 emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2052 }
Evan Cheng1cf6db22006-01-06 00:41:12 +00002053 }
Evan Chengb915f312005-12-09 22:45:35 +00002054 }
2055
Evan Cheng54597732006-01-26 00:22:25 +00002056 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002057 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002058 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002059 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2060 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002061 if (!isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002062 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2063 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2064 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002065 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2066 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002067 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002068 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002069 }
Evan Cheng1feeeec2006-01-26 19:13:45 +00002070 if (!EmittedSlctedCheck)
2071 // hasOneUse() check is not strong enough. If the original node has
2072 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002073 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002074 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002075 "))");
Evan Cheng54597732006-01-26 00:22:25 +00002076 }
2077
Evan Chengb915f312005-12-09 22:45:35 +00002078 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002079 emitDecl(RootName + utostr(OpNo));
2080 emitCode(RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002081 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002082 TreePatternNode *Child = N->getChild(i);
2083
2084 if (!Child->isLeaf()) {
2085 // If it's not a leaf, recursively match.
2086 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
Chris Lattner67a202b2006-01-28 20:43:52 +00002087 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002088 CInfo.getEnumName());
Evan Chenge41bf822006-02-05 06:43:12 +00002089 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2090 ChainSuffix + utostr(OpNo), FoundChain);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002091 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002092 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2093 CInfo.getNumResults()));
Evan Chengb915f312005-12-09 22:45:35 +00002094 } else {
Chris Lattner488580c2006-01-28 19:06:51 +00002095 // If this child has a name associated with it, capture it in VarMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002096 // we already saw this in the pattern, emit code to verify dagness.
2097 if (!Child->getName().empty()) {
2098 std::string &VarMapEntry = VariableMap[Child->getName()];
2099 if (VarMapEntry.empty()) {
2100 VarMapEntry = RootName + utostr(OpNo);
2101 } else {
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002102 // If we get here, this is a second reference to a specific name.
2103 // Since we already have checked that the first reference is valid,
2104 // we don't have to recursively match it, just check that it's the
2105 // same as the previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002106 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
Evan Chengb4ad33c2006-01-19 01:55:45 +00002107 Duplicates.insert(RootName + utostr(OpNo));
Evan Chengb915f312005-12-09 22:45:35 +00002108 continue;
2109 }
2110 }
2111
2112 // Handle leaves of various types.
2113 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2114 Record *LeafRec = DI->getDef();
2115 if (LeafRec->isSubClassOf("RegisterClass")) {
2116 // Handle register references. Nothing to do here.
2117 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00002118 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00002119 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2120 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00002121 } else if (LeafRec->getName() == "srcvalue") {
2122 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00002123 } else if (LeafRec->isSubClassOf("ValueType")) {
2124 // Make sure this is the specified value type.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002125 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002126 ")->getVT() == MVT::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002127 } else if (LeafRec->isSubClassOf("CondCode")) {
2128 // Make sure this is the specified cond code.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002129 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002130 ")->get() == ISD::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002131 } else {
2132 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00002133 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00002134 assert(0 && "Unknown leaf type!");
2135 }
Chris Lattner488580c2006-01-28 19:06:51 +00002136 } else if (IntInit *II =
2137 dynamic_cast<IntInit*>(Child->getLeafValue())) {
Chris Lattner8bc74722006-01-29 04:25:26 +00002138 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2139 unsigned CTmp = TmpNo++;
Andrew Lenharth8e517732006-01-29 05:22:37 +00002140 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
Chris Lattner8bc74722006-01-29 04:25:26 +00002141 RootName + utostr(OpNo) + ")->getSignExtended();");
2142
2143 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002144 } else {
2145 Child->dump();
2146 assert(0 && "Unknown leaf type!");
2147 }
2148 }
2149 }
2150
2151 // If there is a node predicate for this, emit the call.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002152 if (!N->getPredicateFn().empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002153 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
Evan Chengb915f312005-12-09 22:45:35 +00002154 }
2155
2156 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2157 /// we actually have to build a DAG!
2158 std::pair<unsigned, unsigned>
2159 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
2160 // This is something selected from the pattern we matched.
2161 if (!N->getName().empty()) {
2162 assert(!isRoot && "Root of pattern cannot be a leaf!");
2163 std::string &Val = VariableMap[N->getName()];
2164 assert(!Val.empty() &&
2165 "Variable referenced but not defined and not caught earlier!");
2166 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2167 // Already selected this operand, just return the tmpval.
2168 return std::make_pair(1, atoi(Val.c_str()+3));
2169 }
2170
2171 const ComplexPattern *CP;
2172 unsigned ResNo = TmpNo++;
2173 unsigned NumRes = 1;
2174 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002175 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002176 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002177 switch (N->getTypeNum(0)) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002178 default: assert(0 && "Unknown type for constant node!");
Chris Lattner78593132006-01-29 20:01:35 +00002179 case MVT::i1: CastType = "bool"; break;
2180 case MVT::i8: CastType = "unsigned char"; break;
2181 case MVT::i16: CastType = "unsigned short"; break;
2182 case MVT::i32: CastType = "unsigned"; break;
2183 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002184 }
Chris Lattner78593132006-01-29 20:01:35 +00002185 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
Andrew Lenharth2cba57c2006-01-29 05:17:22 +00002186 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
Evan Cheng21ad3922006-02-07 00:37:41 +00002187 emitDecl("Tmp" + utostr(ResNo));
2188 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002189 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
2190 "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengbb48e332006-01-12 07:54:57 +00002191 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002192 Record *Op = OperatorMap[N->getName()];
2193 // Transform ExternalSymbol to TargetExternalSymbol
2194 if (Op && Op->getName() == "externalsym") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002195 emitDecl("Tmp" + utostr(ResNo));
2196 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002197 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2198 Val + ")->getSymbol(), MVT::" +
2199 getEnumName(N->getTypeNum(0)) + ");");
2200 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002201 emitDecl("Tmp" + utostr(ResNo));
2202 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002203 }
Evan Chengb915f312005-12-09 22:45:35 +00002204 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002205 Record *Op = OperatorMap[N->getName()];
2206 // Transform GlobalAddress to TargetGlobalAddress
2207 if (Op && Op->getName() == "globaladdr") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002208 emitDecl("Tmp" + utostr(ResNo));
2209 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002210 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2211 ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2212 ");");
2213 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002214 emitDecl("Tmp" + utostr(ResNo));
2215 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002216 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002217 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng21ad3922006-02-07 00:37:41 +00002218 emitDecl("Tmp" + utostr(ResNo));
2219 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengbb48e332006-01-12 07:54:57 +00002220 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002221 emitDecl("Tmp" + utostr(ResNo));
2222 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengb915f312005-12-09 22:45:35 +00002223 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2224 std::string Fn = CP->getSelectFunc();
2225 NumRes = CP->getNumOperands();
Evan Cheng21ad3922006-02-07 00:37:41 +00002226 for (unsigned i = 0; i < NumRes; ++i)
2227 emitDecl("Tmp" + utostr(i+ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002228
Evan Cheng21ad3922006-02-07 00:37:41 +00002229 std::string Code = Fn + "(" + Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002230 for (unsigned i = 0; i < NumRes; i++)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002231 Code += ", Tmp" + utostr(i + ResNo);
2232 emitCheck(Code + ")");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002233
Evan Cheng2216d8a2006-02-05 05:22:18 +00002234 for (unsigned i = 0; i < NumRes; ++i)
Evan Cheng34167212006-02-09 00:37:58 +00002235 emitCode("Select(Tmp" + utostr(i+ResNo) + ", Tmp" +
Evan Cheng2216d8a2006-02-05 05:22:18 +00002236 utostr(i+ResNo) + ");");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002237
Evan Chengb915f312005-12-09 22:45:35 +00002238 TmpNo = ResNo + NumRes;
2239 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002240 emitDecl("Tmp" + utostr(ResNo));
Evan Cheng34167212006-02-09 00:37:58 +00002241 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002242 }
2243 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2244 // value if used multiple times by this pattern result.
2245 Val = "Tmp"+utostr(ResNo);
2246 return std::make_pair(NumRes, ResNo);
2247 }
2248
2249 if (N->isLeaf()) {
2250 // If this is an explicit register reference, handle it.
2251 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2252 unsigned ResNo = TmpNo++;
2253 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002254 emitDecl("Tmp" + utostr(ResNo));
2255 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002256 ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2257 getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002258 return std::make_pair(1, ResNo);
2259 }
2260 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2261 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002262 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng21ad3922006-02-07 00:37:41 +00002263 emitDecl("Tmp" + utostr(ResNo));
2264 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002265 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2266 ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002267 return std::make_pair(1, ResNo);
2268 }
2269
2270 N->dump();
2271 assert(0 && "Unknown leaf type!");
2272 return std::make_pair(1, ~0U);
2273 }
2274
2275 Record *Op = N->getOperator();
2276 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002277 const CodeGenTarget &CGT = ISE.getTargetInfo();
2278 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002279 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002280 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2281 bool HasImpResults = Inst.getNumImpResults() > 0;
Evan Cheng54597732006-01-26 00:22:25 +00002282 bool HasOptInFlag = isRoot &&
2283 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Cheng51fecc82006-01-09 18:27:06 +00002284 bool HasInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002285 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2286 bool NodeHasOutFlag = HasImpResults ||
Evan Cheng51fecc82006-01-09 18:27:06 +00002287 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
Evan Cheng823b7522006-01-19 21:57:10 +00002288 bool NodeHasChain =
2289 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng51fecc82006-01-09 18:27:06 +00002290 bool HasChain = II.hasCtrlDep ||
2291 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
Evan Cheng4fba2812005-12-20 07:37:41 +00002292
Evan Cheng54597732006-01-26 00:22:25 +00002293 if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
Evan Cheng21ad3922006-02-07 00:37:41 +00002294 emitDecl("InFlag");
Evan Cheng54597732006-01-26 00:22:25 +00002295 if (HasOptInFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002296 emitCode("bool HasOptInFlag = false;");
Evan Cheng4fba2812005-12-20 07:37:41 +00002297
Evan Cheng823b7522006-01-19 21:57:10 +00002298 // How many results is this pattern expected to produce?
Evan Chenged66e852006-03-09 08:19:11 +00002299 unsigned PatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +00002300 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2301 MVT::ValueType VT = Pattern->getTypeNum(i);
2302 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Chenged66e852006-03-09 08:19:11 +00002303 PatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +00002304 }
2305
Evan Chengb915f312005-12-09 22:45:35 +00002306 // Determine operand emission order. Complex pattern first.
2307 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2308 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2309 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2310 TreePatternNode *Child = N->getChild(i);
2311 if (i == 0) {
2312 EmitOrder.push_back(std::make_pair(i, Child));
2313 OI = EmitOrder.begin();
2314 } else if (NodeIsComplexPattern(Child)) {
2315 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2316 } else {
2317 EmitOrder.push_back(std::make_pair(i, Child));
2318 }
2319 }
2320
2321 // Emit all of the operands.
2322 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2323 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2324 unsigned OpOrder = EmitOrder[i].first;
2325 TreePatternNode *Child = EmitOrder[i].second;
2326 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2327 NumTemps[OpOrder] = NumTemp;
2328 }
2329
2330 // List all the operands in the right order.
2331 std::vector<unsigned> Ops;
2332 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2333 for (unsigned j = 0; j < NumTemps[i].first; j++)
2334 Ops.push_back(NumTemps[i].second + j);
2335 }
2336
Evan Chengb915f312005-12-09 22:45:35 +00002337 // Emit all the chain and CopyToReg stuff.
Evan Chengb2c6d492006-01-11 22:16:13 +00002338 bool ChainEmitted = HasChain;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002339 if (HasChain)
Evan Cheng34167212006-02-09 00:37:58 +00002340 emitCode("Select(" + ChainName + ", " + ChainName + ");");
Evan Cheng54597732006-01-26 00:22:25 +00002341 if (HasInFlag || HasOptInFlag || HasImpInputs)
2342 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
Evan Chengb915f312005-12-09 22:45:35 +00002343
Evan Chengb915f312005-12-09 22:45:35 +00002344 unsigned NumResults = Inst.getNumResults();
2345 unsigned ResNo = TmpNo++;
2346 if (!isRoot) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002347 emitDecl("Tmp" + utostr(ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002348 std::string Code =
Evan Chengd7805a72006-02-09 07:16:09 +00002349 "Tmp" + utostr(ResNo) + " = SDOperand(CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002350 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002351 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002352 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002353 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002354 Code += ", MVT::Flag";
Evan Chengbcecf332005-12-17 01:19:28 +00002355
Evan Chengb915f312005-12-09 22:45:35 +00002356 unsigned LastOp = 0;
2357 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2358 LastOp = Ops[i];
Chris Lattner8a0604b2006-01-28 20:31:24 +00002359 Code += ", Tmp" + utostr(LastOp);
Evan Chengb915f312005-12-09 22:45:35 +00002360 }
Evan Chengd7805a72006-02-09 07:16:09 +00002361 emitCode(Code + "), 0);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002362 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002363 // Must have at least one result
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002364 emitCode(ChainName + " = Tmp" + utostr(LastOp) + ".getValue(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002365 utostr(NumResults) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002366 }
Evan Cheng54597732006-01-26 00:22:25 +00002367 } else if (HasChain || NodeHasOutFlag) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002368 if (HasOptInFlag) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002369 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
Evan Chengd7805a72006-02-09 07:16:09 +00002370 emitDecl("ResNode", true);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002371 emitCode("if (HasOptInFlag)");
Evan Chengd7805a72006-02-09 07:16:09 +00002372 std::string Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002373 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002374
Evan Cheng9789aaa2006-01-24 20:46:50 +00002375 // Output order: results, chain, flags
2376 // Result types.
2377 if (NumResults > 0) {
2378 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002379 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002380 }
2381 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002382 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002383 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002384 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002385
2386 // Inputs.
2387 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002388 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002389 if (HasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002390 emitCode(Code + ", InFlag);");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002391
Chris Lattner8a0604b2006-01-28 20:31:24 +00002392 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002393 Code = " ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002394 II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002395
2396 // Output order: results, chain, flags
2397 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002398 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2399 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002400 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002401 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002402 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002403 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002404
2405 // Inputs.
2406 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002407 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002408 if (HasChain) Code += ", " + ChainName + ");";
Chris Lattner8a0604b2006-01-28 20:31:24 +00002409 emitCode(Code);
Evan Cheng9789aaa2006-01-24 20:46:50 +00002410 } else {
Evan Chengd7805a72006-02-09 07:16:09 +00002411 emitDecl("ResNode", true);
2412 std::string Code = "ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002413 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002414
2415 // Output order: results, chain, flags
2416 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002417 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2418 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002419 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002420 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002421 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002422 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002423
2424 // Inputs.
2425 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002426 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002427 if (HasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002428 if (HasInFlag || HasImpInputs) Code += ", InFlag";
2429 emitCode(Code + ");");
Evan Chengbcecf332005-12-17 01:19:28 +00002430 }
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002431
Evan Chenged66e852006-03-09 08:19:11 +00002432 if (NewTF)
2433 emitCode("if (OldTF) "
2434 "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2435 ChainName + ".Val, 0);");
2436
2437 for (unsigned i = 0; i < NumResults; i++)
Evan Cheng67212a02006-02-09 22:12:27 +00002438 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002439 utostr(i) + ", ResNode, " + utostr(i) + ");");
Evan Chengf9fc25d2005-12-19 22:40:04 +00002440
Evan Cheng54597732006-01-26 00:22:25 +00002441 if (NodeHasOutFlag)
Evan Chengd7805a72006-02-09 07:16:09 +00002442 emitCode("InFlag = SDOperand(ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002443 utostr(NumResults + (unsigned)HasChain) + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00002444
Chris Lattner8a0604b2006-01-28 20:31:24 +00002445 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
Evan Chenged66e852006-03-09 08:19:11 +00002446 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2447 "0, ResNode, 0);");
2448 NumResults = 1;
Evan Cheng97938882005-12-22 02:24:50 +00002449 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002450
Evan Chenge41bf822006-02-05 06:43:12 +00002451 if (NodeHasChain) {
Evan Cheng67212a02006-02-09 22:12:27 +00002452 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002453 utostr(PatResults) + ", ResNode, " +
2454 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002455 if (DoReplace)
Evan Chenged66e852006-03-09 08:19:11 +00002456 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2457 utostr(PatResults) + ", " + "ResNode, " +
2458 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002459 }
2460
Evan Cheng97938882005-12-22 02:24:50 +00002461 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002462 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002463 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng67212a02006-02-09 22:12:27 +00002464 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2465 FoldedChains[j].first + ".Val, " +
2466 utostr(FoldedChains[j].second) + ", ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002467 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002468
2469 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2470 std::string Code =
Evan Cheng67212a02006-02-09 22:12:27 +00002471 FoldedChains[j].first + ".Val, " +
2472 utostr(FoldedChains[j].second) + ", ";
2473 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002474 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002475 }
Evan Chengb915f312005-12-09 22:45:35 +00002476 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002477
Evan Cheng54597732006-01-26 00:22:25 +00002478 if (NodeHasOutFlag)
Evan Cheng67212a02006-02-09 22:12:27 +00002479 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002480 utostr(PatResults + (unsigned)NodeHasChain) +
2481 ", InFlag.Val, InFlag.ResNo);");
Evan Cheng97938882005-12-22 02:24:50 +00002482
Evan Chenged66e852006-03-09 08:19:11 +00002483 // User does not expect the instruction would produce a chain!
2484 bool AddedChain = HasChain && !NodeHasChain;
Evan Cheng54597732006-01-26 00:22:25 +00002485 if (AddedChain && NodeHasOutFlag) {
Evan Chenged66e852006-03-09 08:19:11 +00002486 if (PatResults == 0) {
Evan Chengd7805a72006-02-09 07:16:09 +00002487 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002488 } else {
Evan Chenged66e852006-03-09 08:19:11 +00002489 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
Evan Chengd7805a72006-02-09 07:16:09 +00002490 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002491 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002492 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002493 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002494 } else {
Evan Chengd7805a72006-02-09 07:16:09 +00002495 emitCode("Result = SDOperand(ResNode, N.ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002496 }
Evan Chengb915f312005-12-09 22:45:35 +00002497 } else {
2498 // If this instruction is the root, and if there is only one use of it,
2499 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002500 emitCode("if (N.Val->hasOneUse()) {");
Evan Cheng34167212006-02-09 00:37:58 +00002501 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002502 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002503 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002504 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002505 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002506 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002507 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002508 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng51fecc82006-01-09 18:27:06 +00002509 if (HasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002510 Code += ", InFlag";
2511 emitCode(Code + ");");
2512 emitCode("} else {");
Evan Chengd7805a72006-02-09 07:16:09 +00002513 emitDecl("ResNode", true);
2514 Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002515 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002516 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002517 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002518 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002519 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002520 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002521 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng51fecc82006-01-09 18:27:06 +00002522 if (HasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002523 Code += ", InFlag";
2524 emitCode(Code + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002525 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2526 "ResNode, 0);");
2527 emitCode(" Result = SDOperand(ResNode, 0);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002528 emitCode("}");
Evan Chengb915f312005-12-09 22:45:35 +00002529 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002530
Evan Cheng34167212006-02-09 00:37:58 +00002531 if (isRoot)
2532 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002533 return std::make_pair(1, ResNo);
2534 } else if (Op->isSubClassOf("SDNodeXForm")) {
2535 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng58e84a62005-12-14 22:02:59 +00002536 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
Evan Chengb915f312005-12-09 22:45:35 +00002537 unsigned ResNo = TmpNo++;
Evan Cheng21ad3922006-02-07 00:37:41 +00002538 emitDecl("Tmp" + utostr(ResNo));
2539 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
Chris Lattner8a0604b2006-01-28 20:31:24 +00002540 + "(Tmp" + utostr(OpVal) + ".Val);");
Evan Chengb915f312005-12-09 22:45:35 +00002541 if (isRoot) {
Evan Cheng67212a02006-02-09 22:12:27 +00002542 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2543 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2544 utostr(ResNo) + ".ResNo);");
Evan Cheng34167212006-02-09 00:37:58 +00002545 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2546 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002547 }
2548 return std::make_pair(1, ResNo);
2549 } else {
2550 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002551 std::cerr << "\n";
2552 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002553 }
2554 }
2555
Chris Lattner488580c2006-01-28 19:06:51 +00002556 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2557 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00002558 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2559 /// for, this returns true otherwise false if Pat has all types.
2560 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2561 const std::string &Prefix) {
2562 // Did we find one?
2563 if (!Pat->hasTypeSet()) {
2564 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002565 Pat->setTypes(Other->getExtTypes());
Chris Lattner67a202b2006-01-28 20:43:52 +00002566 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002567 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002568 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002569 }
2570
Evan Cheng51fecc82006-01-09 18:27:06 +00002571 unsigned OpNo =
2572 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002573 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2574 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2575 Prefix + utostr(OpNo)))
2576 return true;
2577 return false;
2578 }
2579
2580private:
Evan Cheng54597732006-01-26 00:22:25 +00002581 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002582 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00002583 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2584 bool &ChainEmitted, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002585 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002586 unsigned OpNo =
2587 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng54597732006-01-26 00:22:25 +00002588 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2589 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002590 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2591 TreePatternNode *Child = N->getChild(i);
2592 if (!Child->isLeaf()) {
Evan Cheng54597732006-01-26 00:22:25 +00002593 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
Evan Chengb915f312005-12-09 22:45:35 +00002594 } else {
2595 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00002596 if (!Child->getName().empty()) {
2597 std::string Name = RootName + utostr(OpNo);
2598 if (Duplicates.find(Name) != Duplicates.end())
2599 // A duplicate! Do not emit a copy for this node.
2600 continue;
2601 }
2602
Evan Chengb915f312005-12-09 22:45:35 +00002603 Record *RR = DI->getDef();
2604 if (RR->isSubClassOf("Register")) {
2605 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002606 if (RVT == MVT::Flag) {
Evan Cheng34167212006-02-09 00:37:58 +00002607 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
Evan Chengb2c6d492006-01-11 22:16:13 +00002608 } else {
2609 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002610 emitDecl("Chain");
2611 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002612 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00002613 ChainEmitted = true;
2614 }
Evan Cheng34167212006-02-09 00:37:58 +00002615 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2616 RootName + utostr(OpNo) + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002617 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002618 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
Evan Cheng34167212006-02-09 00:37:58 +00002619 ", MVT::" + getEnumName(RVT) + "), " +
Evan Chengd7805a72006-02-09 07:16:09 +00002620 RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng67212a02006-02-09 22:12:27 +00002621 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2622 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00002623 }
2624 }
2625 }
2626 }
2627 }
Evan Cheng54597732006-01-26 00:22:25 +00002628
2629 if (HasInFlag || HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002630 std::string Code;
Evan Cheng54597732006-01-26 00:22:25 +00002631 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002632 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2633 ") {");
2634 Code = " ";
Evan Cheng54597732006-01-26 00:22:25 +00002635 }
Evan Cheng34167212006-02-09 00:37:58 +00002636 emitCode(Code + "Select(InFlag, " + RootName +
2637 ".getOperand(" + utostr(OpNo) + "));");
Evan Cheng54597732006-01-26 00:22:25 +00002638 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002639 emitCode(" HasOptInFlag = true;");
2640 emitCode("}");
Evan Cheng54597732006-01-26 00:22:25 +00002641 }
2642 }
Evan Chengb915f312005-12-09 22:45:35 +00002643 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002644
2645 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002646 /// as specified by the instruction. It returns true if any copy is
2647 /// emitted.
Evan Chengb2c6d492006-01-11 22:16:13 +00002648 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002649 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002650 Record *Op = N->getOperator();
2651 if (Op->isSubClassOf("Instruction")) {
2652 const DAGInstruction &Inst = ISE.getInstruction(Op);
2653 const CodeGenTarget &CGT = ISE.getTargetInfo();
2654 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2655 unsigned NumImpResults = Inst.getNumImpResults();
2656 for (unsigned i = 0; i < NumImpResults; i++) {
2657 Record *RR = Inst.getImpResult(i);
2658 if (RR->isSubClassOf("Register")) {
2659 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2660 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002661 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002662 emitDecl("Chain");
2663 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00002664 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002665 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00002666 }
Evan Chengd7805a72006-02-09 07:16:09 +00002667 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002668 ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
Evan Chengd7805a72006-02-09 07:16:09 +00002669 ", InFlag).Val;");
2670 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2671 emitCode("InFlag = SDOperand(ResNode, 2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002672 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002673 }
2674 }
2675 }
2676 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002677 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002678 }
Evan Chengb915f312005-12-09 22:45:35 +00002679};
2680
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002681/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2682/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00002683/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00002684void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Chenge41bf822006-02-05 06:43:12 +00002685 std::vector<std::pair<bool, std::string> > &GeneratedCode,
Evan Chengd7805a72006-02-09 07:16:09 +00002686 std::set<std::pair<bool, std::string> > &GeneratedDecl,
Evan Chenge41bf822006-02-05 06:43:12 +00002687 bool DoReplace) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002688 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2689 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Cheng21ad3922006-02-07 00:37:41 +00002690 GeneratedCode, GeneratedDecl, DoReplace);
Evan Chengb915f312005-12-09 22:45:35 +00002691
Chris Lattner8fc35682005-09-23 23:16:51 +00002692 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002693 bool FoundChain = false;
Evan Chenge41bf822006-02-05 06:43:12 +00002694 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002695
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002696 // TP - Get *SOME* tree pattern, we don't care which.
2697 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002698
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002699 // At this point, we know that we structurally match the pattern, but the
2700 // types of the nodes may not match. Figure out the fewest number of type
2701 // comparisons we need to emit. For example, if there is only one integer
2702 // type supported by a target, there should be no type comparisons at all for
2703 // integer patterns!
2704 //
2705 // To figure out the fewest number of type checks needed, clone the pattern,
2706 // remove the types, then perform type inference on the pattern as a whole.
2707 // If there are unresolved types, emit an explicit check for those types,
2708 // apply the type to the tree, then rerun type inference. Iterate until all
2709 // types are resolved.
2710 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002711 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002712 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002713
2714 do {
2715 // Resolve/propagate as many types as possible.
2716 try {
2717 bool MadeChange = true;
2718 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00002719 MadeChange = Pat->ApplyTypeConstraints(TP,
2720 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00002721 } catch (...) {
2722 assert(0 && "Error: could not find consistent types for something we"
2723 " already decided was ok!");
2724 abort();
2725 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002726
Chris Lattner7e82f132005-10-15 21:34:21 +00002727 // Insert a check for an unresolved type and add it to the tree. If we find
2728 // an unresolved type to add a check for, this returns true and we iterate,
2729 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002730 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002731
Evan Cheng58e84a62005-12-14 22:02:59 +00002732 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002733 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00002734}
2735
Chris Lattner24e00a42006-01-29 04:41:05 +00002736/// EraseCodeLine - Erase one code line from all of the patterns. If removing
2737/// a line causes any of them to be empty, remove them and return true when
2738/// done.
2739static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
2740 std::vector<std::pair<bool, std::string> > > >
2741 &Patterns) {
2742 bool ErasedPatterns = false;
2743 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2744 Patterns[i].second.pop_back();
2745 if (Patterns[i].second.empty()) {
2746 Patterns.erase(Patterns.begin()+i);
2747 --i; --e;
2748 ErasedPatterns = true;
2749 }
2750 }
2751 return ErasedPatterns;
2752}
2753
Chris Lattner8bc74722006-01-29 04:25:26 +00002754/// EmitPatterns - Emit code for at least one pattern, but try to group common
2755/// code together between the patterns.
2756void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
2757 std::vector<std::pair<bool, std::string> > > >
2758 &Patterns, unsigned Indent,
2759 std::ostream &OS) {
2760 typedef std::pair<bool, std::string> CodeLine;
2761 typedef std::vector<CodeLine> CodeList;
2762 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2763
2764 if (Patterns.empty()) return;
2765
Chris Lattner24e00a42006-01-29 04:41:05 +00002766 // Figure out how many patterns share the next code line. Explicitly copy
2767 // FirstCodeLine so that we don't invalidate a reference when changing
2768 // Patterns.
2769 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00002770 unsigned LastMatch = Patterns.size()-1;
2771 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2772 --LastMatch;
2773
2774 // If not all patterns share this line, split the list into two pieces. The
2775 // first chunk will use this line, the second chunk won't.
2776 if (LastMatch != 0) {
2777 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2778 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2779
2780 // FIXME: Emit braces?
2781 if (Shared.size() == 1) {
2782 PatternToMatch &Pattern = *Shared.back().first;
2783 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2784 Pattern.getSrcPattern()->print(OS);
2785 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2786 Pattern.getDstPattern()->print(OS);
2787 OS << "\n";
2788 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2789 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00002790 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00002791 }
2792 if (!FirstCodeLine.first) {
2793 OS << std::string(Indent, ' ') << "{\n";
2794 Indent += 2;
2795 }
2796 EmitPatterns(Shared, Indent, OS);
2797 if (!FirstCodeLine.first) {
2798 Indent -= 2;
2799 OS << std::string(Indent, ' ') << "}\n";
2800 }
2801
2802 if (Other.size() == 1) {
2803 PatternToMatch &Pattern = *Other.back().first;
2804 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2805 Pattern.getSrcPattern()->print(OS);
2806 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2807 Pattern.getDstPattern()->print(OS);
2808 OS << "\n";
2809 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2810 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00002811 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00002812 }
2813 EmitPatterns(Other, Indent, OS);
2814 return;
2815 }
2816
Chris Lattner24e00a42006-01-29 04:41:05 +00002817 // Remove this code from all of the patterns that share it.
2818 bool ErasedPatterns = EraseCodeLine(Patterns);
2819
Chris Lattner8bc74722006-01-29 04:25:26 +00002820 bool isPredicate = FirstCodeLine.first;
2821
2822 // Otherwise, every pattern in the list has this line. Emit it.
2823 if (!isPredicate) {
2824 // Normal code.
2825 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
2826 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00002827 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
2828
2829 // If the next code line is another predicate, and if all of the pattern
2830 // in this group share the same next line, emit it inline now. Do this
2831 // until we run out of common predicates.
2832 while (!ErasedPatterns && Patterns.back().second.back().first) {
2833 // Check that all of fhe patterns in Patterns end with the same predicate.
2834 bool AllEndWithSamePredicate = true;
2835 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2836 if (Patterns[i].second.back() != Patterns.back().second.back()) {
2837 AllEndWithSamePredicate = false;
2838 break;
2839 }
2840 // If all of the predicates aren't the same, we can't share them.
2841 if (!AllEndWithSamePredicate) break;
2842
2843 // Otherwise we can. Emit it shared now.
2844 OS << " &&\n" << std::string(Indent+4, ' ')
2845 << Patterns.back().second.back().second;
2846 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00002847 }
Chris Lattner24e00a42006-01-29 04:41:05 +00002848
2849 OS << ") {\n";
2850 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00002851 }
2852
2853 EmitPatterns(Patterns, Indent, OS);
2854
2855 if (isPredicate)
2856 OS << std::string(Indent-2, ' ') << "}\n";
2857}
2858
2859
Chris Lattner37481472005-09-26 21:59:35 +00002860
2861namespace {
2862 /// CompareByRecordName - An ordering predicate that implements less-than by
2863 /// comparing the names records.
2864 struct CompareByRecordName {
2865 bool operator()(const Record *LHS, const Record *RHS) const {
2866 // Sort by name first.
2867 if (LHS->getName() < RHS->getName()) return true;
2868 // If both names are equal, sort by pointer.
2869 return LHS->getName() == RHS->getName() && LHS < RHS;
2870 }
2871 };
2872}
2873
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002874void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002875 std::string InstNS = Target.inst_begin()->second.Namespace;
2876 if (!InstNS.empty()) InstNS += "::";
2877
Chris Lattner602f6922006-01-04 00:25:00 +00002878 // Group the patterns by their top-level opcodes.
2879 std::map<Record*, std::vector<PatternToMatch*>,
2880 CompareByRecordName> PatternsByOpcode;
2881 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2882 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2883 if (!Node->isLeaf()) {
2884 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2885 } else {
2886 const ComplexPattern *CP;
2887 if (IntInit *II =
2888 dynamic_cast<IntInit*>(Node->getLeafValue())) {
2889 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2890 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2891 std::vector<Record*> OpNodes = CP->getRootNodes();
2892 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner488580c2006-01-28 19:06:51 +00002893 PatternsByOpcode[OpNodes[j]]
2894 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00002895 }
2896 } else {
2897 std::cerr << "Unrecognized opcode '";
2898 Node->dump();
2899 std::cerr << "' on tree pattern '";
Chris Lattner488580c2006-01-28 19:06:51 +00002900 std::cerr <<
2901 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00002902 std::cerr << "'!\n";
2903 exit(1);
2904 }
2905 }
2906 }
2907
2908 // Emit one Select_* method for each top-level opcode. We do this instead of
2909 // emitting one giant switch statement to support compilers where this will
2910 // result in the recursive functions taking less stack space.
2911 for (std::map<Record*, std::vector<PatternToMatch*>,
2912 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2913 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Evan Chenge41bf822006-02-05 06:43:12 +00002914 const std::string &OpName = PBOI->first->getName();
Evan Cheng34167212006-02-09 00:37:58 +00002915 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
Chris Lattner602f6922006-01-04 00:25:00 +00002916
2917 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Evan Chenge41bf822006-02-05 06:43:12 +00002918 bool OptSlctOrder =
2919 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
2920 OpcodeInfo.getNumResults() > 0);
2921
2922 if (OptSlctOrder) {
Evan Chenge41bf822006-02-05 06:43:12 +00002923 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
2924 << " && N.getValue(0).hasOneUse()) {\n"
2925 << " SDOperand Dummy = "
2926 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00002927 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2928 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
2929 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
2930 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00002931 << " Result = Dummy;\n"
2932 << " return;\n"
Evan Chenge41bf822006-02-05 06:43:12 +00002933 << " }\n";
2934 }
2935
Chris Lattner602f6922006-01-04 00:25:00 +00002936 std::vector<PatternToMatch*> &Patterns = PBOI->second;
Chris Lattner355408b2006-01-29 02:43:35 +00002937 assert(!Patterns.empty() && "No patterns but map has entry?");
Chris Lattner602f6922006-01-04 00:25:00 +00002938
2939 // We want to emit all of the matching code now. However, we want to emit
2940 // the matches in order of minimal cost. Sort the patterns so the least
2941 // cost one is at the start.
2942 std::stable_sort(Patterns.begin(), Patterns.end(),
2943 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00002944
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002945 typedef std::vector<std::pair<bool, std::string> > CodeList;
Evan Cheng21ad3922006-02-07 00:37:41 +00002946 typedef std::set<std::string> DeclSet;
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002947
2948 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
Evan Chengd7805a72006-02-09 07:16:09 +00002949 std::set<std::pair<bool, std::string> > GeneratedDecl;
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002950 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002951 CodeList GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002952 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
2953 OptSlctOrder);
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002954 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
2955 }
2956
2957 // Scan the code to see if all of the patterns are reachable and if it is
2958 // possible that the last one might not match.
2959 bool mightNotMatch = true;
2960 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
2961 CodeList &GeneratedCode = CodeForPatterns[i].second;
2962 mightNotMatch = false;
Chris Lattner355408b2006-01-29 02:43:35 +00002963
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002964 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
2965 if (GeneratedCode[j].first) { // predicate.
2966 mightNotMatch = true;
2967 break;
2968 }
2969 }
Chris Lattner355408b2006-01-29 02:43:35 +00002970
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002971 // If this pattern definitely matches, and if it isn't the last one, the
2972 // patterns after it CANNOT ever match. Error out.
2973 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
2974 std::cerr << "Pattern '";
2975 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
2976 std::cerr << "' is impossible to select!\n";
2977 exit(1);
2978 }
2979 }
Evan Cheng21ad3922006-02-07 00:37:41 +00002980
2981 // Print all declarations.
Evan Chengd7805a72006-02-09 07:16:09 +00002982 for (std::set<std::pair<bool, std::string> >::iterator I = GeneratedDecl.begin(),
Evan Cheng21ad3922006-02-07 00:37:41 +00002983 E = GeneratedDecl.end(); I != E; ++I)
Evan Chengd7805a72006-02-09 07:16:09 +00002984 if (I->first)
2985 OS << " SDNode *" << I->second << ";\n";
2986 else
2987 OS << " SDOperand " << I->second << "(0, 0);\n";
Evan Cheng21ad3922006-02-07 00:37:41 +00002988
Chris Lattner8bc74722006-01-29 04:25:26 +00002989 // Loop through and reverse all of the CodeList vectors, as we will be
2990 // accessing them from their logical front, but accessing the end of a
2991 // vector is more efficient.
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002992 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
2993 CodeList &GeneratedCode = CodeForPatterns[i].second;
Chris Lattner8bc74722006-01-29 04:25:26 +00002994 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002995 }
Chris Lattner602f6922006-01-04 00:25:00 +00002996
Chris Lattner8bc74722006-01-29 04:25:26 +00002997 // Next, reverse the list of patterns itself for the same reason.
2998 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
2999
3000 // Emit all of the patterns now, grouped together to share code.
3001 EmitPatterns(CodeForPatterns, 2, OS);
3002
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003003 // If the last pattern has predicates (which could fail) emit code to catch
3004 // the case where nothing handles a pattern.
Chris Lattner355408b2006-01-29 02:43:35 +00003005 if (mightNotMatch)
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003006 OS << " std::cerr << \"Cannot yet select: \";\n"
3007 << " N.Val->dump(CurDAG);\n"
3008 << " std::cerr << '\\n';\n"
3009 << " abort();\n";
3010
3011 OS << "}\n\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003012 }
3013
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003014 // Emit boilerplate.
Evan Cheng34167212006-02-09 00:37:58 +00003015 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003016 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Evan Cheng34167212006-02-09 00:37:58 +00003017 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003018 << " // Select the flag operand.\n"
3019 << " if (Ops.back().getValueType() == MVT::Flag)\n"
Evan Cheng34167212006-02-09 00:37:58 +00003020 << " Select(Ops.back(), Ops.back());\n"
Chris Lattnerfd105d42006-02-24 02:13:31 +00003021 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003022 << " std::vector<MVT::ValueType> VTs;\n"
3023 << " VTs.push_back(MVT::Other);\n"
3024 << " VTs.push_back(MVT::Flag);\n"
3025 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003026 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3027 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003028 << " Result = New.getValue(N.ResNo);\n"
3029 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003030 << "}\n\n";
3031
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003032 OS << "// The main instruction selector code.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003033 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003034 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003035 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003036 << "INSTRUCTION_LIST_END)) {\n"
3037 << " Result = N;\n"
3038 << " return; // Already selected.\n"
3039 << " }\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003040 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003041 << " if (CGMI != CodeGenMap.end()) {\n"
3042 << " Result = CGMI->second;\n"
3043 << " return;\n"
3044 << " }\n\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003045 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003046 << " default: break;\n"
3047 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003048 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003049 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003050 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003051 << " case ISD::TargetConstant:\n"
3052 << " case ISD::TargetConstantPool:\n"
3053 << " case ISD::TargetFrameIndex:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003054 << " case ISD::TargetGlobalAddress: {\n"
3055 << " Result = N;\n"
3056 << " return;\n"
3057 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003058 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003059 << " case ISD::AssertZext: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003060 << " SDOperand Tmp0;\n"
3061 << " Select(Tmp0, N.getOperand(0));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003062 << " if (!N.Val->hasOneUse())\n"
3063 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3064 << "Tmp0.Val, Tmp0.ResNo);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003065 << " Result = Tmp0;\n"
3066 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003067 << " }\n"
3068 << " case ISD::TokenFactor:\n"
3069 << " if (N.getNumOperands() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003070 << " SDOperand Op0, Op1;\n"
3071 << " Select(Op0, N.getOperand(0));\n"
3072 << " Select(Op1, N.getOperand(1));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003073 << " Result = \n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003074 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003075 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3076 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003077 << " } else {\n"
3078 << " std::vector<SDOperand> Ops;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003079 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3080 << " SDOperand Val;\n"
3081 << " Select(Val, N.getOperand(i));\n"
3082 << " Ops.push_back(Val);\n"
3083 << " }\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003084 << " Result = \n"
3085 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3086 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3087 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003088 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003089 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003090 << " case ISD::CopyFromReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003091 << " SDOperand Chain;\n"
3092 << " Select(Chain, N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003093 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3094 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003095 << " if (N.Val->getNumValues() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003096 << " if (Chain == N.getOperand(0)) {\n"
3097 << " Result = N; // No change\n"
3098 << " return;\n"
3099 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003100 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003101 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3102 << "New.Val, 0);\n"
3103 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3104 << "New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003105 << " Result = New.getValue(N.ResNo);\n"
3106 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003107 << " } else {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003108 << " SDOperand Flag;\n"
3109 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003110 << " if (Chain == N.getOperand(0) &&\n"
Evan Cheng34167212006-02-09 00:37:58 +00003111 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3112 << " Result = N; // No change\n"
3113 << " return;\n"
3114 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003115 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003116 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3117 << "New.Val, 0);\n"
3118 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3119 << "New.Val, 1);\n"
3120 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3121 << "New.Val, 2);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003122 << " Result = New.getValue(N.ResNo);\n"
3123 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003124 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003125 << " }\n"
3126 << " case ISD::CopyToReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003127 << " SDOperand Chain;\n"
3128 << " Select(Chain, N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003129 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Evan Cheng34167212006-02-09 00:37:58 +00003130 << " SDOperand Val;\n"
3131 << " Select(Val, N.getOperand(2));\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003132 << " Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003133 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003134 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003135 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003136 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3137 << "Result.Val, 0);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003138 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00003139 << " SDOperand Flag(0, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003140 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003141 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003142 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003143 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003144 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3145 << "Result.Val, 0);\n"
3146 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3147 << "Result.Val, 1);\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003148 << " Result = Result.getValue(N.ResNo);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003149 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003150 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003151 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003152 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003153
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003154
Chris Lattner602f6922006-01-04 00:25:00 +00003155 // Loop over all of the case statements, emiting a call to each method we
3156 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00003157 for (std::map<Record*, std::vector<PatternToMatch*>,
3158 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3159 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00003160 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00003161 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00003162 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Evan Cheng34167212006-02-09 00:37:58 +00003163 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
Chris Lattner81303322005-09-23 19:36:15 +00003164 }
Chris Lattner81303322005-09-23 19:36:15 +00003165
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003166 OS << " } // end of big switch.\n\n"
3167 << " std::cerr << \"Cannot yet select: \";\n"
Evan Cheng97938882005-12-22 02:24:50 +00003168 << " N.Val->dump(CurDAG);\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003169 << " std::cerr << '\\n';\n"
3170 << " abort();\n"
3171 << "}\n";
3172}
3173
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003174void DAGISelEmitter::run(std::ostream &OS) {
3175 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3176 " target", OS);
3177
Chris Lattner1f39e292005-09-14 00:09:24 +00003178 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3179 << "// *** instruction selector class. These functions are really "
3180 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003181
Chris Lattner296dfe32005-09-24 00:50:51 +00003182 OS << "// Instance var to keep track of multiply used nodes that have \n"
3183 << "// already been selected.\n"
3184 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003185
3186 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003187 << "// and their place handle nodes.\n";
3188 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3189 OS << "// Instance var to keep track of mapping of place handle nodes\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003190 << "// and their replacement nodes.\n";
3191 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3192
3193 OS << "\n";
3194 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3195 << "std::set<SDNode *> &Visited) {\n";
3196 OS << " if (found || !Visited.insert(Use).second) return;\n";
3197 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3198 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3199 OS << " if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3200 OS << " if (N != Def) {\n";
3201 OS << " findNonImmUse(N, Def, found, Visited);\n";
3202 OS << " } else {\n";
3203 OS << " found = true;\n";
3204 OS << " break;\n";
3205 OS << " }\n";
3206 OS << " }\n";
3207 OS << " }\n";
3208 OS << "}\n";
3209
3210 OS << "\n";
3211 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3212 OS << " std::set<SDNode *> Visited;\n";
3213 OS << " bool found = false;\n";
3214 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3215 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3216 OS << " if (N != Def) {\n";
3217 OS << " findNonImmUse(N, Def, found, Visited);\n";
3218 OS << " if (found) break;\n";
3219 OS << " }\n";
3220 OS << " }\n";
3221 OS << " return found;\n";
3222 OS << "}\n";
3223
3224 OS << "\n";
Evan Cheng024524f2006-02-06 06:03:35 +00003225 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003226 << "// handle node in ReplaceMap.\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003227 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3228 << "unsigned RNum) {\n";
3229 OS << " SDOperand N(H, HNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003230 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3231 OS << " if (HMI != HandleMap.end()) {\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003232 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003233 OS << " HandleMap.erase(N);\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003234 OS << " }\n";
3235 OS << "}\n";
3236
3237 OS << "\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003238 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3239 OS << "// handles.Some handles do not yet have replacements because the\n";
3240 OS << "// nodes they replacements have only dead readers.\n";
3241 OS << "void SelectDanglingHandles() {\n";
3242 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3243 << "HandleMap.begin(),\n"
3244 << " E = HandleMap.end(); I != E; ++I) {\n";
3245 OS << " SDOperand N = I->first;\n";
Evan Cheng34167212006-02-09 00:37:58 +00003246 OS << " SDOperand R;\n";
3247 OS << " Select(R, N.getValue(0));\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003248 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003249 OS << " }\n";
3250 OS << "}\n";
3251 OS << "\n";
3252 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003253 OS << "// specific nodes.\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003254 OS << "void ReplaceHandles() {\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003255 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3256 << "ReplaceMap.begin(),\n"
3257 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3258 OS << " SDOperand From = I->first;\n";
3259 OS << " SDOperand To = I->second;\n";
3260 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3261 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3262 OS << " SDNode *Use = *UI;\n";
3263 OS << " std::vector<SDOperand> Ops;\n";
3264 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3265 OS << " SDOperand O = Use->getOperand(i);\n";
3266 OS << " if (O.Val == From.Val)\n";
3267 OS << " Ops.push_back(To);\n";
3268 OS << " else\n";
3269 OS << " Ops.push_back(O);\n";
3270 OS << " }\n";
3271 OS << " SDOperand U = SDOperand(Use, 0);\n";
3272 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3273 OS << " }\n";
3274 OS << " }\n";
3275 OS << "}\n";
3276
3277 OS << "\n";
Evan Chenged66e852006-03-09 08:19:11 +00003278 OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3279 OS << "// if the folding were to happen. This is called when, for example,\n";
3280 OS << "// a load is folded into a store. If the store's chain is the load,\n";
3281 OS << "// then the resulting node's input chain would be the load's input\n";
3282 OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3283 OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3284 OS << "// with the other operands along with the input chain of the load.\n";
3285 OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3286 << "SDNode *Chain, SDNode* &OldTF) {\n";
3287 OS << " OldTF = NULL;\n";
3288 OS << " if (N == Chain) {\n";
3289 OS << " return N->getOperand(0);\n";
3290 OS << " } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3291 OS << " N->isOperand(Chain)) {\n";
3292 OS << " SDOperand Ch = SDOperand(Chain, 0);\n";
3293 OS << " std::map<SDOperand, SDOperand>::iterator CGMI = "
3294 << "CodeGenMap.find(Ch);\n";
3295 OS << " if (CGMI != CodeGenMap.end())\n";
3296 OS << " return SDOperand(0, 0);\n";
3297 OS << " OldTF = Chain;\n";
3298 OS << " std::vector<SDOperand> Ops;\n";
3299 OS << " for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3300 OS << " SDOperand Op = Chain->getOperand(i);\n";
3301 OS << " if (Op.Val == N)\n";
3302 OS << " Ops.push_back(N->getOperand(0));\n";
3303 OS << " else\n";
3304 OS << " Ops.push_back(Op);\n";
3305 OS << " }\n";
3306 OS << " return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3307 OS << " }\n";
3308 OS << " return SDOperand(0, 0);\n";
3309 OS << "}\n";
3310
3311 OS << "\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003312 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3313 OS << "SDOperand SelectRoot(SDOperand N) {\n";
Evan Cheng34167212006-02-09 00:37:58 +00003314 OS << " SDOperand ResNode;\n";
3315 OS << " Select(ResNode, N);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003316 OS << " SelectDanglingHandles();\n";
3317 OS << " ReplaceHandles();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003318 OS << " ReplaceMap.clear();\n";
Evan Cheng34167212006-02-09 00:37:58 +00003319 OS << " return ResNode;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003320 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003321
Chris Lattnerca559d02005-09-08 21:03:01 +00003322 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003323 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003324 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003325 ParsePatternFragments(OS);
3326 ParseInstructions();
3327 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003328
Chris Lattnere97603f2005-09-28 19:27:25 +00003329 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003330 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003331 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003332
Chris Lattnere46e17b2005-09-29 19:28:10 +00003333
3334 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3335 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003336 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3337 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00003338 std::cerr << "\n";
3339 });
3340
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003341 // At this point, we have full information about the 'Patterns' we need to
3342 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003343 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003344 EmitInstructionSelector(OS);
3345
3346 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3347 E = PatternFragments.end(); I != E; ++I)
3348 delete I->second;
3349 PatternFragments.clear();
3350
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003351 Instructions.clear();
3352}