blob: 21e5ed393dda09379d4101e46afecdbdf50ec153 [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.
66static bool isExtIntegerInVTs(std::vector<unsigned char> EVTs) {
67 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.
73static bool isExtFloatingPointInVTs(std::vector<unsigned char> EVTs) {
74 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
75 return EVTs[0] == MVT::isFP || !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
Chris Lattner3c7e18d2005-10-14 06:12:03 +000076}
77
78//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000079// SDTypeConstraint implementation
80//
81
82SDTypeConstraint::SDTypeConstraint(Record *R) {
83 OperandNo = R->getValueAsInt("OperandNum");
84
85 if (R->isSubClassOf("SDTCisVT")) {
86 ConstraintType = SDTCisVT;
87 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattner5b21be72005-12-09 22:57:42 +000088 } else if (R->isSubClassOf("SDTCisPtrTy")) {
89 ConstraintType = SDTCisPtrTy;
Chris Lattner33c92e92005-09-08 21:27:15 +000090 } else if (R->isSubClassOf("SDTCisInt")) {
91 ConstraintType = SDTCisInt;
92 } else if (R->isSubClassOf("SDTCisFP")) {
93 ConstraintType = SDTCisFP;
94 } else if (R->isSubClassOf("SDTCisSameAs")) {
95 ConstraintType = SDTCisSameAs;
96 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
97 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
98 ConstraintType = SDTCisVTSmallerThanOp;
99 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
100 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +0000101 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
102 ConstraintType = SDTCisOpSmallerThanOp;
103 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
104 R->getValueAsInt("BigOperandNum");
Chris Lattner33c92e92005-09-08 21:27:15 +0000105 } else {
106 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
107 exit(1);
108 }
109}
110
Chris Lattner32707602005-09-08 23:22:48 +0000111/// getOperandNum - Return the node corresponding to operand #OpNo in tree
112/// N, which has NumResults results.
113TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
114 TreePatternNode *N,
115 unsigned NumResults) const {
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000116 assert(NumResults <= 1 &&
117 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000118
119 if (OpNo < NumResults)
120 return N; // FIXME: need value #
121 else
122 return N->getChild(OpNo-NumResults);
123}
124
125/// ApplyTypeConstraint - Given a node in a pattern, apply this type
126/// constraint to the nodes operands. This returns true if it makes a
127/// change, false otherwise. If a type contradiction is found, throw an
128/// exception.
129bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
130 const SDNodeInfo &NodeInfo,
131 TreePattern &TP) const {
132 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000133 assert(NumResults <= 1 &&
134 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000135
136 // Check that the number of operands is sane.
137 if (NodeInfo.getNumOperands() >= 0) {
138 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
139 TP.error(N->getOperator()->getName() + " node requires exactly " +
140 itostr(NodeInfo.getNumOperands()) + " operands!");
141 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000142
143 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000144
145 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
146
147 switch (ConstraintType) {
148 default: assert(0 && "Unknown constraint type!");
149 case SDTCisVT:
150 // Operand must be a particular type.
151 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000152 case SDTCisPtrTy: {
153 // Operand must be same as target pointer type.
154 return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
155 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000156 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000157 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000158 std::vector<MVT::ValueType> IntVTs =
159 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000160
161 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000162 if (IntVTs.size() == 1)
163 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000164 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000165 }
166 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000167 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000168 std::vector<MVT::ValueType> FPVTs =
169 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000170
171 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000172 if (FPVTs.size() == 1)
173 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000174 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000175 }
Chris Lattner32707602005-09-08 23:22:48 +0000176 case SDTCisSameAs: {
177 TreePatternNode *OtherNode =
178 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Nate Begemanb73628b2005-12-30 00:12:56 +0000179 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
180 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000181 }
182 case SDTCisVTSmallerThanOp: {
183 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
184 // have an integer type that is smaller than the VT.
185 if (!NodeToApply->isLeaf() ||
186 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
187 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
188 ->isSubClassOf("ValueType"))
189 TP.error(N->getOperator()->getName() + " expects a VT operand!");
190 MVT::ValueType VT =
191 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
192 if (!MVT::isInteger(VT))
193 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
194
195 TreePatternNode *OtherNode =
196 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000197
198 // It must be integer.
199 bool MadeChange = false;
200 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
201
Nate Begemanb73628b2005-12-30 00:12:56 +0000202 // This code only handles nodes that have one type set. Assert here so
203 // that we can change this if we ever need to deal with multiple value
204 // types at this point.
205 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
206 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000207 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
208 return false;
209 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000210 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000211 TreePatternNode *BigOperand =
212 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
213
214 // Both operands must be integer or FP, but we don't care which.
215 bool MadeChange = false;
216
Nate Begemanb73628b2005-12-30 00:12:56 +0000217 // This code does not currently handle nodes which have multiple types,
218 // where some types are integer, and some are fp. Assert that this is not
219 // the case.
220 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
221 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
222 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
223 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
224 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
225 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000226 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000227 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000228 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000229 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000230 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000231 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000232 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
233
234 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
235
Nate Begemanb73628b2005-12-30 00:12:56 +0000236 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000237 VTs = FilterVTs(VTs, MVT::isInteger);
Nate Begemanb73628b2005-12-30 00:12:56 +0000238 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000239 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
240 } else {
241 VTs.clear();
242 }
243
244 switch (VTs.size()) {
245 default: // Too many VT's to pick from.
246 case 0: break; // No info yet.
247 case 1:
248 // Only one VT of this flavor. Cannot ever satisify the constraints.
249 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
250 case 2:
251 // If we have exactly two possible types, the little operand must be the
252 // small one, the big operand should be the big one. Common with
253 // float/double for example.
254 assert(VTs[0] < VTs[1] && "Should be sorted!");
255 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
256 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
257 break;
258 }
259 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000260 }
Chris Lattner32707602005-09-08 23:22:48 +0000261 }
262 return false;
263}
264
265
Chris Lattner33c92e92005-09-08 21:27:15 +0000266//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000267// SDNodeInfo implementation
268//
269SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
270 EnumName = R->getValueAsString("Opcode");
271 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000272 Record *TypeProfile = R->getValueAsDef("TypeProfile");
273 NumResults = TypeProfile->getValueAsInt("NumResults");
274 NumOperands = TypeProfile->getValueAsInt("NumOperands");
275
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000276 // Parse the properties.
277 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000278 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000279 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
280 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000281 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000282 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000283 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000284 } else if (PropList[i]->getName() == "SDNPHasChain") {
285 Properties |= 1 << SDNPHasChain;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000286 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000287 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000288 << "' on node '" << R->getName() << "'!\n";
289 exit(1);
290 }
291 }
292
293
Chris Lattner33c92e92005-09-08 21:27:15 +0000294 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000295 std::vector<Record*> ConstraintList =
296 TypeProfile->getValueAsListOfDefs("Constraints");
297 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000298}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000299
300//===----------------------------------------------------------------------===//
301// TreePatternNode implementation
302//
303
304TreePatternNode::~TreePatternNode() {
305#if 0 // FIXME: implement refcounted tree nodes!
306 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
307 delete getChild(i);
308#endif
309}
310
Chris Lattner32707602005-09-08 23:22:48 +0000311/// UpdateNodeType - Set the node type of N to VT if VT contains
312/// information. If N already contains a conflicting type, then throw an
313/// exception. This returns true if any information was updated.
314///
Nate Begemanb73628b2005-12-30 00:12:56 +0000315bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
316 TreePattern &TP) {
317 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
318
319 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
320 return false;
321 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
322 setTypes(ExtVTs);
Chris Lattner32707602005-09-08 23:22:48 +0000323 return true;
324 }
325
Nate Begemanb73628b2005-12-30 00:12:56 +0000326 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
327 assert(hasTypeSet() && "should be handled above!");
328 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
329 if (getExtTypes() == FVTs)
330 return false;
331 setTypes(FVTs);
332 return true;
333 }
334 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
335 assert(hasTypeSet() && "should be handled above!");
336 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
337 if (getExtTypes() == FVTs)
338 return false;
339 setTypes(FVTs);
340 return true;
341 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000342
343 // If we know this is an int or fp type, and we are told it is a specific one,
344 // take the advice.
Nate Begemanb73628b2005-12-30 00:12:56 +0000345 //
346 // Similarly, we should probably set the type here to the intersection of
347 // {isInt|isFP} and ExtVTs
348 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
349 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
350 setTypes(ExtVTs);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000351 return true;
352 }
353
Chris Lattner1531f202005-10-26 16:59:37 +0000354 if (isLeaf()) {
355 dump();
Evan Chengbcecf332005-12-17 01:19:28 +0000356 std::cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000357 TP.error("Type inference contradiction found in node!");
358 } else {
359 TP.error("Type inference contradiction found in node " +
360 getOperator()->getName() + "!");
361 }
Chris Lattner32707602005-09-08 23:22:48 +0000362 return true; // unreachable
363}
364
365
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000366void TreePatternNode::print(std::ostream &OS) const {
367 if (isLeaf()) {
368 OS << *getLeafValue();
369 } else {
370 OS << "(" << getOperator()->getName();
371 }
372
Nate Begemanb73628b2005-12-30 00:12:56 +0000373 // FIXME: At some point we should handle printing all the value types for
374 // nodes that are multiply typed.
375 switch (getExtTypeNum(0)) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000376 case MVT::Other: OS << ":Other"; break;
377 case MVT::isInt: OS << ":isInt"; break;
378 case MVT::isFP : OS << ":isFP"; break;
379 case MVT::isUnknown: ; /*OS << ":?";*/ break;
Nate Begemanb73628b2005-12-30 00:12:56 +0000380 default: OS << ":" << getTypeNum(0); break;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000381 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000382
383 if (!isLeaf()) {
384 if (getNumChildren() != 0) {
385 OS << " ";
386 getChild(0)->print(OS);
387 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
388 OS << ", ";
389 getChild(i)->print(OS);
390 }
391 }
392 OS << ")";
393 }
394
395 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000396 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000397 if (TransformFn)
398 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000399 if (!getName().empty())
400 OS << ":$" << getName();
401
402}
403void TreePatternNode::dump() const {
404 print(std::cerr);
405}
406
Chris Lattnere46e17b2005-09-29 19:28:10 +0000407/// isIsomorphicTo - Return true if this node is recursively isomorphic to
408/// the specified node. For this comparison, all of the state of the node
409/// is considered, except for the assigned name. Nodes with differing names
410/// that are otherwise identical are considered isomorphic.
411bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
412 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000413 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000414 getPredicateFn() != N->getPredicateFn() ||
415 getTransformFn() != N->getTransformFn())
416 return false;
417
418 if (isLeaf()) {
419 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
420 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
421 return DI->getDef() == NDI->getDef();
422 return getLeafValue() == N->getLeafValue();
423 }
424
425 if (N->getOperator() != getOperator() ||
426 N->getNumChildren() != getNumChildren()) return false;
427 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
428 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
429 return false;
430 return true;
431}
432
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000433/// clone - Make a copy of this tree and all of its children.
434///
435TreePatternNode *TreePatternNode::clone() const {
436 TreePatternNode *New;
437 if (isLeaf()) {
438 New = new TreePatternNode(getLeafValue());
439 } else {
440 std::vector<TreePatternNode*> CChildren;
441 CChildren.reserve(Children.size());
442 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
443 CChildren.push_back(getChild(i)->clone());
444 New = new TreePatternNode(getOperator(), CChildren);
445 }
446 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000447 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000448 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000449 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000450 return New;
451}
452
Chris Lattner32707602005-09-08 23:22:48 +0000453/// SubstituteFormalArguments - Replace the formal arguments in this tree
454/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000455void TreePatternNode::
456SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
457 if (isLeaf()) return;
458
459 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
460 TreePatternNode *Child = getChild(i);
461 if (Child->isLeaf()) {
462 Init *Val = Child->getLeafValue();
463 if (dynamic_cast<DefInit*>(Val) &&
464 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
465 // We found a use of a formal argument, replace it with its value.
466 Child = ArgMap[Child->getName()];
467 assert(Child && "Couldn't find formal argument!");
468 setChild(i, Child);
469 }
470 } else {
471 getChild(i)->SubstituteFormalArguments(ArgMap);
472 }
473 }
474}
475
476
477/// InlinePatternFragments - If this pattern refers to any pattern
478/// fragments, inline them into place, giving us a pattern without any
479/// PatFrag references.
480TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
481 if (isLeaf()) return this; // nothing to do.
482 Record *Op = getOperator();
483
484 if (!Op->isSubClassOf("PatFrag")) {
485 // Just recursively inline children nodes.
486 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
487 setChild(i, getChild(i)->InlinePatternFragments(TP));
488 return this;
489 }
490
491 // Otherwise, we found a reference to a fragment. First, look up its
492 // TreePattern record.
493 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
494
495 // Verify that we are passing the right number of operands.
496 if (Frag->getNumArgs() != Children.size())
497 TP.error("'" + Op->getName() + "' fragment requires " +
498 utostr(Frag->getNumArgs()) + " operands!");
499
Chris Lattner37937092005-09-09 01:15:01 +0000500 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000501
502 // Resolve formal arguments to their actual value.
503 if (Frag->getNumArgs()) {
504 // Compute the map of formal to actual arguments.
505 std::map<std::string, TreePatternNode*> ArgMap;
506 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
507 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
508
509 FragTree->SubstituteFormalArguments(ArgMap);
510 }
511
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000512 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000513 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000514
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000515 // Get a new copy of this fragment to stitch into here.
516 //delete this; // FIXME: implement refcounting!
517 return FragTree;
518}
519
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000520/// getIntrinsicType - Check to see if the specified record has an intrinsic
521/// type which should be applied to it. This infer the type of register
522/// references from the register file information, for example.
523///
Nate Begemanb73628b2005-12-30 00:12:56 +0000524static std::vector<unsigned char> getIntrinsicType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000525 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000526 // Some common return values
527 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
528 std::vector<unsigned char> Other(1, MVT::Other);
529
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000530 // Check to see if this is a register or a register class...
531 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000532 if (NotRegisters)
533 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000534 const CodeGenRegisterClass &RC =
535 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000536 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000537 } else if (R->isSubClassOf("PatFrag")) {
538 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000539 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000540 } else if (R->isSubClassOf("Register")) {
Chris Lattner22faeab2005-12-05 02:36:37 +0000541 // If the register appears in exactly one regclass, and the regclass has one
542 // value type, use it as the known type.
543 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
544 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
Nate Begemanb73628b2005-12-30 00:12:56 +0000545 return ConvertVTs(RC->getValueTypes());
546 return Unknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000547 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
548 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000549 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000550 } else if (R->isSubClassOf("ComplexPattern")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000551 std::vector<unsigned char>
552 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
553 return ComplexPat;
Evan Cheng01f318b2005-12-14 02:21:57 +0000554 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000555 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000556 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000557 }
558
559 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000560 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000561}
562
Chris Lattner32707602005-09-08 23:22:48 +0000563/// ApplyTypeConstraints - Apply all of the type constraints relevent to
564/// this node and its children in the tree. This returns true if it makes a
565/// change, false otherwise. If a type contradiction is found, throw an
566/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000567bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
568 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000569 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000570 // If it's a regclass or something else known, include the type.
571 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
572 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000573 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
574 // Int inits are always integers. :)
575 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
576
577 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000578 // At some point, it may make sense for this tree pattern to have
579 // multiple types. Assert here that it does not, so we revisit this
580 // code when appropriate.
581 assert(getExtTypes().size() == 1 && "TreePattern has too many types!");
582
583 unsigned Size = MVT::getSizeInBits(getTypeNum(0));
Chris Lattner465c7372005-11-03 05:46:11 +0000584 // Make sure that the value is representable for this type.
585 if (Size < 32) {
586 int Val = (II->getValue() << (32-Size)) >> (32-Size);
587 if (Val != II->getValue())
588 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
589 "' is out of range for type 'MVT::" +
Nate Begemanb73628b2005-12-30 00:12:56 +0000590 getEnumName(getTypeNum(0)) + "'!");
Chris Lattner465c7372005-11-03 05:46:11 +0000591 }
592 }
593
594 return MadeChange;
595 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000596 return false;
597 }
Chris Lattner32707602005-09-08 23:22:48 +0000598
599 // special handling for set, which isn't really an SDNode.
600 if (getOperator()->getName() == "set") {
601 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000602 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
603 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000604
605 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000606 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
607 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000608 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
609 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000610 } else if (getOperator()->isSubClassOf("SDNode")) {
611 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
612
613 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
614 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000615 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000616 // Branch, etc. do not produce results and top-level forms in instr pattern
617 // must have void types.
618 if (NI.getNumResults() == 0)
619 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000620 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000621 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000622 const DAGInstruction &Inst =
623 TP.getDAGISelEmitter().getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000624 bool MadeChange = false;
625 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000626
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000627 assert(NumResults <= 1 &&
628 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000629 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000630 if (NumResults == 0) {
631 MadeChange = UpdateNodeType(MVT::isVoid, TP);
632 } else {
633 Record *ResultNode = Inst.getResult(0);
634 assert(ResultNode->isSubClassOf("RegisterClass") &&
635 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000636
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000637 const CodeGenRegisterClass &RC =
638 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000639 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000640 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000641
642 if (getNumChildren() != Inst.getNumOperands())
643 TP.error("Instruction '" + getOperator()->getName() + " expects " +
644 utostr(Inst.getNumOperands()) + " operands, not " +
645 utostr(getNumChildren()) + " operands!");
646 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000647 Record *OperandNode = Inst.getOperand(i);
648 MVT::ValueType VT;
649 if (OperandNode->isSubClassOf("RegisterClass")) {
650 const CodeGenRegisterClass &RC =
651 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000652 //VT = RC.getValueTypeNum(0);
653 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
654 TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000655 } else if (OperandNode->isSubClassOf("Operand")) {
656 VT = getValueType(OperandNode->getValueAsDef("Type"));
Nate Begemanb73628b2005-12-30 00:12:56 +0000657 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000658 } else {
659 assert(0 && "Unknown operand type!");
660 abort();
661 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000662 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000663 }
664 return MadeChange;
665 } else {
666 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
667
668 // Node transforms always take one operand, and take and return the same
669 // type.
670 if (getNumChildren() != 1)
671 TP.error("Node transform '" + getOperator()->getName() +
672 "' requires one operand!");
Nate Begemanb73628b2005-12-30 00:12:56 +0000673 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
674 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000675 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000676 }
Chris Lattner32707602005-09-08 23:22:48 +0000677}
678
Chris Lattnere97603f2005-09-28 19:27:25 +0000679/// canPatternMatch - If it is impossible for this pattern to match on this
680/// target, fill in Reason and return false. Otherwise, return true. This is
681/// used as a santity check for .td files (to prevent people from writing stuff
682/// that can never possibly work), and to prevent the pattern permuter from
683/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000684bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000685 if (isLeaf()) return true;
686
687 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
688 if (!getChild(i)->canPatternMatch(Reason, ISE))
689 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000690
Chris Lattnere97603f2005-09-28 19:27:25 +0000691 // If this node is a commutative operator, check that the LHS isn't an
692 // immediate.
693 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
694 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
695 // Scan all of the operands of the node and make sure that only the last one
696 // is a constant node.
697 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
698 if (!getChild(i)->isLeaf() &&
699 getChild(i)->getOperator()->getName() == "imm") {
700 Reason = "Immediate value must be on the RHS of commutative operators!";
701 return false;
702 }
703 }
704
705 return true;
706}
Chris Lattner32707602005-09-08 23:22:48 +0000707
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000708//===----------------------------------------------------------------------===//
709// TreePattern implementation
710//
711
Chris Lattneredbd8712005-10-21 01:19:59 +0000712TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000713 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000714 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000715 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
716 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000717}
718
Chris Lattneredbd8712005-10-21 01:19:59 +0000719TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000720 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000721 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000722 Trees.push_back(ParseTreePattern(Pat));
723}
724
Chris Lattneredbd8712005-10-21 01:19:59 +0000725TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000726 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000727 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000728 Trees.push_back(Pat);
729}
730
731
732
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000733void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000734 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000735 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000736}
737
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000738TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
739 Record *Operator = Dag->getNodeType();
740
741 if (Operator->isSubClassOf("ValueType")) {
742 // If the operator is a ValueType, then this must be "type cast" of a leaf
743 // node.
744 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000745 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000746
747 Init *Arg = Dag->getArg(0);
748 TreePatternNode *New;
749 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000750 Record *R = DI->getDef();
751 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
752 Dag->setArg(0, new DagInit(R,
753 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000754 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000755 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000756 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000757 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
758 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000759 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
760 New = new TreePatternNode(II);
761 if (!Dag->getArgName(0).empty())
762 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000763 } else {
764 Arg->dump();
765 error("Unknown leaf value for tree pattern!");
766 return 0;
767 }
768
Chris Lattner32707602005-09-08 23:22:48 +0000769 // Apply the type cast.
770 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000771 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000772 return New;
773 }
774
775 // Verify that this is something that makes sense for an operator.
776 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000777 !Operator->isSubClassOf("Instruction") &&
778 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000779 Operator->getName() != "set")
780 error("Unrecognized node '" + Operator->getName() + "'!");
781
Chris Lattneredbd8712005-10-21 01:19:59 +0000782 // Check to see if this is something that is illegal in an input pattern.
783 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
784 Operator->isSubClassOf("SDNodeXForm")))
785 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
786
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000787 std::vector<TreePatternNode*> Children;
788
789 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
790 Init *Arg = Dag->getArg(i);
791 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
792 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000793 if (Children.back()->getName().empty())
794 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000795 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
796 Record *R = DefI->getDef();
797 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
798 // TreePatternNode if its own.
799 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
800 Dag->setArg(i, new DagInit(R,
801 std::vector<std::pair<Init*, std::string> >()));
802 --i; // Revisit this node...
803 } else {
804 TreePatternNode *Node = new TreePatternNode(DefI);
805 Node->setName(Dag->getArgName(i));
806 Children.push_back(Node);
807
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000808 // Input argument?
809 if (R->getName() == "node") {
810 if (Dag->getArgName(i).empty())
811 error("'node' argument requires a name to match with operand list");
812 Args.push_back(Dag->getArgName(i));
813 }
814 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000815 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
816 TreePatternNode *Node = new TreePatternNode(II);
817 if (!Dag->getArgName(i).empty())
818 error("Constant int argument should not have a name!");
819 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000820 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000821 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000822 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000823 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000824 error("Unknown leaf value for tree pattern!");
825 }
826 }
827
828 return new TreePatternNode(Operator, Children);
829}
830
Chris Lattner32707602005-09-08 23:22:48 +0000831/// InferAllTypes - Infer/propagate as many types throughout the expression
832/// patterns as possible. Return true if all types are infered, false
833/// otherwise. Throw an exception if a type contradiction is found.
834bool TreePattern::InferAllTypes() {
835 bool MadeChange = true;
836 while (MadeChange) {
837 MadeChange = false;
838 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000839 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000840 }
841
842 bool HasUnresolvedTypes = false;
843 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
844 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
845 return !HasUnresolvedTypes;
846}
847
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000848void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000849 OS << getRecord()->getName();
850 if (!Args.empty()) {
851 OS << "(" << Args[0];
852 for (unsigned i = 1, e = Args.size(); i != e; ++i)
853 OS << ", " << Args[i];
854 OS << ")";
855 }
856 OS << ": ";
857
858 if (Trees.size() > 1)
859 OS << "[\n";
860 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
861 OS << "\t";
862 Trees[i]->print(OS);
863 OS << "\n";
864 }
865
866 if (Trees.size() > 1)
867 OS << "]\n";
868}
869
870void TreePattern::dump() const { print(std::cerr); }
871
872
873
874//===----------------------------------------------------------------------===//
875// DAGISelEmitter implementation
876//
877
Chris Lattnerca559d02005-09-08 21:03:01 +0000878// Parse all of the SDNode definitions for the target, populating SDNodes.
879void DAGISelEmitter::ParseNodeInfo() {
880 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
881 while (!Nodes.empty()) {
882 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
883 Nodes.pop_back();
884 }
885}
886
Chris Lattner24eeeb82005-09-13 21:51:00 +0000887/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
888/// map, and emit them to the file as functions.
889void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
890 OS << "\n// Node transformations.\n";
891 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
892 while (!Xforms.empty()) {
893 Record *XFormNode = Xforms.back();
894 Record *SDNode = XFormNode->getValueAsDef("Opcode");
895 std::string Code = XFormNode->getValueAsCode("XFormFunction");
896 SDNodeXForms.insert(std::make_pair(XFormNode,
897 std::make_pair(SDNode, Code)));
898
Chris Lattner1048b7a2005-09-13 22:03:37 +0000899 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000900 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
901 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
902
Chris Lattner1048b7a2005-09-13 22:03:37 +0000903 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000904 << "(SDNode *" << C2 << ") {\n";
905 if (ClassName != "SDNode")
906 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
907 OS << Code << "\n}\n";
908 }
909
910 Xforms.pop_back();
911 }
912}
913
Evan Cheng0fc71982005-12-08 02:00:36 +0000914void DAGISelEmitter::ParseComplexPatterns() {
915 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
916 while (!AMs.empty()) {
917 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
918 AMs.pop_back();
919 }
920}
Chris Lattner24eeeb82005-09-13 21:51:00 +0000921
922
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000923/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
924/// file, building up the PatternFragments map. After we've collected them all,
925/// inline fragments together as necessary, so that there are no references left
926/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000927///
928/// This also emits all of the predicate functions to the output file.
929///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000930void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000931 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
932
933 // First step, parse all of the fragments and emit predicate functions.
934 OS << "\n// Predicate functions.\n";
935 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000936 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000937 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000938 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000939
940 // Validate the argument list, converting it to map, to discard duplicates.
941 std::vector<std::string> &Args = P->getArgList();
942 std::set<std::string> OperandsMap(Args.begin(), Args.end());
943
944 if (OperandsMap.count(""))
945 P->error("Cannot have unnamed 'node' values in pattern fragment!");
946
947 // Parse the operands list.
948 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
949 if (OpsList->getNodeType()->getName() != "ops")
950 P->error("Operands list should start with '(ops ... '!");
951
952 // Copy over the arguments.
953 Args.clear();
954 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
955 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
956 static_cast<DefInit*>(OpsList->getArg(j))->
957 getDef()->getName() != "node")
958 P->error("Operands list should all be 'node' values.");
959 if (OpsList->getArgName(j).empty())
960 P->error("Operands list should have names for each operand!");
961 if (!OperandsMap.count(OpsList->getArgName(j)))
962 P->error("'" + OpsList->getArgName(j) +
963 "' does not occur in pattern or was multiply specified!");
964 OperandsMap.erase(OpsList->getArgName(j));
965 Args.push_back(OpsList->getArgName(j));
966 }
967
968 if (!OperandsMap.empty())
969 P->error("Operands list does not contain an entry for operand '" +
970 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000971
972 // If there is a code init for this fragment, emit the predicate code and
973 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000974 std::string Code = Fragments[i]->getValueAsCode("Predicate");
975 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000976 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000977 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000978 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000979 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
980
Chris Lattner1048b7a2005-09-13 22:03:37 +0000981 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000982 << "(SDNode *" << C2 << ") {\n";
983 if (ClassName != "SDNode")
984 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000985 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000986 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000987 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000988
989 // If there is a node transformation corresponding to this, keep track of
990 // it.
991 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
992 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000993 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000994 }
995
996 OS << "\n\n";
997
998 // Now that we've parsed all of the tree fragments, do a closure on them so
999 // that there are not references to PatFrags left inside of them.
1000 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1001 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001002 TreePattern *ThePat = I->second;
1003 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001004
Chris Lattner32707602005-09-08 23:22:48 +00001005 // Infer as many types as possible. Don't worry about it if we don't infer
1006 // all of them, some may depend on the inputs of the pattern.
1007 try {
1008 ThePat->InferAllTypes();
1009 } catch (...) {
1010 // If this pattern fragment is not supported by this target (no types can
1011 // satisfy its constraints), just ignore it. If the bogus pattern is
1012 // actually used by instructions, the type consistency error will be
1013 // reported there.
1014 }
1015
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001016 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001017 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001018 }
1019}
1020
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001021/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001022/// instruction input. Return true if this is a real use.
1023static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001024 std::map<std::string, TreePatternNode*> &InstInputs,
1025 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001026 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001027 if (Pat->getName().empty()) {
1028 if (Pat->isLeaf()) {
1029 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1030 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1031 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001032 else if (DI && DI->getDef()->isSubClassOf("Register"))
1033 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001034 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001035 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001036 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001037
1038 Record *Rec;
1039 if (Pat->isLeaf()) {
1040 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1041 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1042 Rec = DI->getDef();
1043 } else {
1044 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1045 Rec = Pat->getOperator();
1046 }
1047
Evan Cheng01f318b2005-12-14 02:21:57 +00001048 // SRCVALUE nodes are ignored.
1049 if (Rec->getName() == "srcvalue")
1050 return false;
1051
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001052 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1053 if (!Slot) {
1054 Slot = Pat;
1055 } else {
1056 Record *SlotRec;
1057 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001058 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001059 } else {
1060 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1061 SlotRec = Slot->getOperator();
1062 }
1063
1064 // Ensure that the inputs agree if we've already seen this input.
1065 if (Rec != SlotRec)
1066 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001067 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001068 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1069 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001070 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001071}
1072
1073/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1074/// part of "I", the instruction), computing the set of inputs and outputs of
1075/// the pattern. Report errors if we see anything naughty.
1076void DAGISelEmitter::
1077FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1078 std::map<std::string, TreePatternNode*> &InstInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001079 std::map<std::string, Record*> &InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001080 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001081 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001082 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001083 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001084 if (!isUse && Pat->getTransformFn())
1085 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001086 return;
1087 } else if (Pat->getOperator()->getName() != "set") {
1088 // If this is not a set, verify that the children nodes are not void typed,
1089 // and recurse.
1090 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001091 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001092 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001093 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001094 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001095 }
1096
1097 // If this is a non-leaf node with no children, treat it basically as if
1098 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001099 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001100 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001101 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001102
Chris Lattnerf1311842005-09-14 23:05:13 +00001103 if (!isUse && Pat->getTransformFn())
1104 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001105 return;
1106 }
1107
1108 // Otherwise, this is a set, validate and collect instruction results.
1109 if (Pat->getNumChildren() == 0)
1110 I->error("set requires operands!");
1111 else if (Pat->getNumChildren() & 1)
1112 I->error("set requires an even number of operands");
1113
Chris Lattnerf1311842005-09-14 23:05:13 +00001114 if (Pat->getTransformFn())
1115 I->error("Cannot specify a transform function on a set node!");
1116
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001117 // Check the set destinations.
1118 unsigned NumValues = Pat->getNumChildren()/2;
1119 for (unsigned i = 0; i != NumValues; ++i) {
1120 TreePatternNode *Dest = Pat->getChild(i);
1121 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001122 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001123
1124 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1125 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001126 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001127
Evan Chengbcecf332005-12-17 01:19:28 +00001128 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1129 if (Dest->getName().empty())
1130 I->error("set destination must have a name!");
1131 if (InstResults.count(Dest->getName()))
1132 I->error("cannot set '" + Dest->getName() +"' multiple times");
1133 InstResults[Dest->getName()] = Val->getDef();
Evan Cheng7b05bd52005-12-23 22:11:47 +00001134 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001135 InstImpResults.push_back(Val->getDef());
1136 } else {
1137 I->error("set destination should be a register!");
1138 }
1139
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001140 // Verify and collect info from the computation.
1141 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001142 InstInputs, InstResults,
1143 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001144 }
1145}
1146
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001147/// ParseInstructions - Parse all of the instructions, inlining and resolving
1148/// any fragments involved. This populates the Instructions list with fully
1149/// resolved instructions.
1150void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001151 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1152
1153 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001154 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001155
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001156 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1157 LI = Instrs[i]->getValueAsListInit("Pattern");
1158
1159 // If there is no pattern, only collect minimal information about the
1160 // instruction for its operand list. We have to assume that there is one
1161 // result, as we have no detailed info.
1162 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001163 std::vector<Record*> Results;
1164 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001165
1166 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001167
Evan Cheng3a217f32005-12-22 02:35:21 +00001168 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001169 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001170 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001171 // These produce no results
1172 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1173 Operands.push_back(InstInfo.OperandList[j].Rec);
1174 } else {
1175 // Assume the first operand is the result.
1176 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001177
Evan Cheng3a217f32005-12-22 02:35:21 +00001178 // The rest are inputs.
1179 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1180 Operands.push_back(InstInfo.OperandList[j].Rec);
1181 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001182 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001183
1184 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001185 std::vector<Record*> ImpResults;
1186 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001187 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001188 DAGInstruction(0, Results, Operands, ImpResults,
1189 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001190 continue; // no pattern.
1191 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001192
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001193 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001194 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001195 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001196 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001197
Chris Lattner95f6b762005-09-08 23:26:30 +00001198 // Infer as many types as possible. If we cannot infer all of them, we can
1199 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001200 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001201 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001202
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001203 // InstInputs - Keep track of all of the inputs of the instruction, along
1204 // with the record they are declared as.
1205 std::map<std::string, TreePatternNode*> InstInputs;
1206
1207 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001208 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001209 std::map<std::string, Record*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001210
1211 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001212 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001213
Chris Lattner1f39e292005-09-14 00:09:24 +00001214 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001215 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001216 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1217 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001218 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001219 I->error("Top-level forms in instruction pattern should have"
1220 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001221
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001222 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001223 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001224 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001225 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001226
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001227 // Now that we have inputs and outputs of the pattern, inspect the operands
1228 // list for the instruction. This determines the order that operands are
1229 // added to the machine instruction the node corresponds to.
1230 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001231
1232 // Parse the operands list from the (ops) list, validating it.
1233 std::vector<std::string> &Args = I->getArgList();
1234 assert(Args.empty() && "Args list should still be empty here!");
1235 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1236
1237 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001238 std::vector<Record*> Results;
Chris Lattner39e8af92005-09-14 18:19:25 +00001239 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001240 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001241 I->error("'" + InstResults.begin()->first +
1242 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001243 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001244
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001245 // Check that it exists in InstResults.
1246 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001247 if (R == 0)
1248 I->error("Operand $" + OpName + " should be a set destination: all "
1249 "outputs must occur before inputs in operand list!");
1250
1251 if (CGI.OperandList[i].Rec != R)
1252 I->error("Operand $" + OpName + " class mismatch!");
1253
Chris Lattnerae6d8282005-09-15 21:51:12 +00001254 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001255 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001256
Chris Lattner39e8af92005-09-14 18:19:25 +00001257 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001258 InstResults.erase(OpName);
1259 }
1260
Chris Lattner0b592252005-09-14 21:59:34 +00001261 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1262 // the copy while we're checking the inputs.
1263 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001264
1265 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001266 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001267 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1268 const std::string &OpName = CGI.OperandList[i].Name;
1269 if (OpName.empty())
1270 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1271
Chris Lattner0b592252005-09-14 21:59:34 +00001272 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001273 I->error("Operand $" + OpName +
1274 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001275 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001276 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001277
1278 if (InVal->isLeaf() &&
1279 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1280 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001281 if (CGI.OperandList[i].Rec != InRec &&
1282 !InRec->isSubClassOf("ComplexPattern"))
Nate Begemanddb39542005-12-01 00:06:14 +00001283 I->error("Operand $" + OpName +
Evan Cheng0fc71982005-12-08 02:00:36 +00001284 "'s register class disagrees between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001285 }
1286 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001287
Chris Lattner2175c182005-09-14 23:01:59 +00001288 // Construct the result for the dest-pattern operand list.
1289 TreePatternNode *OpNode = InVal->clone();
1290
1291 // No predicate is useful on the result.
1292 OpNode->setPredicateFn("");
1293
1294 // Promote the xform function to be an explicit node if set.
1295 if (Record *Xform = OpNode->getTransformFn()) {
1296 OpNode->setTransformFn(0);
1297 std::vector<TreePatternNode*> Children;
1298 Children.push_back(OpNode);
1299 OpNode = new TreePatternNode(Xform, Children);
1300 }
1301
1302 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001303 }
1304
Chris Lattner0b592252005-09-14 21:59:34 +00001305 if (!InstInputsCheck.empty())
1306 I->error("Input operand $" + InstInputsCheck.begin()->first +
1307 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001308
1309 TreePatternNode *ResultPattern =
1310 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001311
1312 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001313 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001314 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1315
1316 // Use a temporary tree pattern to infer all types and make sure that the
1317 // constructed result is correct. This depends on the instruction already
1318 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001319 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001320 Temp.InferAllTypes();
1321
1322 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1323 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001324
Chris Lattner32707602005-09-08 23:22:48 +00001325 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001326 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001327
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001328 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001329 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1330 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001331 DAGInstruction &TheInst = II->second;
1332 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001333 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001334
Chris Lattner1f39e292005-09-14 00:09:24 +00001335 if (I->getNumTrees() != 1) {
1336 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1337 continue;
1338 }
1339 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001340 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001341 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001342 if (Pattern->getNumChildren() != 2)
1343 continue; // Not a set of a single value (not handled so far)
1344
1345 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001346 } else{
1347 // Not a set (store or something?)
1348 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001349 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001350
1351 std::string Reason;
1352 if (!SrcPattern->canPatternMatch(Reason, *this))
1353 I->error("Instruction can never match: " + Reason);
1354
Evan Cheng58e84a62005-12-14 22:02:59 +00001355 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001356 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001357 PatternsToMatch.
1358 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1359 SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001360 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001361}
1362
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001363void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001364 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001365
Chris Lattnerabbb6052005-09-15 21:42:00 +00001366 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001367 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001368 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001369
Chris Lattnerabbb6052005-09-15 21:42:00 +00001370 // Inline pattern fragments into it.
1371 Pattern->InlinePatternFragments();
1372
1373 // Infer as many types as possible. If we cannot infer all of them, we can
1374 // never do anything with this pattern: report it to the user.
1375 if (!Pattern->InferAllTypes())
1376 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001377
1378 // Validate that the input pattern is correct.
1379 {
1380 std::map<std::string, TreePatternNode*> InstInputs;
1381 std::map<std::string, Record*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001382 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001383 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001384 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001385 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001386 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001387 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001388
1389 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1390 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001391
1392 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001393 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001394
1395 // Inline pattern fragments into it.
1396 Result->InlinePatternFragments();
1397
1398 // Infer as many types as possible. If we cannot infer all of them, we can
1399 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001400 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001401 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001402
1403 if (Result->getNumTrees() != 1)
1404 Result->error("Cannot handle instructions producing instructions "
1405 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001406
1407 std::string Reason;
1408 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1409 Pattern->error("Pattern can never match: " + Reason);
1410
Evan Cheng58e84a62005-12-14 22:02:59 +00001411 PatternsToMatch.
1412 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1413 Pattern->getOnlyTree(),
1414 Result->getOnlyTree()));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001415 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001416}
1417
Chris Lattnere46e17b2005-09-29 19:28:10 +00001418/// CombineChildVariants - Given a bunch of permutations of each child of the
1419/// 'operator' node, put them together in all possible ways.
1420static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001421 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001422 std::vector<TreePatternNode*> &OutVariants,
1423 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001424 // Make sure that each operand has at least one variant to choose from.
1425 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1426 if (ChildVariants[i].empty())
1427 return;
1428
Chris Lattnere46e17b2005-09-29 19:28:10 +00001429 // The end result is an all-pairs construction of the resultant pattern.
1430 std::vector<unsigned> Idxs;
1431 Idxs.resize(ChildVariants.size());
1432 bool NotDone = true;
1433 while (NotDone) {
1434 // Create the variant and add it to the output list.
1435 std::vector<TreePatternNode*> NewChildren;
1436 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1437 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1438 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1439
1440 // Copy over properties.
1441 R->setName(Orig->getName());
1442 R->setPredicateFn(Orig->getPredicateFn());
1443 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001444 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001445
1446 // If this pattern cannot every match, do not include it as a variant.
1447 std::string ErrString;
1448 if (!R->canPatternMatch(ErrString, ISE)) {
1449 delete R;
1450 } else {
1451 bool AlreadyExists = false;
1452
1453 // Scan to see if this pattern has already been emitted. We can get
1454 // duplication due to things like commuting:
1455 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1456 // which are the same pattern. Ignore the dups.
1457 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1458 if (R->isIsomorphicTo(OutVariants[i])) {
1459 AlreadyExists = true;
1460 break;
1461 }
1462
1463 if (AlreadyExists)
1464 delete R;
1465 else
1466 OutVariants.push_back(R);
1467 }
1468
1469 // Increment indices to the next permutation.
1470 NotDone = false;
1471 // Look for something we can increment without causing a wrap-around.
1472 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1473 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1474 NotDone = true; // Found something to increment.
1475 break;
1476 }
1477 Idxs[IdxsIdx] = 0;
1478 }
1479 }
1480}
1481
Chris Lattneraf302912005-09-29 22:36:54 +00001482/// CombineChildVariants - A helper function for binary operators.
1483///
1484static void CombineChildVariants(TreePatternNode *Orig,
1485 const std::vector<TreePatternNode*> &LHS,
1486 const std::vector<TreePatternNode*> &RHS,
1487 std::vector<TreePatternNode*> &OutVariants,
1488 DAGISelEmitter &ISE) {
1489 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1490 ChildVariants.push_back(LHS);
1491 ChildVariants.push_back(RHS);
1492 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1493}
1494
1495
1496static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1497 std::vector<TreePatternNode *> &Children) {
1498 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1499 Record *Operator = N->getOperator();
1500
1501 // Only permit raw nodes.
1502 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1503 N->getTransformFn()) {
1504 Children.push_back(N);
1505 return;
1506 }
1507
1508 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1509 Children.push_back(N->getChild(0));
1510 else
1511 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1512
1513 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1514 Children.push_back(N->getChild(1));
1515 else
1516 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1517}
1518
Chris Lattnere46e17b2005-09-29 19:28:10 +00001519/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1520/// the (potentially recursive) pattern by using algebraic laws.
1521///
1522static void GenerateVariantsOf(TreePatternNode *N,
1523 std::vector<TreePatternNode*> &OutVariants,
1524 DAGISelEmitter &ISE) {
1525 // We cannot permute leaves.
1526 if (N->isLeaf()) {
1527 OutVariants.push_back(N);
1528 return;
1529 }
1530
1531 // Look up interesting info about the node.
1532 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1533
1534 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001535 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1536 // Reassociate by pulling together all of the linked operators
1537 std::vector<TreePatternNode*> MaximalChildren;
1538 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1539
1540 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1541 // permutations.
1542 if (MaximalChildren.size() == 3) {
1543 // Find the variants of all of our maximal children.
1544 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1545 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1546 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1547 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1548
1549 // There are only two ways we can permute the tree:
1550 // (A op B) op C and A op (B op C)
1551 // Within these forms, we can also permute A/B/C.
1552
1553 // Generate legal pair permutations of A/B/C.
1554 std::vector<TreePatternNode*> ABVariants;
1555 std::vector<TreePatternNode*> BAVariants;
1556 std::vector<TreePatternNode*> ACVariants;
1557 std::vector<TreePatternNode*> CAVariants;
1558 std::vector<TreePatternNode*> BCVariants;
1559 std::vector<TreePatternNode*> CBVariants;
1560 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1561 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1562 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1563 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1564 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1565 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1566
1567 // Combine those into the result: (x op x) op x
1568 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1569 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1570 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1571 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1572 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1573 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1574
1575 // Combine those into the result: x op (x op x)
1576 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1577 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1578 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1579 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1580 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1581 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1582 return;
1583 }
1584 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001585
1586 // Compute permutations of all children.
1587 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1588 ChildVariants.resize(N->getNumChildren());
1589 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1590 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1591
1592 // Build all permutations based on how the children were formed.
1593 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1594
1595 // If this node is commutative, consider the commuted order.
1596 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1597 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001598 // Consider the commuted order.
1599 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1600 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001601 }
1602}
1603
1604
Chris Lattnere97603f2005-09-28 19:27:25 +00001605// GenerateVariants - Generate variants. For example, commutative patterns can
1606// match multiple ways. Add them to PatternsToMatch as well.
1607void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001608
1609 DEBUG(std::cerr << "Generating instruction variants.\n");
1610
1611 // Loop over all of the patterns we've collected, checking to see if we can
1612 // generate variants of the instruction, through the exploitation of
1613 // identities. This permits the target to provide agressive matching without
1614 // the .td file having to contain tons of variants of instructions.
1615 //
1616 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1617 // intentionally do not reconsider these. Any variants of added patterns have
1618 // already been added.
1619 //
1620 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1621 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001622 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001623
1624 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001625 Variants.erase(Variants.begin()); // Remove the original pattern.
1626
1627 if (Variants.empty()) // No variants for this pattern.
1628 continue;
1629
1630 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001631 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001632 std::cerr << "\n");
1633
1634 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1635 TreePatternNode *Variant = Variants[v];
1636
1637 DEBUG(std::cerr << " VAR#" << v << ": ";
1638 Variant->dump();
1639 std::cerr << "\n");
1640
1641 // Scan to see if an instruction or explicit pattern already matches this.
1642 bool AlreadyExists = false;
1643 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1644 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001645 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001646 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1647 AlreadyExists = true;
1648 break;
1649 }
1650 }
1651 // If we already have it, ignore the variant.
1652 if (AlreadyExists) continue;
1653
1654 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001655 PatternsToMatch.
1656 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1657 Variant, PatternsToMatch[i].getDstPattern()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001658 }
1659
1660 DEBUG(std::cerr << "\n");
1661 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001662}
1663
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001664
Evan Cheng0fc71982005-12-08 02:00:36 +00001665// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1666// ComplexPattern.
1667static bool NodeIsComplexPattern(TreePatternNode *N)
1668{
1669 return (N->isLeaf() &&
1670 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1671 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1672 isSubClassOf("ComplexPattern"));
1673}
1674
1675// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1676// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1677static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1678 DAGISelEmitter &ISE)
1679{
1680 if (N->isLeaf() &&
1681 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1682 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1683 isSubClassOf("ComplexPattern")) {
1684 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1685 ->getDef());
1686 }
1687 return NULL;
1688}
1689
Chris Lattner05814af2005-09-28 17:57:56 +00001690/// getPatternSize - Return the 'size' of this pattern. We want to match large
1691/// patterns before small ones. This is used to determine the size of a
1692/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001693static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Chenge1050d62006-01-06 02:30:23 +00001694 unsigned Size = 2; // The node itself.
Evan Cheng0fc71982005-12-08 02:00:36 +00001695
1696 // FIXME: This is a hack to statically increase the priority of patterns
1697 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1698 // Later we can allow complexity / cost for each pattern to be (optionally)
1699 // specified. To get best possible pattern match we'll need to dynamically
1700 // calculate the complexity of all patterns a dag can potentially map to.
1701 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1702 if (AM)
1703 Size += AM->getNumOperands();
1704
Chris Lattner05814af2005-09-28 17:57:56 +00001705 // Count children in the count if they are also nodes.
1706 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1707 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001708 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001709 Size += getPatternSize(Child, ISE);
1710 else if (Child->isLeaf()) {
Evan Chenge1050d62006-01-06 02:30:23 +00001711 Size += getPatternSize(Child, ISE);
Evan Cheng0fc71982005-12-08 02:00:36 +00001712 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Chenge1050d62006-01-06 02:30:23 +00001713 // Matches a ConstantSDNode. More specific to any immediate.
1714 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00001715 }
Chris Lattner05814af2005-09-28 17:57:56 +00001716 }
1717
1718 return Size;
1719}
1720
1721/// getResultPatternCost - Compute the number of instructions for this pattern.
1722/// This is a temporary hack. We should really include the instruction
1723/// latencies in this calculation.
1724static unsigned getResultPatternCost(TreePatternNode *P) {
1725 if (P->isLeaf()) return 0;
1726
1727 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1728 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1729 Cost += getResultPatternCost(P->getChild(i));
1730 return Cost;
1731}
1732
1733// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1734// In particular, we want to match maximal patterns first and lowest cost within
1735// a particular complexity first.
1736struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001737 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1738 DAGISelEmitter &ISE;
1739
Evan Cheng58e84a62005-12-14 22:02:59 +00001740 bool operator()(PatternToMatch *LHS,
1741 PatternToMatch *RHS) {
1742 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1743 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001744 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1745 if (LHSSize < RHSSize) return false;
1746
1747 // If the patterns have equal complexity, compare generated instruction cost
Evan Cheng58e84a62005-12-14 22:02:59 +00001748 return getResultPatternCost(LHS->getDstPattern()) <
1749 getResultPatternCost(RHS->getDstPattern());
Chris Lattner05814af2005-09-28 17:57:56 +00001750 }
1751};
1752
Nate Begeman6510b222005-12-01 04:51:06 +00001753/// getRegisterValueType - Look up and return the first ValueType of specified
1754/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001755static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001756 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1757 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001758 return MVT::Other;
1759}
1760
Chris Lattner72fe91c2005-09-24 00:40:24 +00001761
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001762/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1763/// type information from it.
1764static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001765 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001766 if (!N->isLeaf())
1767 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1768 RemoveAllTypes(N->getChild(i));
1769}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001770
Chris Lattner0614b622005-11-02 06:49:14 +00001771Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1772 Record *N = Records.getDef(Name);
1773 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1774 return N;
1775}
1776
Evan Cheng7b05bd52005-12-23 22:11:47 +00001777/// NodeHasChain - return true if TreePatternNode has the property
1778/// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1779/// a chain result.
1780static bool NodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1781{
1782 if (N->isLeaf()) return false;
1783 Record *Operator = N->getOperator();
1784 if (!Operator->isSubClassOf("SDNode")) return false;
1785
1786 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1787 return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1788}
1789
1790static bool PatternHasCtrlDep(TreePatternNode *N, DAGISelEmitter &ISE)
1791{
1792 if (NodeHasChain(N, ISE))
1793 return true;
1794 else {
1795 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1796 TreePatternNode *Child = N->getChild(i);
1797 if (PatternHasCtrlDep(Child, ISE))
1798 return true;
1799 }
1800 }
1801
1802 return false;
1803}
1804
Evan Chengb915f312005-12-09 22:45:35 +00001805class PatternCodeEmitter {
1806private:
1807 DAGISelEmitter &ISE;
1808
Evan Cheng58e84a62005-12-14 22:02:59 +00001809 // Predicates.
1810 ListInit *Predicates;
1811 // Instruction selector pattern.
1812 TreePatternNode *Pattern;
1813 // Matched instruction.
1814 TreePatternNode *Instruction;
Evan Chengb915f312005-12-09 22:45:35 +00001815 unsigned PatternNo;
1816 std::ostream &OS;
1817 // Node to name mapping
1818 std::map<std::string,std::string> VariableMap;
Evan Chengb915f312005-12-09 22:45:35 +00001819 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001820 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb915f312005-12-09 22:45:35 +00001821 unsigned TmpNo;
1822
1823public:
Evan Cheng58e84a62005-12-14 22:02:59 +00001824 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1825 TreePatternNode *pattern, TreePatternNode *instr,
Evan Chengb915f312005-12-09 22:45:35 +00001826 unsigned PatNum, std::ostream &os) :
Evan Cheng58e84a62005-12-14 22:02:59 +00001827 ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001828 PatternNo(PatNum), OS(os), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00001829
1830 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1831 /// if the match fails. At this point, we already know that the opcode for N
1832 /// matches, and the SDNode for the result has the RootName specified name.
1833 void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001834 bool &FoundChain, bool isRoot = false) {
Evan Cheng58e84a62005-12-14 22:02:59 +00001835
1836 // Emit instruction predicates. Each predicate is just a string for now.
1837 if (isRoot) {
1838 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1839 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1840 Record *Def = Pred->getDef();
1841 if (Def->isSubClassOf("Predicate")) {
1842 if (i == 0)
1843 OS << " if (";
1844 else
1845 OS << " && ";
Evan Cheng5fb5e102005-12-20 20:08:01 +00001846 OS << "!(" << Def->getValueAsString("CondString") << ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00001847 if (i == e-1)
1848 OS << ") goto P" << PatternNo << "Fail;\n";
1849 } else {
1850 Def->dump();
1851 assert(0 && "Unknown predicate type!");
1852 }
1853 }
1854 }
1855 }
1856
Evan Chengb915f312005-12-09 22:45:35 +00001857 if (N->isLeaf()) {
1858 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1859 OS << " if (cast<ConstantSDNode>(" << RootName
1860 << ")->getSignExtended() != " << II->getValue() << ")\n"
1861 << " goto P" << PatternNo << "Fail;\n";
1862 return;
1863 } else if (!NodeIsComplexPattern(N)) {
1864 assert(0 && "Cannot match this as a leaf value!");
1865 abort();
1866 }
1867 }
1868
1869 // If this node has a name associated with it, capture it in VariableMap. If
1870 // we already saw this in the pattern, emit code to verify dagness.
1871 if (!N->getName().empty()) {
1872 std::string &VarMapEntry = VariableMap[N->getName()];
1873 if (VarMapEntry.empty()) {
1874 VarMapEntry = RootName;
1875 } else {
1876 // If we get here, this is a second reference to a specific name. Since
1877 // we already have checked that the first reference is valid, we don't
1878 // have to recursively match it, just check that it's the same as the
1879 // previously named thing.
1880 OS << " if (" << VarMapEntry << " != " << RootName
1881 << ") goto P" << PatternNo << "Fail;\n";
1882 return;
1883 }
1884 }
1885
1886
1887 // Emit code to load the child nodes and match their contents recursively.
1888 unsigned OpNo = 0;
Evan Cheng86217892005-12-12 19:37:43 +00001889 bool HasChain = NodeHasChain(N, ISE);
1890 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00001891 OpNo = 1;
1892 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00001893 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Evan Chengb915f312005-12-09 22:45:35 +00001894 OS << " if (!" << RootName << ".hasOneUse()) goto P"
1895 << PatternNo << "Fail; // Multiple uses of actual result?\n";
1896 OS << " if (CodeGenMap.count(" << RootName
Evan Cheng1129e872005-12-10 00:09:17 +00001897 << ".getValue(" << CInfo.getNumResults() << "))) goto P"
Evan Chengb915f312005-12-09 22:45:35 +00001898 << PatternNo << "Fail; // Already selected for a chain use?\n";
1899 }
Evan Cheng1cf6db22006-01-06 00:41:12 +00001900 if (!FoundChain) {
1901 OS << " SDOperand Chain = " << RootName << ".getOperand(0);\n";
1902 FoundChain = true;
1903 }
Evan Chengb915f312005-12-09 22:45:35 +00001904 }
1905
1906 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00001907 OS << " SDOperand " << RootName << OpNo << " = "
1908 << RootName << ".getOperand(" << OpNo << ");\n";
Evan Chengb915f312005-12-09 22:45:35 +00001909 TreePatternNode *Child = N->getChild(i);
1910
1911 if (!Child->isLeaf()) {
1912 // If it's not a leaf, recursively match.
1913 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1914 OS << " if (" << RootName << OpNo << ".getOpcode() != "
1915 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00001916 EmitMatchCode(Child, RootName + utostr(OpNo), FoundChain);
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001917 if (NodeHasChain(Child, ISE)) {
1918 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
1919 CInfo.getNumResults()));
1920 }
Evan Chengb915f312005-12-09 22:45:35 +00001921 } else {
1922 // If this child has a name associated with it, capture it in VarMap. If
1923 // we already saw this in the pattern, emit code to verify dagness.
1924 if (!Child->getName().empty()) {
1925 std::string &VarMapEntry = VariableMap[Child->getName()];
1926 if (VarMapEntry.empty()) {
1927 VarMapEntry = RootName + utostr(OpNo);
1928 } else {
1929 // If we get here, this is a second reference to a specific name. Since
1930 // we already have checked that the first reference is valid, we don't
1931 // have to recursively match it, just check that it's the same as the
1932 // previously named thing.
1933 OS << " if (" << VarMapEntry << " != " << RootName << OpNo
1934 << ") goto P" << PatternNo << "Fail;\n";
1935 continue;
1936 }
1937 }
1938
1939 // Handle leaves of various types.
1940 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1941 Record *LeafRec = DI->getDef();
1942 if (LeafRec->isSubClassOf("RegisterClass")) {
1943 // Handle register references. Nothing to do here.
1944 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00001945 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00001946 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1947 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00001948 } else if (LeafRec->getName() == "srcvalue") {
1949 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00001950 } else if (LeafRec->isSubClassOf("ValueType")) {
1951 // Make sure this is the specified value type.
1952 OS << " if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
1953 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1954 << "Fail;\n";
1955 } else if (LeafRec->isSubClassOf("CondCode")) {
1956 // Make sure this is the specified cond code.
1957 OS << " if (cast<CondCodeSDNode>(" << RootName << OpNo
1958 << ")->get() != " << "ISD::" << LeafRec->getName()
1959 << ") goto P" << PatternNo << "Fail;\n";
1960 } else {
1961 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00001962 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00001963 assert(0 && "Unknown leaf type!");
1964 }
1965 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1966 OS << " if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1967 << " cast<ConstantSDNode>(" << RootName << OpNo
1968 << ")->getSignExtended() != " << II->getValue() << ")\n"
1969 << " goto P" << PatternNo << "Fail;\n";
1970 } else {
1971 Child->dump();
1972 assert(0 && "Unknown leaf type!");
1973 }
1974 }
1975 }
1976
1977 // If there is a node predicate for this, emit the call.
1978 if (!N->getPredicateFn().empty())
1979 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1980 << ".Val)) goto P" << PatternNo << "Fail;\n";
1981 }
1982
1983 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
1984 /// we actually have to build a DAG!
1985 std::pair<unsigned, unsigned>
1986 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
1987 // This is something selected from the pattern we matched.
1988 if (!N->getName().empty()) {
1989 assert(!isRoot && "Root of pattern cannot be a leaf!");
1990 std::string &Val = VariableMap[N->getName()];
1991 assert(!Val.empty() &&
1992 "Variable referenced but not defined and not caught earlier!");
1993 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1994 // Already selected this operand, just return the tmpval.
1995 return std::make_pair(1, atoi(Val.c_str()+3));
1996 }
1997
1998 const ComplexPattern *CP;
1999 unsigned ResNo = TmpNo++;
2000 unsigned NumRes = 1;
2001 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002002 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2003 switch (N->getTypeNum(0)) {
Evan Chengb915f312005-12-09 22:45:35 +00002004 default: assert(0 && "Unknown type for constant node!");
2005 case MVT::i1: OS << " bool Tmp"; break;
2006 case MVT::i8: OS << " unsigned char Tmp"; break;
2007 case MVT::i16: OS << " unsigned short Tmp"; break;
2008 case MVT::i32: OS << " unsigned Tmp"; break;
2009 case MVT::i64: OS << " uint64_t Tmp"; break;
2010 }
2011 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002012 OS << " SDOperand Tmp" << utostr(ResNo)
2013 << " = CurDAG->getTargetConstant(Tmp"
Nate Begemanb73628b2005-12-30 00:12:56 +00002014 << ResNo << "C, MVT::" << getEnumName(N->getTypeNum(0)) << ");\n";
Evan Chengb915f312005-12-09 22:45:35 +00002015 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002016 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Nate Begeman28a6b022005-12-10 02:36:00 +00002017 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002018 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
2019 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2020 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Evan Chengb915f312005-12-09 22:45:35 +00002021 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2022 std::string Fn = CP->getSelectFunc();
2023 NumRes = CP->getNumOperands();
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002024 OS << " SDOperand ";
Jeff Cohen60e91872006-01-04 03:23:30 +00002025 for (unsigned i = 0; i < NumRes - 1; ++i)
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002026 OS << "Tmp" << (i+ResNo) << ",";
Jeff Cohen60e91872006-01-04 03:23:30 +00002027 OS << "Tmp" << (NumRes - 1 + ResNo) << ";\n";
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002028
Evan Chengb915f312005-12-09 22:45:35 +00002029 OS << " if (!" << Fn << "(" << Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002030 for (unsigned i = 0; i < NumRes; i++)
Evan Chengbcecf332005-12-17 01:19:28 +00002031 OS << ", Tmp" << i + ResNo;
Evan Chengb915f312005-12-09 22:45:35 +00002032 OS << ")) goto P" << PatternNo << "Fail;\n";
2033 TmpNo = ResNo + NumRes;
2034 } else {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002035 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
Evan Chengb915f312005-12-09 22:45:35 +00002036 }
2037 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2038 // value if used multiple times by this pattern result.
2039 Val = "Tmp"+utostr(ResNo);
2040 return std::make_pair(NumRes, ResNo);
2041 }
2042
2043 if (N->isLeaf()) {
2044 // If this is an explicit register reference, handle it.
2045 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2046 unsigned ResNo = TmpNo++;
2047 if (DI->getDef()->isSubClassOf("Register")) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002048 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
Evan Chengb915f312005-12-09 22:45:35 +00002049 << ISE.getQualifiedName(DI->getDef()) << ", MVT::"
Nate Begemanb73628b2005-12-30 00:12:56 +00002050 << getEnumName(N->getTypeNum(0))
Evan Chengb915f312005-12-09 22:45:35 +00002051 << ");\n";
2052 return std::make_pair(1, ResNo);
2053 }
2054 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2055 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002056 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002057 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
Evan Chengb915f312005-12-09 22:45:35 +00002058 << II->getValue() << ", MVT::"
Nate Begemanb73628b2005-12-30 00:12:56 +00002059 << getEnumName(N->getTypeNum(0))
Evan Chengb915f312005-12-09 22:45:35 +00002060 << ");\n";
2061 return std::make_pair(1, ResNo);
2062 }
2063
2064 N->dump();
2065 assert(0 && "Unknown leaf type!");
2066 return std::make_pair(1, ~0U);
2067 }
2068
2069 Record *Op = N->getOperator();
2070 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002071 const CodeGenTarget &CGT = ISE.getTargetInfo();
2072 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002073 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002074 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2075 bool HasImpResults = Inst.getNumImpResults() > 0;
2076 bool HasInFlag = II.hasInFlag || HasImpInputs;
2077 bool HasOutFlag = II.hasOutFlag || HasImpResults;
2078 bool HasChain = II.hasCtrlDep;
Evan Cheng4fba2812005-12-20 07:37:41 +00002079
Evan Cheng7b05bd52005-12-23 22:11:47 +00002080 if (isRoot && PatternHasCtrlDep(Pattern, ISE))
2081 HasChain = true;
2082 if (HasInFlag || HasOutFlag)
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002083 OS << " SDOperand InFlag = SDOperand(0, 0);\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002084
Evan Chengb915f312005-12-09 22:45:35 +00002085 // Determine operand emission order. Complex pattern first.
2086 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2087 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2088 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2089 TreePatternNode *Child = N->getChild(i);
2090 if (i == 0) {
2091 EmitOrder.push_back(std::make_pair(i, Child));
2092 OI = EmitOrder.begin();
2093 } else if (NodeIsComplexPattern(Child)) {
2094 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2095 } else {
2096 EmitOrder.push_back(std::make_pair(i, Child));
2097 }
2098 }
2099
2100 // Emit all of the operands.
2101 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2102 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2103 unsigned OpOrder = EmitOrder[i].first;
2104 TreePatternNode *Child = EmitOrder[i].second;
2105 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2106 NumTemps[OpOrder] = NumTemp;
2107 }
2108
2109 // List all the operands in the right order.
2110 std::vector<unsigned> Ops;
2111 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2112 for (unsigned j = 0; j < NumTemps[i].first; j++)
2113 Ops.push_back(NumTemps[i].second + j);
2114 }
2115
Evan Chengb915f312005-12-09 22:45:35 +00002116 // Emit all the chain and CopyToReg stuff.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002117 if (HasChain)
Evan Cheng86217892005-12-12 19:37:43 +00002118 OS << " Chain = Select(Chain);\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002119 if (HasInFlag)
2120 EmitInFlags(Pattern, "N", HasChain, II.hasInFlag, true);
Evan Chengb915f312005-12-09 22:45:35 +00002121
Evan Chengb915f312005-12-09 22:45:35 +00002122 unsigned NumResults = Inst.getNumResults();
2123 unsigned ResNo = TmpNo++;
2124 if (!isRoot) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002125 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
Evan Chengbcecf332005-12-17 01:19:28 +00002126 << II.Namespace << "::" << II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002127 if (N->getTypeNum(0) != MVT::isVoid)
2128 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
Evan Cheng7b05bd52005-12-23 22:11:47 +00002129 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002130 OS << ", MVT::Flag";
Evan Chengbcecf332005-12-17 01:19:28 +00002131
Evan Chengb915f312005-12-09 22:45:35 +00002132 unsigned LastOp = 0;
2133 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2134 LastOp = Ops[i];
2135 OS << ", Tmp" << LastOp;
2136 }
2137 OS << ");\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002138 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002139 // Must have at least one result
2140 OS << " Chain = Tmp" << LastOp << ".getValue("
2141 << NumResults << ");\n";
2142 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002143 } else if (HasChain || HasOutFlag) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002144 OS << " SDOperand Result = CurDAG->getTargetNode("
Evan Chengb915f312005-12-09 22:45:35 +00002145 << II.Namespace << "::" << II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002146
2147 // Output order: results, chain, flags
2148 // Result types.
Evan Chengbcecf332005-12-17 01:19:28 +00002149 if (NumResults > 0) {
Nate Begemanb73628b2005-12-30 00:12:56 +00002150 if (N->getTypeNum(0) != MVT::isVoid)
2151 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
Evan Chengbcecf332005-12-17 01:19:28 +00002152 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002153 if (HasChain)
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002154 OS << ", MVT::Other";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002155 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002156 OS << ", MVT::Flag";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002157
2158 // Inputs.
Evan Chengb915f312005-12-09 22:45:35 +00002159 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2160 OS << ", Tmp" << Ops[i];
Evan Cheng7b05bd52005-12-23 22:11:47 +00002161 if (HasChain) OS << ", Chain";
2162 if (HasInFlag) OS << ", InFlag";
Evan Chengb915f312005-12-09 22:45:35 +00002163 OS << ");\n";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002164
2165 unsigned ValNo = 0;
Evan Chengf9fc25d2005-12-19 22:40:04 +00002166 for (unsigned i = 0; i < NumResults; i++) {
2167 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = Result"
2168 << ".getValue(" << ValNo << ");\n";
2169 ValNo++;
2170 }
2171
Evan Cheng7b05bd52005-12-23 22:11:47 +00002172 if (HasChain)
Evan Cheng4fba2812005-12-20 07:37:41 +00002173 OS << " Chain = Result.getValue(" << ValNo << ");\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002174
Evan Cheng7b05bd52005-12-23 22:11:47 +00002175 if (HasOutFlag)
Evan Cheng97938882005-12-22 02:24:50 +00002176 OS << " InFlag = Result.getValue("
Evan Cheng7b05bd52005-12-23 22:11:47 +00002177 << ValNo + (unsigned)HasChain << ");\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002178
Evan Cheng7b05bd52005-12-23 22:11:47 +00002179 if (HasImpResults) {
2180 if (EmitCopyFromRegs(N, HasChain)) {
Evan Cheng97938882005-12-22 02:24:50 +00002181 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = "
2182 << "Result.getValue(" << ValNo << ");\n";
2183 ValNo++;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002184 HasChain = true;
Evan Cheng97938882005-12-22 02:24:50 +00002185 }
2186 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002187
Evan Cheng7b05bd52005-12-23 22:11:47 +00002188 // User does not expect that the instruction produces a chain!
2189 bool AddedChain = HasChain && !NodeHasChain(Pattern, ISE);
Evan Cheng97938882005-12-22 02:24:50 +00002190 if (NodeHasChain(Pattern, ISE))
2191 OS << " CodeGenMap[N.getValue(" << ValNo++ << ")] = Chain;\n";
2192
2193 if (FoldedChains.size() > 0) {
Evan Cheng4fba2812005-12-20 07:37:41 +00002194 OS << " ";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002195 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng4fba2812005-12-20 07:37:41 +00002196 OS << "CodeGenMap[" << FoldedChains[j].first << ".getValue("
2197 << FoldedChains[j].second << ")] = ";
2198 OS << "Chain;\n";
Evan Chengb915f312005-12-09 22:45:35 +00002199 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002200
Evan Cheng7b05bd52005-12-23 22:11:47 +00002201 if (HasOutFlag)
Evan Cheng97938882005-12-22 02:24:50 +00002202 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = InFlag;\n";
2203
Evan Cheng7b05bd52005-12-23 22:11:47 +00002204 if (AddedChain && HasOutFlag) {
Evan Cheng97938882005-12-22 02:24:50 +00002205 if (NumResults == 0) {
2206 OS << " return Result.getValue(N.ResNo+1);\n";
2207 } else {
2208 OS << " if (N.ResNo < " << NumResults << ")\n";
2209 OS << " return Result.getValue(N.ResNo);\n";
2210 OS << " else\n";
2211 OS << " return Result.getValue(N.ResNo+1);\n";
2212 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002213 } else {
Evan Chenge0870512005-12-20 00:06:17 +00002214 OS << " return Result.getValue(N.ResNo);\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002215 }
Evan Chengb915f312005-12-09 22:45:35 +00002216 } else {
2217 // If this instruction is the root, and if there is only one use of it,
2218 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2219 OS << " if (N.Val->hasOneUse()) {\n";
2220 OS << " return CurDAG->SelectNodeTo(N.Val, "
Evan Chengbcecf332005-12-17 01:19:28 +00002221 << II.Namespace << "::" << II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002222 if (N->getTypeNum(0) != MVT::isVoid)
2223 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
Evan Cheng7b05bd52005-12-23 22:11:47 +00002224 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002225 OS << ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002226 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2227 OS << ", Tmp" << Ops[i];
Evan Cheng7b05bd52005-12-23 22:11:47 +00002228 if (HasInFlag)
Evan Chengb915f312005-12-09 22:45:35 +00002229 OS << ", InFlag";
2230 OS << ");\n";
2231 OS << " } else {\n";
2232 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
Evan Chengbcecf332005-12-17 01:19:28 +00002233 << II.Namespace << "::" << II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002234 if (N->getTypeNum(0) != MVT::isVoid)
2235 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
Evan Cheng7b05bd52005-12-23 22:11:47 +00002236 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002237 OS << ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002238 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2239 OS << ", Tmp" << Ops[i];
Evan Cheng7b05bd52005-12-23 22:11:47 +00002240 if (HasInFlag)
Evan Chengb915f312005-12-09 22:45:35 +00002241 OS << ", InFlag";
2242 OS << ");\n";
2243 OS << " }\n";
2244 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002245
Evan Chengb915f312005-12-09 22:45:35 +00002246 return std::make_pair(1, ResNo);
2247 } else if (Op->isSubClassOf("SDNodeXForm")) {
2248 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng58e84a62005-12-14 22:02:59 +00002249 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
Evan Chengb915f312005-12-09 22:45:35 +00002250 unsigned ResNo = TmpNo++;
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002251 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
Evan Chengb915f312005-12-09 22:45:35 +00002252 << "(Tmp" << OpVal << ".Val);\n";
2253 if (isRoot) {
2254 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
2255 OS << " return Tmp" << ResNo << ";\n";
2256 }
2257 return std::make_pair(1, ResNo);
2258 } else {
2259 N->dump();
2260 assert(0 && "Unknown node in result pattern!");
2261 return std::make_pair(1, ~0U);
2262 }
2263 }
2264
2265 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2266 /// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2267 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2268 /// for, this returns true otherwise false if Pat has all types.
2269 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2270 const std::string &Prefix) {
2271 // Did we find one?
2272 if (!Pat->hasTypeSet()) {
2273 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002274 Pat->setTypes(Other->getExtTypes());
Evan Chengb915f312005-12-09 22:45:35 +00002275 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
Nate Begemanb73628b2005-12-30 00:12:56 +00002276 << getName(Pat->getTypeNum(0)) << ") goto P" << PatternNo << "Fail;\n";
Evan Chengb915f312005-12-09 22:45:35 +00002277 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002278 }
2279
2280 unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
2281 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2282 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2283 Prefix + utostr(OpNo)))
2284 return true;
2285 return false;
2286 }
2287
2288private:
Evan Cheng7b05bd52005-12-23 22:11:47 +00002289 /// EmitInFlags - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002290 /// being built.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002291 void EmitInFlags(TreePatternNode *N, const std::string &RootName,
2292 bool HasChain, bool HasInFlag, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002293 const CodeGenTarget &T = ISE.getTargetInfo();
2294 unsigned OpNo = (unsigned) NodeHasChain(N, ISE);
2295 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2296 TreePatternNode *Child = N->getChild(i);
2297 if (!Child->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002298 EmitInFlags(Child, RootName + utostr(OpNo), HasChain, HasInFlag);
Evan Chengb915f312005-12-09 22:45:35 +00002299 } else {
2300 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2301 Record *RR = DI->getDef();
2302 if (RR->isSubClassOf("Register")) {
2303 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002304 if (RVT == MVT::Flag) {
2305 OS << " InFlag = Select(" << RootName << OpNo << ");\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002306 } else if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002307 OS << " SDOperand " << RootName << "CR" << i << ";\n";
2308 OS << " " << RootName << "CR" << i
2309 << " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
2310 << ISE.getQualifiedName(RR) << ", MVT::"
2311 << getEnumName(RVT) << ")"
2312 << ", Select(" << RootName << OpNo << "), InFlag);\n";
2313 OS << " Chain = " << RootName << "CR" << i
2314 << ".getValue(0);\n";
2315 OS << " InFlag = " << RootName << "CR" << i
2316 << ".getValue(1);\n";
2317 } else {
2318 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
2319 << ", CurDAG->getRegister(" << ISE.getQualifiedName(RR)
2320 << ", MVT::" << getEnumName(RVT) << ")"
2321 << ", Select(" << RootName << OpNo
2322 << "), InFlag).getValue(1);\n";
2323 }
2324 }
2325 }
2326 }
2327 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002328
2329 if (isRoot && HasInFlag) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002330 OS << " SDOperand " << RootName << OpNo << " = " << RootName
Evan Cheng7b05bd52005-12-23 22:11:47 +00002331 << ".getOperand(" << OpNo << ");\n";
2332 OS << " InFlag = Select(" << RootName << OpNo << ");\n";
2333 }
Evan Chengb915f312005-12-09 22:45:35 +00002334 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002335
2336 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002337 /// as specified by the instruction. It returns true if any copy is
2338 /// emitted.
2339 bool EmitCopyFromRegs(TreePatternNode *N, bool HasChain) {
2340 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002341 Record *Op = N->getOperator();
2342 if (Op->isSubClassOf("Instruction")) {
2343 const DAGInstruction &Inst = ISE.getInstruction(Op);
2344 const CodeGenTarget &CGT = ISE.getTargetInfo();
2345 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2346 unsigned NumImpResults = Inst.getNumImpResults();
2347 for (unsigned i = 0; i < NumImpResults; i++) {
2348 Record *RR = Inst.getImpResult(i);
2349 if (RR->isSubClassOf("Register")) {
2350 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2351 if (RVT != MVT::Flag) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002352 if (HasChain) {
Evan Cheng4fba2812005-12-20 07:37:41 +00002353 OS << " Result = CurDAG->getCopyFromReg(Chain, "
2354 << ISE.getQualifiedName(RR)
2355 << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2356 OS << " Chain = Result.getValue(1);\n";
2357 OS << " InFlag = Result.getValue(2);\n";
2358 } else {
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002359 OS << " Chain;\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002360 OS << " Result = CurDAG->getCopyFromReg("
2361 << "CurDAG->getEntryNode(), ISE.getQualifiedName(RR)"
2362 << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2363 OS << " Chain = Result.getValue(1);\n";
2364 OS << " InFlag = Result.getValue(2);\n";
2365 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002366 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002367 }
2368 }
2369 }
2370 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002371 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002372 }
Evan Chengb915f312005-12-09 22:45:35 +00002373};
2374
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002375/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2376/// stream to match the pattern, and generate the code for the match if it
2377/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00002378void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2379 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002380 static unsigned PatternCount = 0;
2381 unsigned PatternNo = PatternCount++;
2382 OS << " { // Pattern #" << PatternNo << ": ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002383 Pattern.getSrcPattern()->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00002384 OS << "\n // Emits: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002385 Pattern.getDstPattern()->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00002386 OS << "\n";
Evan Cheng58e84a62005-12-14 22:02:59 +00002387 OS << " // Pattern complexity = "
2388 << getPatternSize(Pattern.getSrcPattern(), *this)
2389 << " cost = "
2390 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002391
Evan Cheng58e84a62005-12-14 22:02:59 +00002392 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2393 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2394 PatternNo, OS);
Evan Chengb915f312005-12-09 22:45:35 +00002395
Chris Lattner8fc35682005-09-23 23:16:51 +00002396 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002397 bool FoundChain = false;
2398 Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", FoundChain,
2399 true /*the root*/);
Evan Chengb915f312005-12-09 22:45:35 +00002400
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002401 // TP - Get *SOME* tree pattern, we don't care which.
2402 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002403
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002404 // At this point, we know that we structurally match the pattern, but the
2405 // types of the nodes may not match. Figure out the fewest number of type
2406 // comparisons we need to emit. For example, if there is only one integer
2407 // type supported by a target, there should be no type comparisons at all for
2408 // integer patterns!
2409 //
2410 // To figure out the fewest number of type checks needed, clone the pattern,
2411 // remove the types, then perform type inference on the pattern as a whole.
2412 // If there are unresolved types, emit an explicit check for those types,
2413 // apply the type to the tree, then rerun type inference. Iterate until all
2414 // types are resolved.
2415 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002416 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002417 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002418
2419 do {
2420 // Resolve/propagate as many types as possible.
2421 try {
2422 bool MadeChange = true;
2423 while (MadeChange)
2424 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2425 } catch (...) {
2426 assert(0 && "Error: could not find consistent types for something we"
2427 " already decided was ok!");
2428 abort();
2429 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002430
Chris Lattner7e82f132005-10-15 21:34:21 +00002431 // Insert a check for an unresolved type and add it to the tree. If we find
2432 // an unresolved type to add a check for, this returns true and we iterate,
2433 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002434 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002435
Evan Cheng58e84a62005-12-14 22:02:59 +00002436 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
Evan Chengb915f312005-12-09 22:45:35 +00002437
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002438 delete Pat;
2439
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002440 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002441}
2442
Chris Lattner37481472005-09-26 21:59:35 +00002443
2444namespace {
2445 /// CompareByRecordName - An ordering predicate that implements less-than by
2446 /// comparing the names records.
2447 struct CompareByRecordName {
2448 bool operator()(const Record *LHS, const Record *RHS) const {
2449 // Sort by name first.
2450 if (LHS->getName() < RHS->getName()) return true;
2451 // If both names are equal, sort by pointer.
2452 return LHS->getName() == RHS->getName() && LHS < RHS;
2453 }
2454 };
2455}
2456
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002457void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002458 std::string InstNS = Target.inst_begin()->second.Namespace;
2459 if (!InstNS.empty()) InstNS += "::";
2460
Chris Lattner602f6922006-01-04 00:25:00 +00002461 // Group the patterns by their top-level opcodes.
2462 std::map<Record*, std::vector<PatternToMatch*>,
2463 CompareByRecordName> PatternsByOpcode;
2464 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2465 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2466 if (!Node->isLeaf()) {
2467 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2468 } else {
2469 const ComplexPattern *CP;
2470 if (IntInit *II =
2471 dynamic_cast<IntInit*>(Node->getLeafValue())) {
2472 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2473 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2474 std::vector<Record*> OpNodes = CP->getRootNodes();
2475 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2476 PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2477 &PatternsToMatch[i]);
2478 }
2479 } else {
2480 std::cerr << "Unrecognized opcode '";
2481 Node->dump();
2482 std::cerr << "' on tree pattern '";
2483 std::cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
2484 std::cerr << "'!\n";
2485 exit(1);
2486 }
2487 }
2488 }
2489
2490 // Emit one Select_* method for each top-level opcode. We do this instead of
2491 // emitting one giant switch statement to support compilers where this will
2492 // result in the recursive functions taking less stack space.
2493 for (std::map<Record*, std::vector<PatternToMatch*>,
2494 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2495 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2496 OS << "SDOperand Select_" << PBOI->first->getName() << "(SDOperand N) {\n";
2497
2498 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2499 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2500
2501 // We want to emit all of the matching code now. However, we want to emit
2502 // the matches in order of minimal cost. Sort the patterns so the least
2503 // cost one is at the start.
2504 std::stable_sort(Patterns.begin(), Patterns.end(),
2505 PatternSortingPredicate(*this));
2506
2507 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2508 EmitCodeForPattern(*Patterns[i], OS);
2509
2510 OS << " std::cerr << \"Cannot yet select: \";\n"
2511 << " N.Val->dump(CurDAG);\n"
2512 << " std::cerr << '\\n';\n"
2513 << " abort();\n"
2514 << "}\n\n";
2515 }
2516
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002517 // Emit boilerplate.
2518 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002519 << "SDOperand SelectCode(SDOperand N) {\n"
2520 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002521 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2522 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002523 << " return N; // Already selected.\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002524 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng481c8e02005-12-12 23:22:48 +00002525 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002526 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002527 << " default: break;\n"
2528 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00002529 << " case ISD::BasicBlock:\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002530 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002531 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002532 << " case ISD::AssertZext: {\n"
2533 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2534 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2535 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002536 << " }\n"
2537 << " case ISD::TokenFactor:\n"
2538 << " if (N.getNumOperands() == 2) {\n"
2539 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2540 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2541 << " return CodeGenMap[N] =\n"
2542 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2543 << " } else {\n"
2544 << " std::vector<SDOperand> Ops;\n"
2545 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2546 << " Ops.push_back(Select(N.getOperand(i)));\n"
2547 << " return CodeGenMap[N] = \n"
2548 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2549 << " }\n"
2550 << " case ISD::CopyFromReg: {\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002551 << " SDOperand Chain = Select(N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002552 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2553 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002554 << " if (N.Val->getNumValues() == 2) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002555 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2556 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
2557 << " CodeGenMap[N.getValue(0)] = New;\n"
2558 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2559 << " return New.getValue(N.ResNo);\n"
2560 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00002561 << " SDOperand Flag(0, 0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002562 << " if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
2563 << " if (Chain == N.getOperand(0) &&\n"
2564 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002565 << " return N; // No change\n"
2566 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
2567 << " CodeGenMap[N.getValue(0)] = New;\n"
2568 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2569 << " CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
2570 << " return New.getValue(N.ResNo);\n"
2571 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002572 << " }\n"
2573 << " case ISD::CopyToReg: {\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002574 << " SDOperand Chain = Select(N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002575 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002576 << " SDOperand Val = Select(N.getOperand(2));\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002577 << " SDOperand Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002578 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002579 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002580 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002581 << " return CodeGenMap[N] = Result;\n"
2582 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00002583 << " SDOperand Flag(0, 0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002584 << " if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002585 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002586 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
2587 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002588 << " CodeGenMap[N.getValue(0)] = Result;\n"
2589 << " CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
2590 << " return Result.getValue(N.ResNo);\n"
2591 << " }\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002592 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002593
Chris Lattner602f6922006-01-04 00:25:00 +00002594 // Loop over all of the case statements, emiting a call to each method we
2595 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00002596 for (std::map<Record*, std::vector<PatternToMatch*>,
2597 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2598 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00002599 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00002600 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00002601 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Chris Lattner602f6922006-01-04 00:25:00 +00002602 << "return Select_" << PBOI->first->getName() << "(N);\n";
Chris Lattner81303322005-09-23 19:36:15 +00002603 }
Chris Lattner81303322005-09-23 19:36:15 +00002604
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002605 OS << " } // end of big switch.\n\n"
2606 << " std::cerr << \"Cannot yet select: \";\n"
Evan Cheng97938882005-12-22 02:24:50 +00002607 << " N.Val->dump(CurDAG);\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002608 << " std::cerr << '\\n';\n"
2609 << " abort();\n"
2610 << "}\n";
2611}
2612
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002613void DAGISelEmitter::run(std::ostream &OS) {
2614 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2615 " target", OS);
2616
Chris Lattner1f39e292005-09-14 00:09:24 +00002617 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2618 << "// *** instruction selector class. These functions are really "
2619 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002620
Chris Lattner296dfe32005-09-24 00:50:51 +00002621 OS << "// Instance var to keep track of multiply used nodes that have \n"
2622 << "// already been selected.\n"
2623 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2624
Chris Lattnerca559d02005-09-08 21:03:01 +00002625 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00002626 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00002627 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002628 ParsePatternFragments(OS);
2629 ParseInstructions();
2630 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00002631
Chris Lattnere97603f2005-09-28 19:27:25 +00002632 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00002633 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00002634 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002635
Chris Lattnere46e17b2005-09-29 19:28:10 +00002636
2637 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2638 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002639 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
2640 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00002641 std::cerr << "\n";
2642 });
2643
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002644 // At this point, we have full information about the 'Patterns' we need to
2645 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002646 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002647 EmitInstructionSelector(OS);
2648
2649 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2650 E = PatternFragments.end(); I != E; ++I)
2651 delete I->second;
2652 PatternFragments.clear();
2653
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002654 Instructions.clear();
2655}