blob: 1d8e645e937632e3b042607914a5c73750cb5df4 [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) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001694 assert(isExtIntegerInVTs(P->getExtTypes()) ||
1695 isExtFloatingPointInVTs(P->getExtTypes()) ||
1696 P->getExtTypeNum(0) == MVT::isVoid ||
1697 P->getExtTypeNum(0) == MVT::Flag &&
1698 "Not a valid pattern node to size!");
Chris Lattner05814af2005-09-28 17:57:56 +00001699 unsigned Size = 1; // The node itself.
Evan Cheng0fc71982005-12-08 02:00:36 +00001700
1701 // FIXME: This is a hack to statically increase the priority of patterns
1702 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1703 // Later we can allow complexity / cost for each pattern to be (optionally)
1704 // specified. To get best possible pattern match we'll need to dynamically
1705 // calculate the complexity of all patterns a dag can potentially map to.
1706 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1707 if (AM)
1708 Size += AM->getNumOperands();
1709
Chris Lattner05814af2005-09-28 17:57:56 +00001710 // Count children in the count if they are also nodes.
1711 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1712 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001713 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001714 Size += getPatternSize(Child, ISE);
1715 else if (Child->isLeaf()) {
1716 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1717 ++Size; // Matches a ConstantSDNode.
1718 else if (NodeIsComplexPattern(Child))
1719 Size += getPatternSize(Child, ISE);
Chris Lattner2f041d42005-10-19 04:41:05 +00001720 }
Chris Lattner05814af2005-09-28 17:57:56 +00001721 }
1722
1723 return Size;
1724}
1725
1726/// getResultPatternCost - Compute the number of instructions for this pattern.
1727/// This is a temporary hack. We should really include the instruction
1728/// latencies in this calculation.
1729static unsigned getResultPatternCost(TreePatternNode *P) {
1730 if (P->isLeaf()) return 0;
1731
1732 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1733 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1734 Cost += getResultPatternCost(P->getChild(i));
1735 return Cost;
1736}
1737
1738// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1739// In particular, we want to match maximal patterns first and lowest cost within
1740// a particular complexity first.
1741struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001742 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1743 DAGISelEmitter &ISE;
1744
Evan Cheng58e84a62005-12-14 22:02:59 +00001745 bool operator()(PatternToMatch *LHS,
1746 PatternToMatch *RHS) {
1747 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1748 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001749 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1750 if (LHSSize < RHSSize) return false;
1751
1752 // If the patterns have equal complexity, compare generated instruction cost
Evan Cheng58e84a62005-12-14 22:02:59 +00001753 return getResultPatternCost(LHS->getDstPattern()) <
1754 getResultPatternCost(RHS->getDstPattern());
Chris Lattner05814af2005-09-28 17:57:56 +00001755 }
1756};
1757
Nate Begeman6510b222005-12-01 04:51:06 +00001758/// getRegisterValueType - Look up and return the first ValueType of specified
1759/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001760static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001761 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1762 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001763 return MVT::Other;
1764}
1765
Chris Lattner72fe91c2005-09-24 00:40:24 +00001766
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001767/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1768/// type information from it.
1769static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001770 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001771 if (!N->isLeaf())
1772 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1773 RemoveAllTypes(N->getChild(i));
1774}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001775
Chris Lattner0614b622005-11-02 06:49:14 +00001776Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1777 Record *N = Records.getDef(Name);
1778 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1779 return N;
1780}
1781
Evan Cheng7b05bd52005-12-23 22:11:47 +00001782/// NodeHasChain - return true if TreePatternNode has the property
1783/// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1784/// a chain result.
1785static bool NodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1786{
1787 if (N->isLeaf()) return false;
1788 Record *Operator = N->getOperator();
1789 if (!Operator->isSubClassOf("SDNode")) return false;
1790
1791 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1792 return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1793}
1794
1795static bool PatternHasCtrlDep(TreePatternNode *N, DAGISelEmitter &ISE)
1796{
1797 if (NodeHasChain(N, ISE))
1798 return true;
1799 else {
1800 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1801 TreePatternNode *Child = N->getChild(i);
1802 if (PatternHasCtrlDep(Child, ISE))
1803 return true;
1804 }
1805 }
1806
1807 return false;
1808}
1809
Evan Chengb915f312005-12-09 22:45:35 +00001810class PatternCodeEmitter {
1811private:
1812 DAGISelEmitter &ISE;
1813
Evan Cheng58e84a62005-12-14 22:02:59 +00001814 // Predicates.
1815 ListInit *Predicates;
1816 // Instruction selector pattern.
1817 TreePatternNode *Pattern;
1818 // Matched instruction.
1819 TreePatternNode *Instruction;
Evan Chengb915f312005-12-09 22:45:35 +00001820 unsigned PatternNo;
1821 std::ostream &OS;
1822 // Node to name mapping
1823 std::map<std::string,std::string> VariableMap;
Evan Chengb915f312005-12-09 22:45:35 +00001824 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001825 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb915f312005-12-09 22:45:35 +00001826 unsigned TmpNo;
1827
1828public:
Evan Cheng58e84a62005-12-14 22:02:59 +00001829 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1830 TreePatternNode *pattern, TreePatternNode *instr,
Evan Chengb915f312005-12-09 22:45:35 +00001831 unsigned PatNum, std::ostream &os) :
Evan Cheng58e84a62005-12-14 22:02:59 +00001832 ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001833 PatternNo(PatNum), OS(os), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00001834
1835 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1836 /// if the match fails. At this point, we already know that the opcode for N
1837 /// matches, and the SDNode for the result has the RootName specified name.
1838 void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001839 bool &FoundChain, bool isRoot = false) {
Evan Cheng58e84a62005-12-14 22:02:59 +00001840
1841 // Emit instruction predicates. Each predicate is just a string for now.
1842 if (isRoot) {
1843 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1844 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1845 Record *Def = Pred->getDef();
1846 if (Def->isSubClassOf("Predicate")) {
1847 if (i == 0)
1848 OS << " if (";
1849 else
1850 OS << " && ";
Evan Cheng5fb5e102005-12-20 20:08:01 +00001851 OS << "!(" << Def->getValueAsString("CondString") << ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00001852 if (i == e-1)
1853 OS << ") goto P" << PatternNo << "Fail;\n";
1854 } else {
1855 Def->dump();
1856 assert(0 && "Unknown predicate type!");
1857 }
1858 }
1859 }
1860 }
1861
Evan Chengb915f312005-12-09 22:45:35 +00001862 if (N->isLeaf()) {
1863 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1864 OS << " if (cast<ConstantSDNode>(" << RootName
1865 << ")->getSignExtended() != " << II->getValue() << ")\n"
1866 << " goto P" << PatternNo << "Fail;\n";
1867 return;
1868 } else if (!NodeIsComplexPattern(N)) {
1869 assert(0 && "Cannot match this as a leaf value!");
1870 abort();
1871 }
1872 }
1873
1874 // If this node has a name associated with it, capture it in VariableMap. If
1875 // we already saw this in the pattern, emit code to verify dagness.
1876 if (!N->getName().empty()) {
1877 std::string &VarMapEntry = VariableMap[N->getName()];
1878 if (VarMapEntry.empty()) {
1879 VarMapEntry = RootName;
1880 } else {
1881 // If we get here, this is a second reference to a specific name. Since
1882 // we already have checked that the first reference is valid, we don't
1883 // have to recursively match it, just check that it's the same as the
1884 // previously named thing.
1885 OS << " if (" << VarMapEntry << " != " << RootName
1886 << ") goto P" << PatternNo << "Fail;\n";
1887 return;
1888 }
1889 }
1890
1891
1892 // Emit code to load the child nodes and match their contents recursively.
1893 unsigned OpNo = 0;
Evan Cheng86217892005-12-12 19:37:43 +00001894 bool HasChain = NodeHasChain(N, ISE);
1895 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00001896 OpNo = 1;
1897 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00001898 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Evan Chengb915f312005-12-09 22:45:35 +00001899 OS << " if (!" << RootName << ".hasOneUse()) goto P"
1900 << PatternNo << "Fail; // Multiple uses of actual result?\n";
1901 OS << " if (CodeGenMap.count(" << RootName
Evan Cheng1129e872005-12-10 00:09:17 +00001902 << ".getValue(" << CInfo.getNumResults() << "))) goto P"
Evan Chengb915f312005-12-09 22:45:35 +00001903 << PatternNo << "Fail; // Already selected for a chain use?\n";
1904 }
Evan Cheng1cf6db22006-01-06 00:41:12 +00001905 if (!FoundChain) {
1906 OS << " SDOperand Chain = " << RootName << ".getOperand(0);\n";
1907 FoundChain = true;
1908 }
Evan Chengb915f312005-12-09 22:45:35 +00001909 }
1910
1911 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00001912 OS << " SDOperand " << RootName << OpNo << " = "
1913 << RootName << ".getOperand(" << OpNo << ");\n";
Evan Chengb915f312005-12-09 22:45:35 +00001914 TreePatternNode *Child = N->getChild(i);
1915
1916 if (!Child->isLeaf()) {
1917 // If it's not a leaf, recursively match.
1918 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1919 OS << " if (" << RootName << OpNo << ".getOpcode() != "
1920 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00001921 EmitMatchCode(Child, RootName + utostr(OpNo), FoundChain);
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001922 if (NodeHasChain(Child, ISE)) {
1923 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
1924 CInfo.getNumResults()));
1925 }
Evan Chengb915f312005-12-09 22:45:35 +00001926 } else {
1927 // If this child has a name associated with it, capture it in VarMap. If
1928 // we already saw this in the pattern, emit code to verify dagness.
1929 if (!Child->getName().empty()) {
1930 std::string &VarMapEntry = VariableMap[Child->getName()];
1931 if (VarMapEntry.empty()) {
1932 VarMapEntry = RootName + utostr(OpNo);
1933 } else {
1934 // If we get here, this is a second reference to a specific name. Since
1935 // we already have checked that the first reference is valid, we don't
1936 // have to recursively match it, just check that it's the same as the
1937 // previously named thing.
1938 OS << " if (" << VarMapEntry << " != " << RootName << OpNo
1939 << ") goto P" << PatternNo << "Fail;\n";
1940 continue;
1941 }
1942 }
1943
1944 // Handle leaves of various types.
1945 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1946 Record *LeafRec = DI->getDef();
1947 if (LeafRec->isSubClassOf("RegisterClass")) {
1948 // Handle register references. Nothing to do here.
1949 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00001950 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00001951 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1952 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00001953 } else if (LeafRec->getName() == "srcvalue") {
1954 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00001955 } else if (LeafRec->isSubClassOf("ValueType")) {
1956 // Make sure this is the specified value type.
1957 OS << " if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
1958 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1959 << "Fail;\n";
1960 } else if (LeafRec->isSubClassOf("CondCode")) {
1961 // Make sure this is the specified cond code.
1962 OS << " if (cast<CondCodeSDNode>(" << RootName << OpNo
1963 << ")->get() != " << "ISD::" << LeafRec->getName()
1964 << ") goto P" << PatternNo << "Fail;\n";
1965 } else {
1966 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00001967 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00001968 assert(0 && "Unknown leaf type!");
1969 }
1970 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1971 OS << " if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1972 << " cast<ConstantSDNode>(" << RootName << OpNo
1973 << ")->getSignExtended() != " << II->getValue() << ")\n"
1974 << " goto P" << PatternNo << "Fail;\n";
1975 } else {
1976 Child->dump();
1977 assert(0 && "Unknown leaf type!");
1978 }
1979 }
1980 }
1981
1982 // If there is a node predicate for this, emit the call.
1983 if (!N->getPredicateFn().empty())
1984 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1985 << ".Val)) goto P" << PatternNo << "Fail;\n";
1986 }
1987
1988 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
1989 /// we actually have to build a DAG!
1990 std::pair<unsigned, unsigned>
1991 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
1992 // This is something selected from the pattern we matched.
1993 if (!N->getName().empty()) {
1994 assert(!isRoot && "Root of pattern cannot be a leaf!");
1995 std::string &Val = VariableMap[N->getName()];
1996 assert(!Val.empty() &&
1997 "Variable referenced but not defined and not caught earlier!");
1998 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1999 // Already selected this operand, just return the tmpval.
2000 return std::make_pair(1, atoi(Val.c_str()+3));
2001 }
2002
2003 const ComplexPattern *CP;
2004 unsigned ResNo = TmpNo++;
2005 unsigned NumRes = 1;
2006 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002007 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2008 switch (N->getTypeNum(0)) {
Evan Chengb915f312005-12-09 22:45:35 +00002009 default: assert(0 && "Unknown type for constant node!");
2010 case MVT::i1: OS << " bool Tmp"; break;
2011 case MVT::i8: OS << " unsigned char Tmp"; break;
2012 case MVT::i16: OS << " unsigned short Tmp"; break;
2013 case MVT::i32: OS << " unsigned Tmp"; break;
2014 case MVT::i64: OS << " uint64_t Tmp"; break;
2015 }
2016 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002017 OS << " SDOperand Tmp" << utostr(ResNo)
2018 << " = CurDAG->getTargetConstant(Tmp"
Nate Begemanb73628b2005-12-30 00:12:56 +00002019 << ResNo << "C, MVT::" << getEnumName(N->getTypeNum(0)) << ");\n";
Evan Chengb915f312005-12-09 22:45:35 +00002020 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002021 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Nate Begeman28a6b022005-12-10 02:36:00 +00002022 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002023 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
2024 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2025 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Evan Chengb915f312005-12-09 22:45:35 +00002026 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2027 std::string Fn = CP->getSelectFunc();
2028 NumRes = CP->getNumOperands();
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002029 OS << " SDOperand ";
Jeff Cohen60e91872006-01-04 03:23:30 +00002030 for (unsigned i = 0; i < NumRes - 1; ++i)
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002031 OS << "Tmp" << (i+ResNo) << ",";
Jeff Cohen60e91872006-01-04 03:23:30 +00002032 OS << "Tmp" << (NumRes - 1 + ResNo) << ";\n";
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002033
Evan Chengb915f312005-12-09 22:45:35 +00002034 OS << " if (!" << Fn << "(" << Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002035 for (unsigned i = 0; i < NumRes; i++)
Evan Chengbcecf332005-12-17 01:19:28 +00002036 OS << ", Tmp" << i + ResNo;
Evan Chengb915f312005-12-09 22:45:35 +00002037 OS << ")) goto P" << PatternNo << "Fail;\n";
2038 TmpNo = ResNo + NumRes;
2039 } else {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002040 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
Evan Chengb915f312005-12-09 22:45:35 +00002041 }
2042 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2043 // value if used multiple times by this pattern result.
2044 Val = "Tmp"+utostr(ResNo);
2045 return std::make_pair(NumRes, ResNo);
2046 }
2047
2048 if (N->isLeaf()) {
2049 // If this is an explicit register reference, handle it.
2050 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2051 unsigned ResNo = TmpNo++;
2052 if (DI->getDef()->isSubClassOf("Register")) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002053 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
Evan Chengb915f312005-12-09 22:45:35 +00002054 << ISE.getQualifiedName(DI->getDef()) << ", MVT::"
Nate Begemanb73628b2005-12-30 00:12:56 +00002055 << getEnumName(N->getTypeNum(0))
Evan Chengb915f312005-12-09 22:45:35 +00002056 << ");\n";
2057 return std::make_pair(1, ResNo);
2058 }
2059 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2060 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002061 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002062 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
Evan Chengb915f312005-12-09 22:45:35 +00002063 << II->getValue() << ", MVT::"
Nate Begemanb73628b2005-12-30 00:12:56 +00002064 << getEnumName(N->getTypeNum(0))
Evan Chengb915f312005-12-09 22:45:35 +00002065 << ");\n";
2066 return std::make_pair(1, ResNo);
2067 }
2068
2069 N->dump();
2070 assert(0 && "Unknown leaf type!");
2071 return std::make_pair(1, ~0U);
2072 }
2073
2074 Record *Op = N->getOperator();
2075 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002076 const CodeGenTarget &CGT = ISE.getTargetInfo();
2077 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002078 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002079 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2080 bool HasImpResults = Inst.getNumImpResults() > 0;
2081 bool HasInFlag = II.hasInFlag || HasImpInputs;
2082 bool HasOutFlag = II.hasOutFlag || HasImpResults;
2083 bool HasChain = II.hasCtrlDep;
Evan Cheng4fba2812005-12-20 07:37:41 +00002084
Evan Cheng7b05bd52005-12-23 22:11:47 +00002085 if (isRoot && PatternHasCtrlDep(Pattern, ISE))
2086 HasChain = true;
2087 if (HasInFlag || HasOutFlag)
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002088 OS << " SDOperand InFlag = SDOperand(0, 0);\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002089
Evan Chengb915f312005-12-09 22:45:35 +00002090 // Determine operand emission order. Complex pattern first.
2091 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2092 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2093 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2094 TreePatternNode *Child = N->getChild(i);
2095 if (i == 0) {
2096 EmitOrder.push_back(std::make_pair(i, Child));
2097 OI = EmitOrder.begin();
2098 } else if (NodeIsComplexPattern(Child)) {
2099 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2100 } else {
2101 EmitOrder.push_back(std::make_pair(i, Child));
2102 }
2103 }
2104
2105 // Emit all of the operands.
2106 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2107 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2108 unsigned OpOrder = EmitOrder[i].first;
2109 TreePatternNode *Child = EmitOrder[i].second;
2110 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2111 NumTemps[OpOrder] = NumTemp;
2112 }
2113
2114 // List all the operands in the right order.
2115 std::vector<unsigned> Ops;
2116 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2117 for (unsigned j = 0; j < NumTemps[i].first; j++)
2118 Ops.push_back(NumTemps[i].second + j);
2119 }
2120
Evan Chengb915f312005-12-09 22:45:35 +00002121 // Emit all the chain and CopyToReg stuff.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002122 if (HasChain)
Evan Cheng86217892005-12-12 19:37:43 +00002123 OS << " Chain = Select(Chain);\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002124 if (HasInFlag)
2125 EmitInFlags(Pattern, "N", HasChain, II.hasInFlag, true);
Evan Chengb915f312005-12-09 22:45:35 +00002126
Evan Chengb915f312005-12-09 22:45:35 +00002127 unsigned NumResults = Inst.getNumResults();
2128 unsigned ResNo = TmpNo++;
2129 if (!isRoot) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002130 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
Evan Chengbcecf332005-12-17 01:19:28 +00002131 << II.Namespace << "::" << II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002132 if (N->getTypeNum(0) != MVT::isVoid)
2133 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
Evan Cheng7b05bd52005-12-23 22:11:47 +00002134 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002135 OS << ", MVT::Flag";
Evan Chengbcecf332005-12-17 01:19:28 +00002136
Evan Chengb915f312005-12-09 22:45:35 +00002137 unsigned LastOp = 0;
2138 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2139 LastOp = Ops[i];
2140 OS << ", Tmp" << LastOp;
2141 }
2142 OS << ");\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002143 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002144 // Must have at least one result
2145 OS << " Chain = Tmp" << LastOp << ".getValue("
2146 << NumResults << ");\n";
2147 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002148 } else if (HasChain || HasOutFlag) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002149 OS << " SDOperand Result = CurDAG->getTargetNode("
Evan Chengb915f312005-12-09 22:45:35 +00002150 << II.Namespace << "::" << II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002151
2152 // Output order: results, chain, flags
2153 // Result types.
Evan Chengbcecf332005-12-17 01:19:28 +00002154 if (NumResults > 0) {
Nate Begemanb73628b2005-12-30 00:12:56 +00002155 if (N->getTypeNum(0) != MVT::isVoid)
2156 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
Evan Chengbcecf332005-12-17 01:19:28 +00002157 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002158 if (HasChain)
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002159 OS << ", MVT::Other";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002160 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002161 OS << ", MVT::Flag";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002162
2163 // Inputs.
Evan Chengb915f312005-12-09 22:45:35 +00002164 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2165 OS << ", Tmp" << Ops[i];
Evan Cheng7b05bd52005-12-23 22:11:47 +00002166 if (HasChain) OS << ", Chain";
2167 if (HasInFlag) OS << ", InFlag";
Evan Chengb915f312005-12-09 22:45:35 +00002168 OS << ");\n";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002169
2170 unsigned ValNo = 0;
Evan Chengf9fc25d2005-12-19 22:40:04 +00002171 for (unsigned i = 0; i < NumResults; i++) {
2172 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = Result"
2173 << ".getValue(" << ValNo << ");\n";
2174 ValNo++;
2175 }
2176
Evan Cheng7b05bd52005-12-23 22:11:47 +00002177 if (HasChain)
Evan Cheng4fba2812005-12-20 07:37:41 +00002178 OS << " Chain = Result.getValue(" << ValNo << ");\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002179
Evan Cheng7b05bd52005-12-23 22:11:47 +00002180 if (HasOutFlag)
Evan Cheng97938882005-12-22 02:24:50 +00002181 OS << " InFlag = Result.getValue("
Evan Cheng7b05bd52005-12-23 22:11:47 +00002182 << ValNo + (unsigned)HasChain << ");\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002183
Evan Cheng7b05bd52005-12-23 22:11:47 +00002184 if (HasImpResults) {
2185 if (EmitCopyFromRegs(N, HasChain)) {
Evan Cheng97938882005-12-22 02:24:50 +00002186 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = "
2187 << "Result.getValue(" << ValNo << ");\n";
2188 ValNo++;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002189 HasChain = true;
Evan Cheng97938882005-12-22 02:24:50 +00002190 }
2191 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002192
Evan Cheng7b05bd52005-12-23 22:11:47 +00002193 // User does not expect that the instruction produces a chain!
2194 bool AddedChain = HasChain && !NodeHasChain(Pattern, ISE);
Evan Cheng97938882005-12-22 02:24:50 +00002195 if (NodeHasChain(Pattern, ISE))
2196 OS << " CodeGenMap[N.getValue(" << ValNo++ << ")] = Chain;\n";
2197
2198 if (FoldedChains.size() > 0) {
Evan Cheng4fba2812005-12-20 07:37:41 +00002199 OS << " ";
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002200 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng4fba2812005-12-20 07:37:41 +00002201 OS << "CodeGenMap[" << FoldedChains[j].first << ".getValue("
2202 << FoldedChains[j].second << ")] = ";
2203 OS << "Chain;\n";
Evan Chengb915f312005-12-09 22:45:35 +00002204 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002205
Evan Cheng7b05bd52005-12-23 22:11:47 +00002206 if (HasOutFlag)
Evan Cheng97938882005-12-22 02:24:50 +00002207 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = InFlag;\n";
2208
Evan Cheng7b05bd52005-12-23 22:11:47 +00002209 if (AddedChain && HasOutFlag) {
Evan Cheng97938882005-12-22 02:24:50 +00002210 if (NumResults == 0) {
2211 OS << " return Result.getValue(N.ResNo+1);\n";
2212 } else {
2213 OS << " if (N.ResNo < " << NumResults << ")\n";
2214 OS << " return Result.getValue(N.ResNo);\n";
2215 OS << " else\n";
2216 OS << " return Result.getValue(N.ResNo+1);\n";
2217 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002218 } else {
Evan Chenge0870512005-12-20 00:06:17 +00002219 OS << " return Result.getValue(N.ResNo);\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002220 }
Evan Chengb915f312005-12-09 22:45:35 +00002221 } else {
2222 // If this instruction is the root, and if there is only one use of it,
2223 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2224 OS << " if (N.Val->hasOneUse()) {\n";
2225 OS << " return CurDAG->SelectNodeTo(N.Val, "
Evan Chengbcecf332005-12-17 01:19:28 +00002226 << II.Namespace << "::" << II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002227 if (N->getTypeNum(0) != MVT::isVoid)
2228 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
Evan Cheng7b05bd52005-12-23 22:11:47 +00002229 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002230 OS << ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002231 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2232 OS << ", Tmp" << Ops[i];
Evan Cheng7b05bd52005-12-23 22:11:47 +00002233 if (HasInFlag)
Evan Chengb915f312005-12-09 22:45:35 +00002234 OS << ", InFlag";
2235 OS << ");\n";
2236 OS << " } else {\n";
2237 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
Evan Chengbcecf332005-12-17 01:19:28 +00002238 << II.Namespace << "::" << II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002239 if (N->getTypeNum(0) != MVT::isVoid)
2240 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
Evan Cheng7b05bd52005-12-23 22:11:47 +00002241 if (HasOutFlag)
Evan Cheng4fba2812005-12-20 07:37:41 +00002242 OS << ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002243 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2244 OS << ", Tmp" << Ops[i];
Evan Cheng7b05bd52005-12-23 22:11:47 +00002245 if (HasInFlag)
Evan Chengb915f312005-12-09 22:45:35 +00002246 OS << ", InFlag";
2247 OS << ");\n";
2248 OS << " }\n";
2249 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002250
Evan Chengb915f312005-12-09 22:45:35 +00002251 return std::make_pair(1, ResNo);
2252 } else if (Op->isSubClassOf("SDNodeXForm")) {
2253 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng58e84a62005-12-14 22:02:59 +00002254 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
Evan Chengb915f312005-12-09 22:45:35 +00002255 unsigned ResNo = TmpNo++;
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002256 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
Evan Chengb915f312005-12-09 22:45:35 +00002257 << "(Tmp" << OpVal << ".Val);\n";
2258 if (isRoot) {
2259 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
2260 OS << " return Tmp" << ResNo << ";\n";
2261 }
2262 return std::make_pair(1, ResNo);
2263 } else {
2264 N->dump();
2265 assert(0 && "Unknown node in result pattern!");
2266 return std::make_pair(1, ~0U);
2267 }
2268 }
2269
2270 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2271 /// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2272 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2273 /// for, this returns true otherwise false if Pat has all types.
2274 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2275 const std::string &Prefix) {
2276 // Did we find one?
2277 if (!Pat->hasTypeSet()) {
2278 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002279 Pat->setTypes(Other->getExtTypes());
Evan Chengb915f312005-12-09 22:45:35 +00002280 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
Nate Begemanb73628b2005-12-30 00:12:56 +00002281 << getName(Pat->getTypeNum(0)) << ") goto P" << PatternNo << "Fail;\n";
Evan Chengb915f312005-12-09 22:45:35 +00002282 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002283 }
2284
2285 unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
2286 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2287 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2288 Prefix + utostr(OpNo)))
2289 return true;
2290 return false;
2291 }
2292
2293private:
Evan Cheng7b05bd52005-12-23 22:11:47 +00002294 /// EmitInFlags - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002295 /// being built.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002296 void EmitInFlags(TreePatternNode *N, const std::string &RootName,
2297 bool HasChain, bool HasInFlag, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002298 const CodeGenTarget &T = ISE.getTargetInfo();
2299 unsigned OpNo = (unsigned) NodeHasChain(N, ISE);
2300 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2301 TreePatternNode *Child = N->getChild(i);
2302 if (!Child->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002303 EmitInFlags(Child, RootName + utostr(OpNo), HasChain, HasInFlag);
Evan Chengb915f312005-12-09 22:45:35 +00002304 } else {
2305 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2306 Record *RR = DI->getDef();
2307 if (RR->isSubClassOf("Register")) {
2308 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002309 if (RVT == MVT::Flag) {
2310 OS << " InFlag = Select(" << RootName << OpNo << ");\n";
Evan Cheng7b05bd52005-12-23 22:11:47 +00002311 } else if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002312 OS << " SDOperand " << RootName << "CR" << i << ";\n";
2313 OS << " " << RootName << "CR" << i
2314 << " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
2315 << ISE.getQualifiedName(RR) << ", MVT::"
2316 << getEnumName(RVT) << ")"
2317 << ", Select(" << RootName << OpNo << "), InFlag);\n";
2318 OS << " Chain = " << RootName << "CR" << i
2319 << ".getValue(0);\n";
2320 OS << " InFlag = " << RootName << "CR" << i
2321 << ".getValue(1);\n";
2322 } else {
2323 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
2324 << ", CurDAG->getRegister(" << ISE.getQualifiedName(RR)
2325 << ", MVT::" << getEnumName(RVT) << ")"
2326 << ", Select(" << RootName << OpNo
2327 << "), InFlag).getValue(1);\n";
2328 }
2329 }
2330 }
2331 }
2332 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002333
2334 if (isRoot && HasInFlag) {
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002335 OS << " SDOperand " << RootName << OpNo << " = " << RootName
Evan Cheng7b05bd52005-12-23 22:11:47 +00002336 << ".getOperand(" << OpNo << ");\n";
2337 OS << " InFlag = Select(" << RootName << OpNo << ");\n";
2338 }
Evan Chengb915f312005-12-09 22:45:35 +00002339 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002340
2341 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002342 /// as specified by the instruction. It returns true if any copy is
2343 /// emitted.
2344 bool EmitCopyFromRegs(TreePatternNode *N, bool HasChain) {
2345 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002346 Record *Op = N->getOperator();
2347 if (Op->isSubClassOf("Instruction")) {
2348 const DAGInstruction &Inst = ISE.getInstruction(Op);
2349 const CodeGenTarget &CGT = ISE.getTargetInfo();
2350 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2351 unsigned NumImpResults = Inst.getNumImpResults();
2352 for (unsigned i = 0; i < NumImpResults; i++) {
2353 Record *RR = Inst.getImpResult(i);
2354 if (RR->isSubClassOf("Register")) {
2355 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2356 if (RVT != MVT::Flag) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002357 if (HasChain) {
Evan Cheng4fba2812005-12-20 07:37:41 +00002358 OS << " Result = CurDAG->getCopyFromReg(Chain, "
2359 << ISE.getQualifiedName(RR)
2360 << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2361 OS << " Chain = Result.getValue(1);\n";
2362 OS << " InFlag = Result.getValue(2);\n";
2363 } else {
Chris Lattner2f0f9a62005-12-20 19:41:03 +00002364 OS << " Chain;\n";
Evan Cheng4fba2812005-12-20 07:37:41 +00002365 OS << " Result = CurDAG->getCopyFromReg("
2366 << "CurDAG->getEntryNode(), ISE.getQualifiedName(RR)"
2367 << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2368 OS << " Chain = Result.getValue(1);\n";
2369 OS << " InFlag = Result.getValue(2);\n";
2370 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002371 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002372 }
2373 }
2374 }
2375 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002376 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002377 }
Evan Chengb915f312005-12-09 22:45:35 +00002378};
2379
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002380/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2381/// stream to match the pattern, and generate the code for the match if it
2382/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00002383void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2384 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002385 static unsigned PatternCount = 0;
2386 unsigned PatternNo = PatternCount++;
2387 OS << " { // Pattern #" << PatternNo << ": ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002388 Pattern.getSrcPattern()->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00002389 OS << "\n // Emits: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00002390 Pattern.getDstPattern()->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00002391 OS << "\n";
Evan Cheng58e84a62005-12-14 22:02:59 +00002392 OS << " // Pattern complexity = "
2393 << getPatternSize(Pattern.getSrcPattern(), *this)
2394 << " cost = "
2395 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002396
Evan Cheng58e84a62005-12-14 22:02:59 +00002397 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2398 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2399 PatternNo, OS);
Evan Chengb915f312005-12-09 22:45:35 +00002400
Chris Lattner8fc35682005-09-23 23:16:51 +00002401 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002402 bool FoundChain = false;
2403 Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", FoundChain,
2404 true /*the root*/);
Evan Chengb915f312005-12-09 22:45:35 +00002405
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002406 // TP - Get *SOME* tree pattern, we don't care which.
2407 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002408
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002409 // At this point, we know that we structurally match the pattern, but the
2410 // types of the nodes may not match. Figure out the fewest number of type
2411 // comparisons we need to emit. For example, if there is only one integer
2412 // type supported by a target, there should be no type comparisons at all for
2413 // integer patterns!
2414 //
2415 // To figure out the fewest number of type checks needed, clone the pattern,
2416 // remove the types, then perform type inference on the pattern as a whole.
2417 // If there are unresolved types, emit an explicit check for those types,
2418 // apply the type to the tree, then rerun type inference. Iterate until all
2419 // types are resolved.
2420 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002421 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002422 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002423
2424 do {
2425 // Resolve/propagate as many types as possible.
2426 try {
2427 bool MadeChange = true;
2428 while (MadeChange)
2429 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2430 } catch (...) {
2431 assert(0 && "Error: could not find consistent types for something we"
2432 " already decided was ok!");
2433 abort();
2434 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002435
Chris Lattner7e82f132005-10-15 21:34:21 +00002436 // Insert a check for an unresolved type and add it to the tree. If we find
2437 // an unresolved type to add a check for, this returns true and we iterate,
2438 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002439 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002440
Evan Cheng58e84a62005-12-14 22:02:59 +00002441 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
Evan Chengb915f312005-12-09 22:45:35 +00002442
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002443 delete Pat;
2444
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002445 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002446}
2447
Chris Lattner37481472005-09-26 21:59:35 +00002448
2449namespace {
2450 /// CompareByRecordName - An ordering predicate that implements less-than by
2451 /// comparing the names records.
2452 struct CompareByRecordName {
2453 bool operator()(const Record *LHS, const Record *RHS) const {
2454 // Sort by name first.
2455 if (LHS->getName() < RHS->getName()) return true;
2456 // If both names are equal, sort by pointer.
2457 return LHS->getName() == RHS->getName() && LHS < RHS;
2458 }
2459 };
2460}
2461
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002462void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002463 std::string InstNS = Target.inst_begin()->second.Namespace;
2464 if (!InstNS.empty()) InstNS += "::";
2465
Chris Lattner602f6922006-01-04 00:25:00 +00002466 // Group the patterns by their top-level opcodes.
2467 std::map<Record*, std::vector<PatternToMatch*>,
2468 CompareByRecordName> PatternsByOpcode;
2469 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2470 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2471 if (!Node->isLeaf()) {
2472 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2473 } else {
2474 const ComplexPattern *CP;
2475 if (IntInit *II =
2476 dynamic_cast<IntInit*>(Node->getLeafValue())) {
2477 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2478 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2479 std::vector<Record*> OpNodes = CP->getRootNodes();
2480 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2481 PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2482 &PatternsToMatch[i]);
2483 }
2484 } else {
2485 std::cerr << "Unrecognized opcode '";
2486 Node->dump();
2487 std::cerr << "' on tree pattern '";
2488 std::cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
2489 std::cerr << "'!\n";
2490 exit(1);
2491 }
2492 }
2493 }
2494
2495 // Emit one Select_* method for each top-level opcode. We do this instead of
2496 // emitting one giant switch statement to support compilers where this will
2497 // result in the recursive functions taking less stack space.
2498 for (std::map<Record*, std::vector<PatternToMatch*>,
2499 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2500 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2501 OS << "SDOperand Select_" << PBOI->first->getName() << "(SDOperand N) {\n";
2502
2503 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2504 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2505
2506 // We want to emit all of the matching code now. However, we want to emit
2507 // the matches in order of minimal cost. Sort the patterns so the least
2508 // cost one is at the start.
2509 std::stable_sort(Patterns.begin(), Patterns.end(),
2510 PatternSortingPredicate(*this));
2511
2512 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2513 EmitCodeForPattern(*Patterns[i], OS);
2514
2515 OS << " std::cerr << \"Cannot yet select: \";\n"
2516 << " N.Val->dump(CurDAG);\n"
2517 << " std::cerr << '\\n';\n"
2518 << " abort();\n"
2519 << "}\n\n";
2520 }
2521
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002522 // Emit boilerplate.
2523 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002524 << "SDOperand SelectCode(SDOperand N) {\n"
2525 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002526 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2527 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002528 << " return N; // Already selected.\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002529 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng481c8e02005-12-12 23:22:48 +00002530 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002531 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002532 << " default: break;\n"
2533 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00002534 << " case ISD::BasicBlock:\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002535 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002536 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002537 << " case ISD::AssertZext: {\n"
2538 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2539 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2540 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002541 << " }\n"
2542 << " case ISD::TokenFactor:\n"
2543 << " if (N.getNumOperands() == 2) {\n"
2544 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2545 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2546 << " return CodeGenMap[N] =\n"
2547 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2548 << " } else {\n"
2549 << " std::vector<SDOperand> Ops;\n"
2550 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2551 << " Ops.push_back(Select(N.getOperand(i)));\n"
2552 << " return CodeGenMap[N] = \n"
2553 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2554 << " }\n"
2555 << " case ISD::CopyFromReg: {\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002556 << " SDOperand Chain = Select(N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002557 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2558 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002559 << " if (N.Val->getNumValues() == 2) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002560 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2561 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
2562 << " CodeGenMap[N.getValue(0)] = New;\n"
2563 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2564 << " return New.getValue(N.ResNo);\n"
2565 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00002566 << " SDOperand Flag(0, 0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002567 << " if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
2568 << " if (Chain == N.getOperand(0) &&\n"
2569 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002570 << " return N; // No change\n"
2571 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
2572 << " CodeGenMap[N.getValue(0)] = New;\n"
2573 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2574 << " CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
2575 << " return New.getValue(N.ResNo);\n"
2576 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002577 << " }\n"
2578 << " case ISD::CopyToReg: {\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002579 << " SDOperand Chain = Select(N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002580 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002581 << " SDOperand Val = Select(N.getOperand(2));\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002582 << " SDOperand Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002583 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002584 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002585 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002586 << " return CodeGenMap[N] = Result;\n"
2587 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00002588 << " SDOperand Flag(0, 0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002589 << " if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002590 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002591 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
2592 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002593 << " CodeGenMap[N.getValue(0)] = Result;\n"
2594 << " CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
2595 << " return Result.getValue(N.ResNo);\n"
2596 << " }\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002597 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002598
Chris Lattner602f6922006-01-04 00:25:00 +00002599 // Loop over all of the case statements, emiting a call to each method we
2600 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00002601 for (std::map<Record*, std::vector<PatternToMatch*>,
2602 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2603 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00002604 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00002605 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00002606 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Chris Lattner602f6922006-01-04 00:25:00 +00002607 << "return Select_" << PBOI->first->getName() << "(N);\n";
Chris Lattner81303322005-09-23 19:36:15 +00002608 }
Chris Lattner81303322005-09-23 19:36:15 +00002609
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002610 OS << " } // end of big switch.\n\n"
2611 << " std::cerr << \"Cannot yet select: \";\n"
Evan Cheng97938882005-12-22 02:24:50 +00002612 << " N.Val->dump(CurDAG);\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002613 << " std::cerr << '\\n';\n"
2614 << " abort();\n"
2615 << "}\n";
2616}
2617
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002618void DAGISelEmitter::run(std::ostream &OS) {
2619 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2620 " target", OS);
2621
Chris Lattner1f39e292005-09-14 00:09:24 +00002622 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2623 << "// *** instruction selector class. These functions are really "
2624 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002625
Chris Lattner296dfe32005-09-24 00:50:51 +00002626 OS << "// Instance var to keep track of multiply used nodes that have \n"
2627 << "// already been selected.\n"
2628 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2629
Chris Lattnerca559d02005-09-08 21:03:01 +00002630 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00002631 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00002632 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002633 ParsePatternFragments(OS);
2634 ParseInstructions();
2635 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00002636
Chris Lattnere97603f2005-09-28 19:27:25 +00002637 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00002638 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00002639 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002640
Chris Lattnere46e17b2005-09-29 19:28:10 +00002641
2642 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2643 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002644 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
2645 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00002646 std::cerr << "\n";
2647 });
2648
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002649 // At this point, we have full information about the 'Patterns' we need to
2650 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002651 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002652 EmitInstructionSelector(OS);
2653
2654 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2655 E = PatternFragments.end(); I != E; ++I)
2656 delete I->second;
2657 PatternFragments.clear();
2658
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002659 Instructions.clear();
2660}