blob: fab41c5f4c46fa3aea536c23e6d7e15a8b5f4d1a [file] [log] [blame]
Chris Lattnerfe718932008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner6cefb772008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfe718932008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner6cefb772008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner93c7e412008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000016#include "Record.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/Support/Debug.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000020#include <algorithm>
Daniel Dunbar1a551802009-07-03 00:10:29 +000021#include <iostream>
Chris Lattner6cefb772008-01-05 22:25:12 +000022using namespace llvm;
23
24//===----------------------------------------------------------------------===//
25// Helpers for working with extended types.
26
27/// FilterVTs - Filter a list of VT's according to a predicate.
28///
29template<typename T>
Owen Anderson825b72b2009-08-11 20:47:22 +000030static std::vector<MVT::SimpleValueType>
31FilterVTs(const std::vector<MVT::SimpleValueType> &InVTs, T Filter) {
32 std::vector<MVT::SimpleValueType> Result;
Chris Lattner6cefb772008-01-05 22:25:12 +000033 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
34 if (Filter(InVTs[i]))
35 Result.push_back(InVTs[i]);
36 return Result;
37}
38
39template<typename T>
40static std::vector<unsigned char>
41FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42 std::vector<unsigned char> Result;
43 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
Owen Anderson825b72b2009-08-11 20:47:22 +000044 if (Filter((MVT::SimpleValueType)InVTs[i]))
Chris Lattner6cefb772008-01-05 22:25:12 +000045 Result.push_back(InVTs[i]);
46 return Result;
47}
48
49static std::vector<unsigned char>
Owen Anderson825b72b2009-08-11 20:47:22 +000050ConvertVTs(const std::vector<MVT::SimpleValueType> &InVTs) {
Chris Lattner6cefb772008-01-05 22:25:12 +000051 std::vector<unsigned char> Result;
52 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53 Result.push_back(InVTs[i]);
54 return Result;
55}
56
Owen Anderson825b72b2009-08-11 20:47:22 +000057static inline bool isInteger(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000058 return EVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000059}
60
Owen Anderson825b72b2009-08-11 20:47:22 +000061static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000062 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000063}
64
Owen Anderson825b72b2009-08-11 20:47:22 +000065static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000066 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000067}
68
Chris Lattner6cefb772008-01-05 22:25:12 +000069static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
70 const std::vector<unsigned char> &RHS) {
71 if (LHS.size() > RHS.size()) return false;
72 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
73 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
74 return false;
75 return true;
76}
77
Chris Lattner6cefb772008-01-05 22:25:12 +000078namespace llvm {
Owen Andersone50ed302009-08-10 22:56:29 +000079namespace EEVT {
Dan Gohman4b6fce42009-03-31 16:48:35 +000080/// isExtIntegerInVTs - Return true if the specified extended value type vector
Bob Wilsoncdfa01b2009-08-29 05:53:25 +000081/// contains iAny or an integer value type.
Chris Lattner6cefb772008-01-05 22:25:12 +000082bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
83 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
Bob Wilsoncdfa01b2009-08-29 05:53:25 +000084 return EVTs[0] == MVT::iAny || !(FilterEVTs(EVTs, isInteger).empty());
Chris Lattner6cefb772008-01-05 22:25:12 +000085}
86
Dan Gohman4b6fce42009-03-31 16:48:35 +000087/// isExtFloatingPointInVTs - Return true if the specified extended value type
Bob Wilsoncdfa01b2009-08-29 05:53:25 +000088/// vector contains fAny or a FP value type.
Chris Lattner6cefb772008-01-05 22:25:12 +000089bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
Bob Wilson61fc4cf2009-08-11 01:14:02 +000090 assert(!EVTs.empty() && "Cannot check for FP in empty ExtVT list!");
Bob Wilsoncdfa01b2009-08-29 05:53:25 +000091 return EVTs[0] == MVT::fAny || !(FilterEVTs(EVTs, isFloatingPoint).empty());
Chris Lattner6cefb772008-01-05 22:25:12 +000092}
Bob Wilson61fc4cf2009-08-11 01:14:02 +000093
94/// isExtVectorInVTs - Return true if the specified extended value type
Bob Wilsoncdfa01b2009-08-29 05:53:25 +000095/// vector contains vAny or a vector value type.
Bob Wilson61fc4cf2009-08-11 01:14:02 +000096bool isExtVectorInVTs(const std::vector<unsigned char> &EVTs) {
97 assert(!EVTs.empty() && "Cannot check for vector in empty ExtVT list!");
Bob Wilsoncdfa01b2009-08-29 05:53:25 +000098 return EVTs[0] == MVT::vAny || !(FilterEVTs(EVTs, isVector).empty());
Bob Wilson61fc4cf2009-08-11 01:14:02 +000099}
Owen Andersone50ed302009-08-10 22:56:29 +0000100} // end namespace EEVT.
Chris Lattner6cefb772008-01-05 22:25:12 +0000101} // end namespace llvm.
102
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000103bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
104 return LHS->getID() < RHS->getID();
105}
Scott Michel327d0652008-03-05 17:49:05 +0000106
107/// Dependent variable map for CodeGenDAGPattern variant generation
108typedef std::map<std::string, int> DepVarMap;
109
110/// Const iterator shorthand for DepVarMap
111typedef DepVarMap::const_iterator DepVarMap_citer;
112
113namespace {
114void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
115 if (N->isLeaf()) {
116 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
117 DepMap[N->getName()]++;
118 }
119 } else {
120 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
121 FindDepVarsOf(N->getChild(i), DepMap);
122 }
123}
124
125//! Find dependent variables within child patterns
126/*!
127 */
128void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
129 DepVarMap depcounts;
130 FindDepVarsOf(N, depcounts);
131 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
132 if (i->second > 1) { // std::pair<std::string, int>
133 DepVars.insert(i->first);
134 }
135 }
136}
137
138//! Dump the dependent variable set:
139void DumpDepVars(MultipleUseVarSet &DepVars) {
140 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000141 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000142 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000143 DEBUG(errs() << "[ ");
Scott Michel327d0652008-03-05 17:49:05 +0000144 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
145 i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000146 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000147 }
Chris Lattner569f1212009-08-23 04:44:11 +0000148 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000149 }
150}
151}
152
Chris Lattner6cefb772008-01-05 22:25:12 +0000153//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000154// PatternToMatch implementation
155//
156
157/// getPredicateCheck - Return a single string containing all of this
158/// pattern's predicates concatenated with "&&" operators.
159///
160std::string PatternToMatch::getPredicateCheck() const {
161 std::string PredicateCheck;
162 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
163 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
164 Record *Def = Pred->getDef();
165 if (!Def->isSubClassOf("Predicate")) {
166#ifndef NDEBUG
167 Def->dump();
168#endif
169 assert(0 && "Unknown predicate type!");
170 }
171 if (!PredicateCheck.empty())
172 PredicateCheck += " && ";
173 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
174 }
175 }
176
177 return PredicateCheck;
178}
179
180//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000181// SDTypeConstraint implementation
182//
183
184SDTypeConstraint::SDTypeConstraint(Record *R) {
185 OperandNo = R->getValueAsInt("OperandNum");
186
187 if (R->isSubClassOf("SDTCisVT")) {
188 ConstraintType = SDTCisVT;
189 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
190 } else if (R->isSubClassOf("SDTCisPtrTy")) {
191 ConstraintType = SDTCisPtrTy;
192 } else if (R->isSubClassOf("SDTCisInt")) {
193 ConstraintType = SDTCisInt;
194 } else if (R->isSubClassOf("SDTCisFP")) {
195 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000196 } else if (R->isSubClassOf("SDTCisVec")) {
197 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000198 } else if (R->isSubClassOf("SDTCisSameAs")) {
199 ConstraintType = SDTCisSameAs;
200 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
201 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
202 ConstraintType = SDTCisVTSmallerThanOp;
203 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
204 R->getValueAsInt("OtherOperandNum");
205 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
206 ConstraintType = SDTCisOpSmallerThanOp;
207 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
208 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000209 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
210 ConstraintType = SDTCisEltOfVec;
211 x.SDTCisEltOfVec_Info.OtherOperandNum =
212 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000213 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000214 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000215 exit(1);
216 }
217}
218
219/// getOperandNum - Return the node corresponding to operand #OpNo in tree
220/// N, which has NumResults results.
221TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
222 TreePatternNode *N,
223 unsigned NumResults) const {
224 assert(NumResults <= 1 &&
225 "We only work with nodes with zero or one result so far!");
226
227 if (OpNo >= (NumResults + N->getNumChildren())) {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000228 errs() << "Invalid operand number " << OpNo << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000229 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000230 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000231 exit(1);
232 }
233
234 if (OpNo < NumResults)
235 return N; // FIXME: need value #
236 else
237 return N->getChild(OpNo-NumResults);
238}
239
240/// ApplyTypeConstraint - Given a node in a pattern, apply this type
241/// constraint to the nodes operands. This returns true if it makes a
242/// change, false otherwise. If a type contradiction is found, throw an
243/// exception.
244bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
245 const SDNodeInfo &NodeInfo,
246 TreePattern &TP) const {
247 unsigned NumResults = NodeInfo.getNumResults();
248 assert(NumResults <= 1 &&
249 "We only work with nodes with zero or one result so far!");
250
251 // Check that the number of operands is sane. Negative operands -> varargs.
252 if (NodeInfo.getNumOperands() >= 0) {
253 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
254 TP.error(N->getOperator()->getName() + " node requires exactly " +
255 itostr(NodeInfo.getNumOperands()) + " operands!");
256 }
257
258 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
259
260 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
261
262 switch (ConstraintType) {
263 default: assert(0 && "Unknown constraint type!");
264 case SDTCisVT:
265 // Operand must be a particular type.
266 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
267 case SDTCisPtrTy: {
268 // Operand must be same as target pointer type.
Owen Anderson825b72b2009-08-11 20:47:22 +0000269 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000270 }
271 case SDTCisInt: {
272 // If there is only one integer type supported, this must be it.
Owen Anderson825b72b2009-08-11 20:47:22 +0000273 std::vector<MVT::SimpleValueType> IntVTs =
Duncan Sands83ec4b62008-06-06 12:08:01 +0000274 FilterVTs(CGT.getLegalValueTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000275
276 // If we found exactly one supported integer type, apply it.
277 if (IntVTs.size() == 1)
278 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000279 return NodeToApply->UpdateNodeType(MVT::iAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000280 }
281 case SDTCisFP: {
282 // If there is only one FP type supported, this must be it.
Owen Anderson825b72b2009-08-11 20:47:22 +0000283 std::vector<MVT::SimpleValueType> FPVTs =
Duncan Sands83ec4b62008-06-06 12:08:01 +0000284 FilterVTs(CGT.getLegalValueTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000285
286 // If we found exactly one supported FP type, apply it.
287 if (FPVTs.size() == 1)
288 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000289 return NodeToApply->UpdateNodeType(MVT::fAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000290 }
Bob Wilson36e3e662009-08-12 22:30:59 +0000291 case SDTCisVec: {
292 // If there is only one vector type supported, this must be it.
293 std::vector<MVT::SimpleValueType> VecVTs =
294 FilterVTs(CGT.getLegalValueTypes(), isVector);
295
296 // If we found exactly one supported vector type, apply it.
297 if (VecVTs.size() == 1)
298 return NodeToApply->UpdateNodeType(VecVTs[0], TP);
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000299 return NodeToApply->UpdateNodeType(MVT::vAny, TP);
Bob Wilson36e3e662009-08-12 22:30:59 +0000300 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000301 case SDTCisSameAs: {
302 TreePatternNode *OtherNode =
303 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
304 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
305 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
306 }
307 case SDTCisVTSmallerThanOp: {
308 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
309 // have an integer type that is smaller than the VT.
310 if (!NodeToApply->isLeaf() ||
311 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
312 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
313 ->isSubClassOf("ValueType"))
314 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000315 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000316 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Duncan Sands83ec4b62008-06-06 12:08:01 +0000317 if (!isInteger(VT))
Chris Lattner6cefb772008-01-05 22:25:12 +0000318 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
319
320 TreePatternNode *OtherNode =
321 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
322
323 // It must be integer.
324 bool MadeChange = false;
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000325 MadeChange |= OtherNode->UpdateNodeType(MVT::iAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000326
327 // This code only handles nodes that have one type set. Assert here so
328 // that we can change this if we ever need to deal with multiple value
329 // types at this point.
330 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
331 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Owen Anderson825b72b2009-08-11 20:47:22 +0000332 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
Chris Lattner6cefb772008-01-05 22:25:12 +0000333 return false;
334 }
335 case SDTCisOpSmallerThanOp: {
336 TreePatternNode *BigOperand =
337 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
338
339 // Both operands must be integer or FP, but we don't care which.
340 bool MadeChange = false;
341
342 // This code does not currently handle nodes which have multiple types,
343 // where some types are integer, and some are fp. Assert that this is not
344 // the case.
Owen Andersone50ed302009-08-10 22:56:29 +0000345 assert(!(EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
346 EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
347 !(EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
348 EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000349 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
Owen Andersone50ed302009-08-10 22:56:29 +0000350 if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000351 MadeChange |= BigOperand->UpdateNodeType(MVT::iAny, TP);
Owen Andersone50ed302009-08-10 22:56:29 +0000352 else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000353 MadeChange |= BigOperand->UpdateNodeType(MVT::fAny, TP);
Owen Andersone50ed302009-08-10 22:56:29 +0000354 if (EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000355 MadeChange |= NodeToApply->UpdateNodeType(MVT::iAny, TP);
Owen Andersone50ed302009-08-10 22:56:29 +0000356 else if (EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000357 MadeChange |= NodeToApply->UpdateNodeType(MVT::fAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000358
Owen Anderson825b72b2009-08-11 20:47:22 +0000359 std::vector<MVT::SimpleValueType> VTs = CGT.getLegalValueTypes();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000360
Owen Andersone50ed302009-08-10 22:56:29 +0000361 if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000362 VTs = FilterVTs(VTs, isInteger);
Owen Andersone50ed302009-08-10 22:56:29 +0000363 } else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000364 VTs = FilterVTs(VTs, isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000365 } else {
366 VTs.clear();
367 }
368
369 switch (VTs.size()) {
370 default: // Too many VT's to pick from.
371 case 0: break; // No info yet.
372 case 1:
Jim Grosbachda4231f2009-03-26 16:17:51 +0000373 // Only one VT of this flavor. Cannot ever satisfy the constraints.
Owen Anderson825b72b2009-08-11 20:47:22 +0000374 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
Chris Lattner6cefb772008-01-05 22:25:12 +0000375 case 2:
376 // If we have exactly two possible types, the little operand must be the
377 // small one, the big operand should be the big one. Common with
378 // float/double for example.
379 assert(VTs[0] < VTs[1] && "Should be sorted!");
380 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
381 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
382 break;
383 }
384 return MadeChange;
385 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000386 case SDTCisEltOfVec: {
387 TreePatternNode *OtherOperand =
Nate Begeman9008ca62009-04-27 18:41:29 +0000388 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum,
Nate Begemanb5af3342008-02-09 01:37:05 +0000389 N, NumResults);
390 if (OtherOperand->hasTypeSet()) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000391 if (!isVector(OtherOperand->getTypeNum(0)))
Nate Begemanb5af3342008-02-09 01:37:05 +0000392 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Owen Andersone50ed302009-08-10 22:56:29 +0000393 EVT IVT = OtherOperand->getTypeNum(0);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000394 IVT = IVT.getVectorElementType();
Owen Anderson825b72b2009-08-11 20:47:22 +0000395 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000396 }
397 return false;
398 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000399 }
400 return false;
401}
402
403//===----------------------------------------------------------------------===//
404// SDNodeInfo implementation
405//
406SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
407 EnumName = R->getValueAsString("Opcode");
408 SDClassName = R->getValueAsString("SDClass");
409 Record *TypeProfile = R->getValueAsDef("TypeProfile");
410 NumResults = TypeProfile->getValueAsInt("NumResults");
411 NumOperands = TypeProfile->getValueAsInt("NumOperands");
412
413 // Parse the properties.
414 Properties = 0;
415 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
416 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
417 if (PropList[i]->getName() == "SDNPCommutative") {
418 Properties |= 1 << SDNPCommutative;
419 } else if (PropList[i]->getName() == "SDNPAssociative") {
420 Properties |= 1 << SDNPAssociative;
421 } else if (PropList[i]->getName() == "SDNPHasChain") {
422 Properties |= 1 << SDNPHasChain;
423 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen874ae252009-06-02 03:12:52 +0000424 Properties |= 1 << SDNPOutFlag;
Chris Lattner6cefb772008-01-05 22:25:12 +0000425 } else if (PropList[i]->getName() == "SDNPInFlag") {
426 Properties |= 1 << SDNPInFlag;
427 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
428 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000429 } else if (PropList[i]->getName() == "SDNPMayStore") {
430 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000431 } else if (PropList[i]->getName() == "SDNPMayLoad") {
432 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000433 } else if (PropList[i]->getName() == "SDNPSideEffect") {
434 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000435 } else if (PropList[i]->getName() == "SDNPMemOperand") {
436 Properties |= 1 << SDNPMemOperand;
Chris Lattner6cefb772008-01-05 22:25:12 +0000437 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000438 errs() << "Unknown SD Node property '" << PropList[i]->getName()
439 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000440 exit(1);
441 }
442 }
443
444
445 // Parse the type constraints.
446 std::vector<Record*> ConstraintList =
447 TypeProfile->getValueAsListOfDefs("Constraints");
448 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
449}
450
451//===----------------------------------------------------------------------===//
452// TreePatternNode implementation
453//
454
455TreePatternNode::~TreePatternNode() {
456#if 0 // FIXME: implement refcounted tree nodes!
457 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
458 delete getChild(i);
459#endif
460}
461
462/// UpdateNodeType - Set the node type of N to VT if VT contains
463/// information. If N already contains a conflicting type, then throw an
464/// exception. This returns true if any information was updated.
465///
466bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
467 TreePattern &TP) {
468 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
469
Owen Andersone50ed302009-08-10 22:56:29 +0000470 if (ExtVTs[0] == EEVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
Chris Lattner6cefb772008-01-05 22:25:12 +0000471 return false;
472 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
473 setTypes(ExtVTs);
474 return true;
475 }
476
Owen Anderson825b72b2009-08-11 20:47:22 +0000477 if (getExtTypeNum(0) == MVT::iPTR || getExtTypeNum(0) == MVT::iPTRAny) {
478 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny ||
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000479 ExtVTs[0] == MVT::iAny)
Chris Lattner6cefb772008-01-05 22:25:12 +0000480 return false;
Owen Andersone50ed302009-08-10 22:56:29 +0000481 if (EEVT::isExtIntegerInVTs(ExtVTs)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000482 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000483 if (FVTs.size()) {
484 setTypes(ExtVTs);
485 return true;
486 }
487 }
488 }
Bob Wilsone035fa52009-01-05 17:52:54 +0000489
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000490 // Merge vAny with iAny/fAny. The latter include vector types so keep them
491 // as the more specific information.
492 if (ExtVTs[0] == MVT::vAny &&
493 (getExtTypeNum(0) == MVT::iAny || getExtTypeNum(0) == MVT::fAny))
494 return false;
495 if (getExtTypeNum(0) == MVT::vAny &&
496 (ExtVTs[0] == MVT::iAny || ExtVTs[0] == MVT::fAny)) {
497 setTypes(ExtVTs);
498 return true;
499 }
500
501 if (ExtVTs[0] == MVT::iAny &&
Owen Andersone50ed302009-08-10 22:56:29 +0000502 EEVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000503 assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000504 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000505 if (getExtTypes() == FVTs)
506 return false;
507 setTypes(FVTs);
508 return true;
509 }
Owen Anderson825b72b2009-08-11 20:47:22 +0000510 if ((ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny) &&
Owen Andersone50ed302009-08-10 22:56:29 +0000511 EEVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000512 //assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000513 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000514 if (getExtTypes() == FVTs)
515 return false;
516 if (FVTs.size()) {
517 setTypes(FVTs);
518 return true;
519 }
520 }
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000521 if (ExtVTs[0] == MVT::fAny &&
Owen Andersone50ed302009-08-10 22:56:29 +0000522 EEVT::isExtFloatingPointInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000523 assert(hasTypeSet() && "should be handled above!");
524 std::vector<unsigned char> FVTs =
Duncan Sands83ec4b62008-06-06 12:08:01 +0000525 FilterEVTs(getExtTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000526 if (getExtTypes() == FVTs)
527 return false;
528 setTypes(FVTs);
529 return true;
530 }
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000531 if (ExtVTs[0] == MVT::vAny &&
Bob Wilson36e3e662009-08-12 22:30:59 +0000532 EEVT::isExtVectorInVTs(getExtTypes())) {
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000533 assert(hasTypeSet() && "should be handled above!");
534 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isVector);
535 if (getExtTypes() == FVTs)
536 return false;
537 setTypes(FVTs);
538 return true;
539 }
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000540
Bob Wilson36e3e662009-08-12 22:30:59 +0000541 // If we know this is an int, FP, or vector type, and we are told it is a
542 // specific one, take the advice.
Chris Lattner6cefb772008-01-05 22:25:12 +0000543 //
544 // Similarly, we should probably set the type here to the intersection of
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000545 // {iAny|fAny|vAny} and ExtVTs
546 if ((getExtTypeNum(0) == MVT::iAny &&
Owen Andersone50ed302009-08-10 22:56:29 +0000547 EEVT::isExtIntegerInVTs(ExtVTs)) ||
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000548 (getExtTypeNum(0) == MVT::fAny &&
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000549 EEVT::isExtFloatingPointInVTs(ExtVTs)) ||
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000550 (getExtTypeNum(0) == MVT::vAny &&
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000551 EEVT::isExtVectorInVTs(ExtVTs))) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000552 setTypes(ExtVTs);
553 return true;
554 }
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000555 if (getExtTypeNum(0) == MVT::iAny &&
Owen Anderson825b72b2009-08-11 20:47:22 +0000556 (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000557 setTypes(ExtVTs);
558 return true;
559 }
560
561 if (isLeaf()) {
562 dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000563 errs() << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000564 TP.error("Type inference contradiction found in node!");
565 } else {
566 TP.error("Type inference contradiction found in node " +
567 getOperator()->getName() + "!");
568 }
569 return true; // unreachable
570}
571
572
Daniel Dunbar1a551802009-07-03 00:10:29 +0000573void TreePatternNode::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000574 if (isLeaf()) {
575 OS << *getLeafValue();
576 } else {
577 OS << "(" << getOperator()->getName();
578 }
579
580 // FIXME: At some point we should handle printing all the value types for
581 // nodes that are multiply typed.
582 switch (getExtTypeNum(0)) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000583 case MVT::Other: OS << ":Other"; break;
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000584 case MVT::iAny: OS << ":iAny"; break;
585 case MVT::fAny : OS << ":fAny"; break;
586 case MVT::vAny: OS << ":vAny"; break;
Owen Andersone50ed302009-08-10 22:56:29 +0000587 case EEVT::isUnknown: ; /*OS << ":?";*/ break;
Owen Anderson825b72b2009-08-11 20:47:22 +0000588 case MVT::iPTR: OS << ":iPTR"; break;
589 case MVT::iPTRAny: OS << ":iPTRAny"; break;
Chris Lattner6cefb772008-01-05 22:25:12 +0000590 default: {
591 std::string VTName = llvm::getName(getTypeNum(0));
Owen Andersone50ed302009-08-10 22:56:29 +0000592 // Strip off EVT:: prefix if present.
Owen Anderson825b72b2009-08-11 20:47:22 +0000593 if (VTName.substr(0,5) == "MVT::")
Chris Lattner6cefb772008-01-05 22:25:12 +0000594 VTName = VTName.substr(5);
595 OS << ":" << VTName;
596 break;
597 }
598 }
599
600 if (!isLeaf()) {
601 if (getNumChildren() != 0) {
602 OS << " ";
603 getChild(0)->print(OS);
604 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
605 OS << ", ";
606 getChild(i)->print(OS);
607 }
608 }
609 OS << ")";
610 }
611
Dan Gohman0540e172008-10-15 06:17:21 +0000612 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
613 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000614 if (TransformFn)
615 OS << "<<X:" << TransformFn->getName() << ">>";
616 if (!getName().empty())
617 OS << ":$" << getName();
618
619}
620void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000621 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000622}
623
Scott Michel327d0652008-03-05 17:49:05 +0000624/// isIsomorphicTo - Return true if this node is recursively
625/// isomorphic to the specified node. For this comparison, the node's
626/// entire state is considered. The assigned name is ignored, since
627/// nodes with differing names are considered isomorphic. However, if
628/// the assigned name is present in the dependent variable set, then
629/// the assigned name is considered significant and the node is
630/// isomorphic if the names match.
631bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
632 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000633 if (N == this) return true;
634 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000635 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000636 getTransformFn() != N->getTransformFn())
637 return false;
638
639 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000640 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
641 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000642 return ((DI->getDef() == NDI->getDef())
643 && (DepVars.find(getName()) == DepVars.end()
644 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000645 }
646 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000647 return getLeafValue() == N->getLeafValue();
648 }
649
650 if (N->getOperator() != getOperator() ||
651 N->getNumChildren() != getNumChildren()) return false;
652 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000653 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000654 return false;
655 return true;
656}
657
658/// clone - Make a copy of this tree and all of its children.
659///
660TreePatternNode *TreePatternNode::clone() const {
661 TreePatternNode *New;
662 if (isLeaf()) {
663 New = new TreePatternNode(getLeafValue());
664 } else {
665 std::vector<TreePatternNode*> CChildren;
666 CChildren.reserve(Children.size());
667 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
668 CChildren.push_back(getChild(i)->clone());
669 New = new TreePatternNode(getOperator(), CChildren);
670 }
671 New->setName(getName());
672 New->setTypes(getExtTypes());
Dan Gohman0540e172008-10-15 06:17:21 +0000673 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000674 New->setTransformFn(getTransformFn());
675 return New;
676}
677
678/// SubstituteFormalArguments - Replace the formal arguments in this tree
679/// with actual values specified by ArgMap.
680void TreePatternNode::
681SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
682 if (isLeaf()) return;
683
684 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
685 TreePatternNode *Child = getChild(i);
686 if (Child->isLeaf()) {
687 Init *Val = Child->getLeafValue();
688 if (dynamic_cast<DefInit*>(Val) &&
689 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
690 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000691 TreePatternNode *NewChild = ArgMap[Child->getName()];
692 assert(NewChild && "Couldn't find formal argument!");
693 assert((Child->getPredicateFns().empty() ||
694 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
695 "Non-empty child predicate clobbered!");
696 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000697 }
698 } else {
699 getChild(i)->SubstituteFormalArguments(ArgMap);
700 }
701 }
702}
703
704
705/// InlinePatternFragments - If this pattern refers to any pattern
706/// fragments, inline them into place, giving us a pattern without any
707/// PatFrag references.
708TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
709 if (isLeaf()) return this; // nothing to do.
710 Record *Op = getOperator();
711
712 if (!Op->isSubClassOf("PatFrag")) {
713 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000714 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
715 TreePatternNode *Child = getChild(i);
716 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
717
718 assert((Child->getPredicateFns().empty() ||
719 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
720 "Non-empty child predicate clobbered!");
721
722 setChild(i, NewChild);
723 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000724 return this;
725 }
726
727 // Otherwise, we found a reference to a fragment. First, look up its
728 // TreePattern record.
729 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
730
731 // Verify that we are passing the right number of operands.
732 if (Frag->getNumArgs() != Children.size())
733 TP.error("'" + Op->getName() + "' fragment requires " +
734 utostr(Frag->getNumArgs()) + " operands!");
735
736 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
737
Dan Gohman0540e172008-10-15 06:17:21 +0000738 std::string Code = Op->getValueAsCode("Predicate");
739 if (!Code.empty())
740 FragTree->addPredicateFn("Predicate_"+Op->getName());
741
Chris Lattner6cefb772008-01-05 22:25:12 +0000742 // Resolve formal arguments to their actual value.
743 if (Frag->getNumArgs()) {
744 // Compute the map of formal to actual arguments.
745 std::map<std::string, TreePatternNode*> ArgMap;
746 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
747 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
748
749 FragTree->SubstituteFormalArguments(ArgMap);
750 }
751
752 FragTree->setName(getName());
753 FragTree->UpdateNodeType(getExtTypes(), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000754
755 // Transfer in the old predicates.
756 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
757 FragTree->addPredicateFn(getPredicateFns()[i]);
758
Chris Lattner6cefb772008-01-05 22:25:12 +0000759 // Get a new copy of this fragment to stitch into here.
760 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000761
762 // The fragment we inlined could have recursive inlining that is needed. See
763 // if there are any pattern fragments in it and inline them as needed.
764 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000765}
766
767/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000768/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +0000769/// references from the register file information, for example.
770///
771static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
772 TreePattern &TP) {
773 // Some common return values
Owen Andersone50ed302009-08-10 22:56:29 +0000774 std::vector<unsigned char> Unknown(1, EEVT::isUnknown);
Owen Anderson825b72b2009-08-11 20:47:22 +0000775 std::vector<unsigned char> Other(1, MVT::Other);
Chris Lattner6cefb772008-01-05 22:25:12 +0000776
777 // Check to see if this is a register or a register class...
778 if (R->isSubClassOf("RegisterClass")) {
779 if (NotRegisters)
780 return Unknown;
781 const CodeGenRegisterClass &RC =
782 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
783 return ConvertVTs(RC.getValueTypes());
784 } else if (R->isSubClassOf("PatFrag")) {
785 // Pattern fragment types will be resolved when they are inlined.
786 return Unknown;
787 } else if (R->isSubClassOf("Register")) {
788 if (NotRegisters)
789 return Unknown;
790 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
791 return T.getRegisterVTs(R);
792 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
793 // Using a VTSDNode or CondCodeSDNode.
794 return Other;
795 } else if (R->isSubClassOf("ComplexPattern")) {
796 if (NotRegisters)
797 return Unknown;
798 std::vector<unsigned char>
799 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
800 return ComplexPat;
Chris Lattnera938ac62009-07-29 20:43:05 +0000801 } else if (R->isSubClassOf("PointerLikeRegClass")) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000802 Other[0] = MVT::iPTR;
Chris Lattner6cefb772008-01-05 22:25:12 +0000803 return Other;
804 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
805 R->getName() == "zero_reg") {
806 // Placeholder.
807 return Unknown;
808 }
809
810 TP.error("Unknown node flavor used in pattern: " + R->getName());
811 return Other;
812}
813
Chris Lattnere67bde52008-01-06 05:36:50 +0000814
815/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
816/// CodeGenIntrinsic information for it, otherwise return a null pointer.
817const CodeGenIntrinsic *TreePatternNode::
818getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
819 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
820 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
821 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
822 return 0;
823
824 unsigned IID =
825 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
826 return &CDP.getIntrinsicInfo(IID);
827}
828
Evan Cheng6bd95672008-06-16 20:29:38 +0000829/// isCommutativeIntrinsic - Return true if the node corresponds to a
830/// commutative intrinsic.
831bool
832TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
833 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
834 return Int->isCommutative;
835 return false;
836}
837
Chris Lattnere67bde52008-01-06 05:36:50 +0000838
Bob Wilson6c01ca92009-01-05 17:23:09 +0000839/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +0000840/// this node and its children in the tree. This returns true if it makes a
841/// change, false otherwise. If a type contradiction is found, throw an
842/// exception.
843bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +0000844 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +0000845 if (isLeaf()) {
846 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
847 // If it's a regclass or something else known, include the type.
848 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
849 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
850 // Int inits are always integers. :)
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000851 bool MadeChange = UpdateNodeType(MVT::iAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000852
853 if (hasTypeSet()) {
854 // At some point, it may make sense for this tree pattern to have
855 // multiple types. Assert here that it does not, so we revisit this
856 // code when appropriate.
857 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000858 MVT::SimpleValueType VT = getTypeNum(0);
Chris Lattner6cefb772008-01-05 22:25:12 +0000859 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
860 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
861
862 VT = getTypeNum(0);
Owen Anderson825b72b2009-08-11 20:47:22 +0000863 if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
Owen Andersone50ed302009-08-10 22:56:29 +0000864 unsigned Size = EVT(VT).getSizeInBits();
Chris Lattner6cefb772008-01-05 22:25:12 +0000865 // Make sure that the value is representable for this type.
866 if (Size < 32) {
867 int Val = (II->getValue() << (32-Size)) >> (32-Size);
Scott Michel0123b7d2008-02-15 23:05:48 +0000868 if (Val != II->getValue()) {
Bill Wendling27926af2008-02-26 10:45:29 +0000869 // If sign-extended doesn't fit, does it fit as unsigned?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000870 unsigned ValueMask;
871 unsigned UnsignedVal;
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +0000872 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
Duncan Sands83ec4b62008-06-06 12:08:01 +0000873 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +0000874
Bill Wendling27926af2008-02-26 10:45:29 +0000875 if ((ValueMask & UnsignedVal) != UnsignedVal) {
876 TP.error("Integer value '" + itostr(II->getValue())+
877 "' is out of range for type '" +
878 getEnumName(getTypeNum(0)) + "'!");
879 }
880 }
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000881 }
882 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000883 }
884
885 return MadeChange;
886 }
887 return false;
888 }
889
890 // special handling for set, which isn't really an SDNode.
891 if (getOperator()->getName() == "set") {
892 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
893 unsigned NC = getNumChildren();
894 bool MadeChange = false;
895 for (unsigned i = 0; i < NC-1; ++i) {
896 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
897 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
898
899 // Types of operands must match.
900 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
901 TP);
902 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
903 TP);
Owen Anderson825b72b2009-08-11 20:47:22 +0000904 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000905 }
906 return MadeChange;
907 } else if (getOperator()->getName() == "implicit" ||
908 getOperator()->getName() == "parallel") {
909 bool MadeChange = false;
910 for (unsigned i = 0; i < getNumChildren(); ++i)
911 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Owen Anderson825b72b2009-08-11 20:47:22 +0000912 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000913 return MadeChange;
Dan Gohman88c7af02009-04-13 21:06:25 +0000914 } else if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +0000915 bool MadeChange = false;
916 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
917 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Dan Gohmanf8c73942009-04-13 15:38:05 +0000918 return MadeChange;
Chris Lattnere67bde52008-01-06 05:36:50 +0000919 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000920 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000921
Chris Lattner6cefb772008-01-05 22:25:12 +0000922 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000923 unsigned NumRetVTs = Int->IS.RetVTs.size();
924 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000925
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000926 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
927 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
928
929 if (getNumChildren() != NumParamVTs + NumRetVTs)
Chris Lattnere67bde52008-01-06 05:36:50 +0000930 TP.error("Intrinsic '" + Int->Name + "' expects " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000931 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
932 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +0000933
934 // Apply type info to the intrinsic ID.
Owen Anderson825b72b2009-08-11 20:47:22 +0000935 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000936
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000937 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000938 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
Chris Lattner6cefb772008-01-05 22:25:12 +0000939 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
940 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
941 }
942 return MadeChange;
943 } else if (getOperator()->isSubClassOf("SDNode")) {
944 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
945
946 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
947 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
948 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
949 // Branch, etc. do not produce results and top-level forms in instr pattern
950 // must have void types.
951 if (NI.getNumResults() == 0)
Owen Anderson825b72b2009-08-11 20:47:22 +0000952 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000953
Chris Lattner6cefb772008-01-05 22:25:12 +0000954 return MadeChange;
955 } else if (getOperator()->isSubClassOf("Instruction")) {
956 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
957 bool MadeChange = false;
958 unsigned NumResults = Inst.getNumResults();
959
960 assert(NumResults <= 1 &&
961 "Only supports zero or one result instrs!");
962
963 CodeGenInstruction &InstInfo =
964 CDP.getTargetInfo().getInstruction(getOperator()->getName());
965 // Apply the result type to the node
966 if (NumResults == 0 || InstInfo.NumDefs == 0) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000967 MadeChange = UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000968 } else {
969 Record *ResultNode = Inst.getResult(0);
970
Chris Lattnera938ac62009-07-29 20:43:05 +0000971 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000972 std::vector<unsigned char> VT;
Owen Anderson825b72b2009-08-11 20:47:22 +0000973 VT.push_back(MVT::iPTR);
Chris Lattner6cefb772008-01-05 22:25:12 +0000974 MadeChange = UpdateNodeType(VT, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +0000975 } else if (ResultNode->getName() == "unknown") {
976 std::vector<unsigned char> VT;
Owen Andersone50ed302009-08-10 22:56:29 +0000977 VT.push_back(EEVT::isUnknown);
Christopher Lamb5b415372008-03-11 09:33:47 +0000978 MadeChange = UpdateNodeType(VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000979 } else {
980 assert(ResultNode->isSubClassOf("RegisterClass") &&
981 "Operands should be register classes!");
982
983 const CodeGenRegisterClass &RC =
984 CDP.getTargetInfo().getRegisterClass(ResultNode);
985 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
986 }
987 }
988
989 unsigned ChildNo = 0;
990 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
991 Record *OperandNode = Inst.getOperand(i);
992
993 // If the instruction expects a predicate or optional def operand, we
994 // codegen this by setting the operand to it's default value if it has a
995 // non-empty DefaultOps field.
996 if ((OperandNode->isSubClassOf("PredicateOperand") ||
997 OperandNode->isSubClassOf("OptionalDefOperand")) &&
998 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
999 continue;
1000
1001 // Verify that we didn't run out of provided operands.
1002 if (ChildNo >= getNumChildren())
1003 TP.error("Instruction '" + getOperator()->getName() +
1004 "' expects more operands than were provided.");
1005
Owen Anderson825b72b2009-08-11 20:47:22 +00001006 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001007 TreePatternNode *Child = getChild(ChildNo++);
1008 if (OperandNode->isSubClassOf("RegisterClass")) {
1009 const CodeGenRegisterClass &RC =
1010 CDP.getTargetInfo().getRegisterClass(OperandNode);
1011 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
1012 } else if (OperandNode->isSubClassOf("Operand")) {
1013 VT = getValueType(OperandNode->getValueAsDef("Type"));
1014 MadeChange |= Child->UpdateNodeType(VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001015 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001016 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001017 } else if (OperandNode->getName() == "unknown") {
Owen Andersone50ed302009-08-10 22:56:29 +00001018 MadeChange |= Child->UpdateNodeType(EEVT::isUnknown, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001019 } else {
1020 assert(0 && "Unknown operand type!");
1021 abort();
1022 }
1023 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1024 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001025
Christopher Lamb02f69372008-03-10 04:16:09 +00001026 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001027 TP.error("Instruction '" + getOperator()->getName() +
1028 "' was provided too many operands!");
1029
1030 return MadeChange;
1031 } else {
1032 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1033
1034 // Node transforms always take one operand.
1035 if (getNumChildren() != 1)
1036 TP.error("Node transform '" + getOperator()->getName() +
1037 "' requires one operand!");
1038
1039 // If either the output or input of the xform does not have exact
1040 // type info. We assume they must be the same. Otherwise, it is perfectly
1041 // legal to transform from one type to a completely different type.
1042 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1043 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
1044 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
1045 return MadeChange;
1046 }
1047 return false;
1048 }
1049}
1050
1051/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1052/// RHS of a commutative operation, not the on LHS.
1053static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1054 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1055 return true;
1056 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1057 return true;
1058 return false;
1059}
1060
1061
1062/// canPatternMatch - If it is impossible for this pattern to match on this
1063/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001064/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001065/// that can never possibly work), and to prevent the pattern permuter from
1066/// generating stuff that is useless.
1067bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001068 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001069 if (isLeaf()) return true;
1070
1071 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1072 if (!getChild(i)->canPatternMatch(Reason, CDP))
1073 return false;
1074
1075 // If this is an intrinsic, handle cases that would make it not match. For
1076 // example, if an operand is required to be an immediate.
1077 if (getOperator()->isSubClassOf("Intrinsic")) {
1078 // TODO:
1079 return true;
1080 }
1081
1082 // If this node is a commutative operator, check that the LHS isn't an
1083 // immediate.
1084 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001085 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1086 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001087 // Scan all of the operands of the node and make sure that only the last one
1088 // is a constant node, unless the RHS also is.
1089 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001090 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1091 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001092 if (OnlyOnRHSOfCommutative(getChild(i))) {
1093 Reason="Immediate value must be on the RHS of commutative operators!";
1094 return false;
1095 }
1096 }
1097 }
1098
1099 return true;
1100}
1101
1102//===----------------------------------------------------------------------===//
1103// TreePattern implementation
1104//
1105
1106TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001107 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001108 isInputPattern = isInput;
1109 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1110 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1111}
1112
1113TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001114 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001115 isInputPattern = isInput;
1116 Trees.push_back(ParseTreePattern(Pat));
1117}
1118
1119TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001120 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001121 isInputPattern = isInput;
1122 Trees.push_back(Pat);
1123}
1124
1125
1126
1127void TreePattern::error(const std::string &Msg) const {
1128 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001129 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001130}
1131
1132TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1133 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1134 if (!OpDef) error("Pattern has unexpected operator type!");
1135 Record *Operator = OpDef->getDef();
1136
1137 if (Operator->isSubClassOf("ValueType")) {
1138 // If the operator is a ValueType, then this must be "type cast" of a leaf
1139 // node.
1140 if (Dag->getNumArgs() != 1)
1141 error("Type cast only takes one operand!");
1142
1143 Init *Arg = Dag->getArg(0);
1144 TreePatternNode *New;
1145 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1146 Record *R = DI->getDef();
1147 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001148 Dag->setArg(0, new DagInit(DI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001149 std::vector<std::pair<Init*, std::string> >()));
1150 return ParseTreePattern(Dag);
1151 }
1152 New = new TreePatternNode(DI);
1153 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1154 New = ParseTreePattern(DI);
1155 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1156 New = new TreePatternNode(II);
1157 if (!Dag->getArgName(0).empty())
1158 error("Constant int argument should not have a name!");
1159 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1160 // Turn this into an IntInit.
1161 Init *II = BI->convertInitializerTo(new IntRecTy());
1162 if (II == 0 || !dynamic_cast<IntInit*>(II))
1163 error("Bits value must be constants!");
1164
1165 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1166 if (!Dag->getArgName(0).empty())
1167 error("Constant int argument should not have a name!");
1168 } else {
1169 Arg->dump();
1170 error("Unknown leaf value for tree pattern!");
1171 return 0;
1172 }
1173
1174 // Apply the type cast.
1175 New->UpdateNodeType(getValueType(Operator), *this);
Nate Begeman7cee8172009-03-19 05:21:56 +00001176 if (New->getNumChildren() == 0)
1177 New->setName(Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001178 return New;
1179 }
1180
1181 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001182 if (!Operator->isSubClassOf("PatFrag") &&
1183 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001184 !Operator->isSubClassOf("Instruction") &&
1185 !Operator->isSubClassOf("SDNodeXForm") &&
1186 !Operator->isSubClassOf("Intrinsic") &&
1187 Operator->getName() != "set" &&
1188 Operator->getName() != "implicit" &&
1189 Operator->getName() != "parallel")
1190 error("Unrecognized node '" + Operator->getName() + "'!");
1191
1192 // Check to see if this is something that is illegal in an input pattern.
1193 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1194 Operator->isSubClassOf("SDNodeXForm")))
1195 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1196
1197 std::vector<TreePatternNode*> Children;
1198
1199 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1200 Init *Arg = Dag->getArg(i);
1201 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1202 Children.push_back(ParseTreePattern(DI));
1203 if (Children.back()->getName().empty())
1204 Children.back()->setName(Dag->getArgName(i));
1205 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1206 Record *R = DefI->getDef();
1207 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1208 // TreePatternNode if its own.
1209 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001210 Dag->setArg(i, new DagInit(DefI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001211 std::vector<std::pair<Init*, std::string> >()));
1212 --i; // Revisit this node...
1213 } else {
1214 TreePatternNode *Node = new TreePatternNode(DefI);
1215 Node->setName(Dag->getArgName(i));
1216 Children.push_back(Node);
1217
1218 // Input argument?
1219 if (R->getName() == "node") {
1220 if (Dag->getArgName(i).empty())
1221 error("'node' argument requires a name to match with operand list");
1222 Args.push_back(Dag->getArgName(i));
1223 }
1224 }
1225 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1226 TreePatternNode *Node = new TreePatternNode(II);
1227 if (!Dag->getArgName(i).empty())
1228 error("Constant int argument should not have a name!");
1229 Children.push_back(Node);
1230 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1231 // Turn this into an IntInit.
1232 Init *II = BI->convertInitializerTo(new IntRecTy());
1233 if (II == 0 || !dynamic_cast<IntInit*>(II))
1234 error("Bits value must be constants!");
1235
1236 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1237 if (!Dag->getArgName(i).empty())
1238 error("Constant int argument should not have a name!");
1239 Children.push_back(Node);
1240 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001241 errs() << '"';
Chris Lattner6cefb772008-01-05 22:25:12 +00001242 Arg->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001243 errs() << "\": ";
Chris Lattner6cefb772008-01-05 22:25:12 +00001244 error("Unknown leaf value for tree pattern!");
1245 }
1246 }
1247
1248 // If the operator is an intrinsic, then this is just syntactic sugar for for
1249 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1250 // convert the intrinsic name to a number.
1251 if (Operator->isSubClassOf("Intrinsic")) {
1252 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1253 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1254
1255 // If this intrinsic returns void, it must have side-effects and thus a
1256 // chain.
Owen Anderson825b72b2009-08-11 20:47:22 +00001257 if (Int.IS.RetVTs[0] == MVT::isVoid) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001258 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1259 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1260 // Has side-effects, requires chain.
1261 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1262 } else {
1263 // Otherwise, no chain.
1264 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1265 }
1266
1267 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1268 Children.insert(Children.begin(), IIDNode);
1269 }
1270
Nate Begeman7cee8172009-03-19 05:21:56 +00001271 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1272 Result->setName(Dag->getName());
1273 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001274}
1275
1276/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001277/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001278/// otherwise. Throw an exception if a type contradiction is found.
1279bool TreePattern::InferAllTypes() {
1280 bool MadeChange = true;
1281 while (MadeChange) {
1282 MadeChange = false;
1283 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1284 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1285 }
1286
1287 bool HasUnresolvedTypes = false;
1288 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1289 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1290 return !HasUnresolvedTypes;
1291}
1292
Daniel Dunbar1a551802009-07-03 00:10:29 +00001293void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001294 OS << getRecord()->getName();
1295 if (!Args.empty()) {
1296 OS << "(" << Args[0];
1297 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1298 OS << ", " << Args[i];
1299 OS << ")";
1300 }
1301 OS << ": ";
1302
1303 if (Trees.size() > 1)
1304 OS << "[\n";
1305 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1306 OS << "\t";
1307 Trees[i]->print(OS);
1308 OS << "\n";
1309 }
1310
1311 if (Trees.size() > 1)
1312 OS << "]\n";
1313}
1314
Daniel Dunbar1a551802009-07-03 00:10:29 +00001315void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001316
1317//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001318// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001319//
1320
1321// FIXME: REMOVE OSTREAM ARGUMENT
Chris Lattnerfe718932008-01-06 01:10:31 +00001322CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001323 Intrinsics = LoadIntrinsics(Records, false);
1324 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001325 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001326 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001327 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001328 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001329 ParseDefaultOperands();
1330 ParseInstructions();
1331 ParsePatterns();
1332
1333 // Generate variants. For example, commutative patterns can match
1334 // multiple ways. Add them to PatternsToMatch as well.
1335 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001336
1337 // Infer instruction flags. For example, we can detect loads,
1338 // stores, and side effects in many cases by examining an
1339 // instruction's pattern.
1340 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001341}
1342
Chris Lattnerfe718932008-01-06 01:10:31 +00001343CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001344 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001345 E = PatternFragments.end(); I != E; ++I)
1346 delete I->second;
1347}
1348
1349
Chris Lattnerfe718932008-01-06 01:10:31 +00001350Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001351 Record *N = Records.getDef(Name);
1352 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001353 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001354 exit(1);
1355 }
1356 return N;
1357}
1358
1359// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001360void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001361 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1362 while (!Nodes.empty()) {
1363 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1364 Nodes.pop_back();
1365 }
1366
Jim Grosbachda4231f2009-03-26 16:17:51 +00001367 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001368 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1369 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1370 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1371}
1372
1373/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1374/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001375void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001376 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1377 while (!Xforms.empty()) {
1378 Record *XFormNode = Xforms.back();
1379 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1380 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001381 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001382
1383 Xforms.pop_back();
1384 }
1385}
1386
Chris Lattnerfe718932008-01-06 01:10:31 +00001387void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001388 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1389 while (!AMs.empty()) {
1390 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1391 AMs.pop_back();
1392 }
1393}
1394
1395
1396/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1397/// file, building up the PatternFragments map. After we've collected them all,
1398/// inline fragments together as necessary, so that there are no references left
1399/// inside a pattern fragment to a pattern fragment.
1400///
Chris Lattnerfe718932008-01-06 01:10:31 +00001401void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001402 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1403
Chris Lattnerdc32f982008-01-05 22:43:57 +00001404 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001405 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1406 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1407 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1408 PatternFragments[Fragments[i]] = P;
1409
Chris Lattnerdc32f982008-01-05 22:43:57 +00001410 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001411 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001412 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001413
Chris Lattnerdc32f982008-01-05 22:43:57 +00001414 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001415 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1416
1417 // Parse the operands list.
1418 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1419 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1420 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001421 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001422 if (!OpsOp ||
1423 (OpsOp->getDef()->getName() != "ops" &&
1424 OpsOp->getDef()->getName() != "outs" &&
1425 OpsOp->getDef()->getName() != "ins"))
1426 P->error("Operands list should start with '(ops ... '!");
1427
1428 // Copy over the arguments.
1429 Args.clear();
1430 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1431 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1432 static_cast<DefInit*>(OpsList->getArg(j))->
1433 getDef()->getName() != "node")
1434 P->error("Operands list should all be 'node' values.");
1435 if (OpsList->getArgName(j).empty())
1436 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001437 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001438 P->error("'" + OpsList->getArgName(j) +
1439 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001440 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001441 Args.push_back(OpsList->getArgName(j));
1442 }
1443
Chris Lattnerdc32f982008-01-05 22:43:57 +00001444 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001445 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001446 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001447
Chris Lattnerdc32f982008-01-05 22:43:57 +00001448 // If there is a code init for this fragment, keep track of the fact that
1449 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001450 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001451 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001452 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001453
1454 // If there is a node transformation corresponding to this, keep track of
1455 // it.
1456 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1457 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1458 P->getOnlyTree()->setTransformFn(Transform);
1459 }
1460
Chris Lattner6cefb772008-01-05 22:25:12 +00001461 // Now that we've parsed all of the tree fragments, do a closure on them so
1462 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001463 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1464 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001465 ThePat->InlinePatternFragments();
1466
1467 // Infer as many types as possible. Don't worry about it if we don't infer
1468 // all of them, some may depend on the inputs of the pattern.
1469 try {
1470 ThePat->InferAllTypes();
1471 } catch (...) {
1472 // If this pattern fragment is not supported by this target (no types can
1473 // satisfy its constraints), just ignore it. If the bogus pattern is
1474 // actually used by instructions, the type consistency error will be
1475 // reported there.
1476 }
1477
1478 // If debugging, print out the pattern fragment result.
1479 DEBUG(ThePat->dump());
1480 }
1481}
1482
Chris Lattnerfe718932008-01-06 01:10:31 +00001483void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001484 std::vector<Record*> DefaultOps[2];
1485 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1486 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1487
1488 // Find some SDNode.
1489 assert(!SDNodes.empty() && "No SDNodes parsed?");
1490 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1491
1492 for (unsigned iter = 0; iter != 2; ++iter) {
1493 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1494 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1495
1496 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1497 // SomeSDnode so that we can parse this.
1498 std::vector<std::pair<Init*, std::string> > Ops;
1499 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1500 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1501 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001502 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001503
1504 // Create a TreePattern to parse this.
1505 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1506 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1507
1508 // Copy the operands over into a DAGDefaultOperand.
1509 DAGDefaultOperand DefaultOpInfo;
1510
1511 TreePatternNode *T = P.getTree(0);
1512 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1513 TreePatternNode *TPN = T->getChild(op);
1514 while (TPN->ApplyTypeConstraints(P, false))
1515 /* Resolve all types */;
1516
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001517 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001518 if (iter == 0)
1519 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1520 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1521 else
1522 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1523 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001524 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001525 DefaultOpInfo.DefaultOps.push_back(TPN);
1526 }
1527
1528 // Insert it into the DefaultOperands map so we can find it later.
1529 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1530 }
1531 }
1532}
1533
1534/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1535/// instruction input. Return true if this is a real use.
1536static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1537 std::map<std::string, TreePatternNode*> &InstInputs,
1538 std::vector<Record*> &InstImpInputs) {
1539 // No name -> not interesting.
1540 if (Pat->getName().empty()) {
1541 if (Pat->isLeaf()) {
1542 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1543 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1544 I->error("Input " + DI->getDef()->getName() + " must be named!");
1545 else if (DI && DI->getDef()->isSubClassOf("Register"))
1546 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001547 }
1548 return false;
1549 }
1550
1551 Record *Rec;
1552 if (Pat->isLeaf()) {
1553 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1554 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1555 Rec = DI->getDef();
1556 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001557 Rec = Pat->getOperator();
1558 }
1559
1560 // SRCVALUE nodes are ignored.
1561 if (Rec->getName() == "srcvalue")
1562 return false;
1563
1564 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1565 if (!Slot) {
1566 Slot = Pat;
1567 } else {
1568 Record *SlotRec;
1569 if (Slot->isLeaf()) {
1570 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1571 } else {
1572 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1573 SlotRec = Slot->getOperator();
1574 }
1575
1576 // Ensure that the inputs agree if we've already seen this input.
1577 if (Rec != SlotRec)
1578 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1579 if (Slot->getExtTypes() != Pat->getExtTypes())
1580 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1581 }
1582 return true;
1583}
1584
1585/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1586/// part of "I", the instruction), computing the set of inputs and outputs of
1587/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001588void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001589FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1590 std::map<std::string, TreePatternNode*> &InstInputs,
1591 std::map<std::string, TreePatternNode*>&InstResults,
1592 std::vector<Record*> &InstImpInputs,
1593 std::vector<Record*> &InstImpResults) {
1594 if (Pat->isLeaf()) {
1595 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1596 if (!isUse && Pat->getTransformFn())
1597 I->error("Cannot specify a transform function for a non-input value!");
1598 return;
1599 } else if (Pat->getOperator()->getName() == "implicit") {
1600 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1601 TreePatternNode *Dest = Pat->getChild(i);
1602 if (!Dest->isLeaf())
1603 I->error("implicitly defined value should be a register!");
1604
1605 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1606 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1607 I->error("implicitly defined value should be a register!");
1608 InstImpResults.push_back(Val->getDef());
1609 }
1610 return;
1611 } else if (Pat->getOperator()->getName() != "set") {
1612 // If this is not a set, verify that the children nodes are not void typed,
1613 // and recurse.
1614 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001615 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00001616 I->error("Cannot have void nodes inside of patterns!");
1617 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1618 InstImpInputs, InstImpResults);
1619 }
1620
1621 // If this is a non-leaf node with no children, treat it basically as if
1622 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00001623 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00001624
1625 if (!isUse && Pat->getTransformFn())
1626 I->error("Cannot specify a transform function for a non-input value!");
1627 return;
1628 }
1629
1630 // Otherwise, this is a set, validate and collect instruction results.
1631 if (Pat->getNumChildren() == 0)
1632 I->error("set requires operands!");
1633
1634 if (Pat->getTransformFn())
1635 I->error("Cannot specify a transform function on a set node!");
1636
1637 // Check the set destinations.
1638 unsigned NumDests = Pat->getNumChildren()-1;
1639 for (unsigned i = 0; i != NumDests; ++i) {
1640 TreePatternNode *Dest = Pat->getChild(i);
1641 if (!Dest->isLeaf())
1642 I->error("set destination should be a register!");
1643
1644 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1645 if (!Val)
1646 I->error("set destination should be a register!");
1647
1648 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00001649 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001650 if (Dest->getName().empty())
1651 I->error("set destination must have a name!");
1652 if (InstResults.count(Dest->getName()))
1653 I->error("cannot set '" + Dest->getName() +"' multiple times");
1654 InstResults[Dest->getName()] = Dest;
1655 } else if (Val->getDef()->isSubClassOf("Register")) {
1656 InstImpResults.push_back(Val->getDef());
1657 } else {
1658 I->error("set destination should be a register!");
1659 }
1660 }
1661
1662 // Verify and collect info from the computation.
1663 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1664 InstInputs, InstResults,
1665 InstImpInputs, InstImpResults);
1666}
1667
Dan Gohmanee4fa192008-04-03 00:02:49 +00001668//===----------------------------------------------------------------------===//
1669// Instruction Analysis
1670//===----------------------------------------------------------------------===//
1671
1672class InstAnalyzer {
1673 const CodeGenDAGPatterns &CDP;
1674 bool &mayStore;
1675 bool &mayLoad;
1676 bool &HasSideEffects;
1677public:
1678 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1679 bool &maystore, bool &mayload, bool &hse)
1680 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1681 }
1682
1683 /// Analyze - Analyze the specified instruction, returning true if the
1684 /// instruction had a pattern.
1685 bool Analyze(Record *InstRecord) {
1686 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1687 if (Pattern == 0) {
1688 HasSideEffects = 1;
1689 return false; // No pattern.
1690 }
1691
1692 // FIXME: Assume only the first tree is the pattern. The others are clobber
1693 // nodes.
1694 AnalyzeNode(Pattern->getTree(0));
1695 return true;
1696 }
1697
1698private:
1699 void AnalyzeNode(const TreePatternNode *N) {
1700 if (N->isLeaf()) {
1701 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1702 Record *LeafRec = DI->getDef();
1703 // Handle ComplexPattern leaves.
1704 if (LeafRec->isSubClassOf("ComplexPattern")) {
1705 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1706 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1707 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1708 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1709 }
1710 }
1711 return;
1712 }
1713
1714 // Analyze children.
1715 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1716 AnalyzeNode(N->getChild(i));
1717
1718 // Ignore set nodes, which are not SDNodes.
1719 if (N->getOperator()->getName() == "set")
1720 return;
1721
1722 // Get information about the SDNode for the operator.
1723 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1724
1725 // Notice properties of the node.
1726 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1727 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1728 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1729
1730 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1731 // If this is an intrinsic, analyze it.
1732 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1733 mayLoad = true;// These may load memory.
1734
1735 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1736 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1737
1738 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1739 // WriteMem intrinsics can have other strange effects.
1740 HasSideEffects = true;
1741 }
1742 }
1743
1744};
1745
1746static void InferFromPattern(const CodeGenInstruction &Inst,
1747 bool &MayStore, bool &MayLoad,
1748 bool &HasSideEffects,
1749 const CodeGenDAGPatterns &CDP) {
1750 MayStore = MayLoad = HasSideEffects = false;
1751
1752 bool HadPattern =
1753 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1754
1755 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1756 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1757 // If we decided that this is a store from the pattern, then the .td file
1758 // entry is redundant.
1759 if (MayStore)
1760 fprintf(stderr,
1761 "Warning: mayStore flag explicitly set on instruction '%s'"
1762 " but flag already inferred from pattern.\n",
1763 Inst.TheDef->getName().c_str());
1764 MayStore = true;
1765 }
1766
1767 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1768 // If we decided that this is a load from the pattern, then the .td file
1769 // entry is redundant.
1770 if (MayLoad)
1771 fprintf(stderr,
1772 "Warning: mayLoad flag explicitly set on instruction '%s'"
1773 " but flag already inferred from pattern.\n",
1774 Inst.TheDef->getName().c_str());
1775 MayLoad = true;
1776 }
1777
1778 if (Inst.neverHasSideEffects) {
1779 if (HadPattern)
1780 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1781 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1782 HasSideEffects = false;
1783 }
1784
1785 if (Inst.hasSideEffects) {
1786 if (HasSideEffects)
1787 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1788 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1789 HasSideEffects = true;
1790 }
1791}
1792
Chris Lattner6cefb772008-01-05 22:25:12 +00001793/// ParseInstructions - Parse all of the instructions, inlining and resolving
1794/// any fragments involved. This populates the Instructions list with fully
1795/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001796void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001797 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1798
1799 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1800 ListInit *LI = 0;
1801
1802 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1803 LI = Instrs[i]->getValueAsListInit("Pattern");
1804
1805 // If there is no pattern, only collect minimal information about the
1806 // instruction for its operand list. We have to assume that there is one
1807 // result, as we have no detailed info.
1808 if (!LI || LI->getSize() == 0) {
1809 std::vector<Record*> Results;
1810 std::vector<Record*> Operands;
1811
1812 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1813
1814 if (InstInfo.OperandList.size() != 0) {
1815 if (InstInfo.NumDefs == 0) {
1816 // These produce no results
1817 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1818 Operands.push_back(InstInfo.OperandList[j].Rec);
1819 } else {
1820 // Assume the first operand is the result.
1821 Results.push_back(InstInfo.OperandList[0].Rec);
1822
1823 // The rest are inputs.
1824 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1825 Operands.push_back(InstInfo.OperandList[j].Rec);
1826 }
1827 }
1828
1829 // Create and insert the instruction.
1830 std::vector<Record*> ImpResults;
1831 std::vector<Record*> ImpOperands;
1832 Instructions.insert(std::make_pair(Instrs[i],
1833 DAGInstruction(0, Results, Operands, ImpResults,
1834 ImpOperands)));
1835 continue; // no pattern.
1836 }
1837
1838 // Parse the instruction.
1839 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1840 // Inline pattern fragments into it.
1841 I->InlinePatternFragments();
1842
1843 // Infer as many types as possible. If we cannot infer all of them, we can
1844 // never do anything with this instruction pattern: report it to the user.
1845 if (!I->InferAllTypes())
1846 I->error("Could not infer all types in pattern!");
1847
1848 // InstInputs - Keep track of all of the inputs of the instruction, along
1849 // with the record they are declared as.
1850 std::map<std::string, TreePatternNode*> InstInputs;
1851
1852 // InstResults - Keep track of all the virtual registers that are 'set'
1853 // in the instruction, including what reg class they are.
1854 std::map<std::string, TreePatternNode*> InstResults;
1855
1856 std::vector<Record*> InstImpInputs;
1857 std::vector<Record*> InstImpResults;
1858
1859 // Verify that the top-level forms in the instruction are of void type, and
1860 // fill in the InstResults map.
1861 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1862 TreePatternNode *Pat = I->getTree(j);
Owen Anderson825b72b2009-08-11 20:47:22 +00001863 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00001864 I->error("Top-level forms in instruction pattern should have"
1865 " void types");
1866
1867 // Find inputs and outputs, and verify the structure of the uses/defs.
1868 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1869 InstImpInputs, InstImpResults);
1870 }
1871
1872 // Now that we have inputs and outputs of the pattern, inspect the operands
1873 // list for the instruction. This determines the order that operands are
1874 // added to the machine instruction the node corresponds to.
1875 unsigned NumResults = InstResults.size();
1876
1877 // Parse the operands list from the (ops) list, validating it.
1878 assert(I->getArgList().empty() && "Args list should still be empty here!");
1879 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1880
1881 // Check that all of the results occur first in the list.
1882 std::vector<Record*> Results;
1883 TreePatternNode *Res0Node = NULL;
1884 for (unsigned i = 0; i != NumResults; ++i) {
1885 if (i == CGI.OperandList.size())
1886 I->error("'" + InstResults.begin()->first +
1887 "' set but does not appear in operand list!");
1888 const std::string &OpName = CGI.OperandList[i].Name;
1889
1890 // Check that it exists in InstResults.
1891 TreePatternNode *RNode = InstResults[OpName];
1892 if (RNode == 0)
1893 I->error("Operand $" + OpName + " does not exist in operand list!");
1894
1895 if (i == 0)
1896 Res0Node = RNode;
1897 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1898 if (R == 0)
1899 I->error("Operand $" + OpName + " should be a set destination: all "
1900 "outputs must occur before inputs in operand list!");
1901
1902 if (CGI.OperandList[i].Rec != R)
1903 I->error("Operand $" + OpName + " class mismatch!");
1904
1905 // Remember the return type.
1906 Results.push_back(CGI.OperandList[i].Rec);
1907
1908 // Okay, this one checks out.
1909 InstResults.erase(OpName);
1910 }
1911
1912 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1913 // the copy while we're checking the inputs.
1914 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1915
1916 std::vector<TreePatternNode*> ResultNodeOperands;
1917 std::vector<Record*> Operands;
1918 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1919 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1920 const std::string &OpName = Op.Name;
1921 if (OpName.empty())
1922 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1923
1924 if (!InstInputsCheck.count(OpName)) {
1925 // If this is an predicate operand or optional def operand with an
1926 // DefaultOps set filled in, we can ignore this. When we codegen it,
1927 // we will do so as always executed.
1928 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1929 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1930 // Does it have a non-empty DefaultOps field? If so, ignore this
1931 // operand.
1932 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1933 continue;
1934 }
1935 I->error("Operand $" + OpName +
1936 " does not appear in the instruction pattern");
1937 }
1938 TreePatternNode *InVal = InstInputsCheck[OpName];
1939 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1940
1941 if (InVal->isLeaf() &&
1942 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1943 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1944 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1945 I->error("Operand $" + OpName + "'s register class disagrees"
1946 " between the operand and pattern");
1947 }
1948 Operands.push_back(Op.Rec);
1949
1950 // Construct the result for the dest-pattern operand list.
1951 TreePatternNode *OpNode = InVal->clone();
1952
1953 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00001954 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001955
1956 // Promote the xform function to be an explicit node if set.
1957 if (Record *Xform = OpNode->getTransformFn()) {
1958 OpNode->setTransformFn(0);
1959 std::vector<TreePatternNode*> Children;
1960 Children.push_back(OpNode);
1961 OpNode = new TreePatternNode(Xform, Children);
1962 }
1963
1964 ResultNodeOperands.push_back(OpNode);
1965 }
1966
1967 if (!InstInputsCheck.empty())
1968 I->error("Input operand $" + InstInputsCheck.begin()->first +
1969 " occurs in pattern but not in operands list!");
1970
1971 TreePatternNode *ResultPattern =
1972 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1973 // Copy fully inferred output node type to instruction result pattern.
1974 if (NumResults > 0)
1975 ResultPattern->setTypes(Res0Node->getExtTypes());
1976
1977 // Create and insert the instruction.
1978 // FIXME: InstImpResults and InstImpInputs should not be part of
1979 // DAGInstruction.
1980 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1981 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1982
1983 // Use a temporary tree pattern to infer all types and make sure that the
1984 // constructed result is correct. This depends on the instruction already
1985 // being inserted into the Instructions map.
1986 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1987 Temp.InferAllTypes();
1988
1989 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1990 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1991
1992 DEBUG(I->dump());
1993 }
1994
1995 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001996 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
1997 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001998 E = Instructions.end(); II != E; ++II) {
1999 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002000 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002001 if (I == 0) continue; // No pattern.
2002
2003 // FIXME: Assume only the first tree is the pattern. The others are clobber
2004 // nodes.
2005 TreePatternNode *Pattern = I->getTree(0);
2006 TreePatternNode *SrcPattern;
2007 if (Pattern->getOperator()->getName() == "set") {
2008 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2009 } else{
2010 // Not a set (store or something?)
2011 SrcPattern = Pattern;
2012 }
2013
2014 std::string Reason;
2015 if (!SrcPattern->canPatternMatch(Reason, *this))
2016 I->error("Instruction can never match: " + Reason);
2017
2018 Record *Instr = II->first;
2019 TreePatternNode *DstPattern = TheInst.getResultPattern();
2020 PatternsToMatch.
2021 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
2022 SrcPattern, DstPattern, TheInst.getImpResults(),
2023 Instr->getValueAsInt("AddedComplexity")));
2024 }
2025}
2026
Dan Gohmanee4fa192008-04-03 00:02:49 +00002027
2028void CodeGenDAGPatterns::InferInstructionFlags() {
2029 std::map<std::string, CodeGenInstruction> &InstrDescs =
2030 Target.getInstructions();
2031 for (std::map<std::string, CodeGenInstruction>::iterator
2032 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2033 CodeGenInstruction &InstInfo = II->second;
2034 // Determine properties of the instruction from its pattern.
2035 bool MayStore, MayLoad, HasSideEffects;
2036 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2037 InstInfo.mayStore = MayStore;
2038 InstInfo.mayLoad = MayLoad;
2039 InstInfo.hasSideEffects = HasSideEffects;
2040 }
2041}
2042
Chris Lattnerfe718932008-01-06 01:10:31 +00002043void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002044 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2045
2046 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2047 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2048 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2049 Record *Operator = OpDef->getDef();
2050 TreePattern *Pattern;
2051 if (Operator->getName() != "parallel")
2052 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2053 else {
2054 std::vector<Init*> Values;
David Greenee1b46912009-06-08 20:23:18 +00002055 RecTy *ListTy = 0;
2056 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002057 Values.push_back(Tree->getArg(j));
David Greenee1b46912009-06-08 20:23:18 +00002058 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2059 if (TArg == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002060 errs() << "In dag: " << Tree->getAsString();
2061 errs() << " -- Untyped argument in pattern\n";
David Greenee1b46912009-06-08 20:23:18 +00002062 assert(0 && "Untyped argument in pattern");
2063 }
2064 if (ListTy != 0) {
2065 ListTy = resolveTypes(ListTy, TArg->getType());
2066 if (ListTy == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002067 errs() << "In dag: " << Tree->getAsString();
2068 errs() << " -- Incompatible types in pattern arguments\n";
David Greenee1b46912009-06-08 20:23:18 +00002069 assert(0 && "Incompatible types in pattern arguments");
2070 }
2071 }
2072 else {
Bill Wendlingee1f6b02009-06-09 18:49:42 +00002073 ListTy = TArg->getType();
David Greenee1b46912009-06-08 20:23:18 +00002074 }
2075 }
2076 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
Chris Lattner6cefb772008-01-05 22:25:12 +00002077 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2078 }
2079
2080 // Inline pattern fragments into it.
2081 Pattern->InlinePatternFragments();
2082
2083 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2084 if (LI->getSize() == 0) continue; // no pattern.
2085
2086 // Parse the instruction.
2087 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2088
2089 // Inline pattern fragments into it.
2090 Result->InlinePatternFragments();
2091
2092 if (Result->getNumTrees() != 1)
2093 Result->error("Cannot handle instructions producing instructions "
2094 "with temporaries yet!");
2095
2096 bool IterateInference;
2097 bool InferredAllPatternTypes, InferredAllResultTypes;
2098 do {
2099 // Infer as many types as possible. If we cannot infer all of them, we
2100 // can never do anything with this pattern: report it to the user.
2101 InferredAllPatternTypes = Pattern->InferAllTypes();
2102
2103 // Infer as many types as possible. If we cannot infer all of them, we
2104 // can never do anything with this pattern: report it to the user.
2105 InferredAllResultTypes = Result->InferAllTypes();
2106
2107 // Apply the type of the result to the source pattern. This helps us
2108 // resolve cases where the input type is known to be a pointer type (which
2109 // is considered resolved), but the result knows it needs to be 32- or
2110 // 64-bits. Infer the other way for good measure.
2111 IterateInference = Pattern->getTree(0)->
2112 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2113 IterateInference |= Result->getTree(0)->
2114 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2115 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002116
Chris Lattner6cefb772008-01-05 22:25:12 +00002117 // Verify that we inferred enough types that we can do something with the
2118 // pattern and result. If these fire the user has to add type casts.
2119 if (!InferredAllPatternTypes)
2120 Pattern->error("Could not infer all types in pattern!");
2121 if (!InferredAllResultTypes)
2122 Result->error("Could not infer all types in pattern result!");
2123
2124 // Validate that the input pattern is correct.
2125 std::map<std::string, TreePatternNode*> InstInputs;
2126 std::map<std::string, TreePatternNode*> InstResults;
2127 std::vector<Record*> InstImpInputs;
2128 std::vector<Record*> InstImpResults;
2129 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2130 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2131 InstInputs, InstResults,
2132 InstImpInputs, InstImpResults);
2133
2134 // Promote the xform function to be an explicit node if set.
2135 TreePatternNode *DstPattern = Result->getOnlyTree();
2136 std::vector<TreePatternNode*> ResultNodeOperands;
2137 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2138 TreePatternNode *OpNode = DstPattern->getChild(ii);
2139 if (Record *Xform = OpNode->getTransformFn()) {
2140 OpNode->setTransformFn(0);
2141 std::vector<TreePatternNode*> Children;
2142 Children.push_back(OpNode);
2143 OpNode = new TreePatternNode(Xform, Children);
2144 }
2145 ResultNodeOperands.push_back(OpNode);
2146 }
2147 DstPattern = Result->getOnlyTree();
2148 if (!DstPattern->isLeaf())
2149 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2150 ResultNodeOperands);
2151 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2152 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2153 Temp.InferAllTypes();
2154
2155 std::string Reason;
2156 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2157 Pattern->error("Pattern can never match: " + Reason);
2158
2159 PatternsToMatch.
2160 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2161 Pattern->getTree(0),
2162 Temp.getOnlyTree(), InstImpResults,
2163 Patterns[i]->getValueAsInt("AddedComplexity")));
2164 }
2165}
2166
2167/// CombineChildVariants - Given a bunch of permutations of each child of the
2168/// 'operator' node, put them together in all possible ways.
2169static void CombineChildVariants(TreePatternNode *Orig,
2170 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2171 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002172 CodeGenDAGPatterns &CDP,
2173 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002174 // Make sure that each operand has at least one variant to choose from.
2175 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2176 if (ChildVariants[i].empty())
2177 return;
2178
2179 // The end result is an all-pairs construction of the resultant pattern.
2180 std::vector<unsigned> Idxs;
2181 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002182 bool NotDone;
2183 do {
2184#ifndef NDEBUG
2185 if (DebugFlag && !Idxs.empty()) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002186 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Scott Michel327d0652008-03-05 17:49:05 +00002187 for (unsigned i = 0; i < Idxs.size(); ++i) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002188 errs() << Idxs[i] << " ";
Scott Michel327d0652008-03-05 17:49:05 +00002189 }
Daniel Dunbar1a551802009-07-03 00:10:29 +00002190 errs() << "]\n";
Scott Michel327d0652008-03-05 17:49:05 +00002191 }
2192#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002193 // Create the variant and add it to the output list.
2194 std::vector<TreePatternNode*> NewChildren;
2195 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2196 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2197 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2198
2199 // Copy over properties.
2200 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002201 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002202 R->setTransformFn(Orig->getTransformFn());
2203 R->setTypes(Orig->getExtTypes());
2204
Scott Michel327d0652008-03-05 17:49:05 +00002205 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002206 std::string ErrString;
2207 if (!R->canPatternMatch(ErrString, CDP)) {
2208 delete R;
2209 } else {
2210 bool AlreadyExists = false;
2211
2212 // Scan to see if this pattern has already been emitted. We can get
2213 // duplication due to things like commuting:
2214 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2215 // which are the same pattern. Ignore the dups.
2216 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002217 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002218 AlreadyExists = true;
2219 break;
2220 }
2221
2222 if (AlreadyExists)
2223 delete R;
2224 else
2225 OutVariants.push_back(R);
2226 }
2227
Scott Michel327d0652008-03-05 17:49:05 +00002228 // Increment indices to the next permutation by incrementing the
2229 // indicies from last index backward, e.g., generate the sequence
2230 // [0, 0], [0, 1], [1, 0], [1, 1].
2231 int IdxsIdx;
2232 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2233 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2234 Idxs[IdxsIdx] = 0;
2235 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002236 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002237 }
Scott Michel327d0652008-03-05 17:49:05 +00002238 NotDone = (IdxsIdx >= 0);
2239 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002240}
2241
2242/// CombineChildVariants - A helper function for binary operators.
2243///
2244static void CombineChildVariants(TreePatternNode *Orig,
2245 const std::vector<TreePatternNode*> &LHS,
2246 const std::vector<TreePatternNode*> &RHS,
2247 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002248 CodeGenDAGPatterns &CDP,
2249 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002250 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2251 ChildVariants.push_back(LHS);
2252 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002253 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002254}
2255
2256
2257static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2258 std::vector<TreePatternNode *> &Children) {
2259 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2260 Record *Operator = N->getOperator();
2261
2262 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002263 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002264 N->getTransformFn()) {
2265 Children.push_back(N);
2266 return;
2267 }
2268
2269 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2270 Children.push_back(N->getChild(0));
2271 else
2272 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2273
2274 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2275 Children.push_back(N->getChild(1));
2276 else
2277 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2278}
2279
2280/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2281/// the (potentially recursive) pattern by using algebraic laws.
2282///
2283static void GenerateVariantsOf(TreePatternNode *N,
2284 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002285 CodeGenDAGPatterns &CDP,
2286 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002287 // We cannot permute leaves.
2288 if (N->isLeaf()) {
2289 OutVariants.push_back(N);
2290 return;
2291 }
2292
2293 // Look up interesting info about the node.
2294 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2295
Jim Grosbachda4231f2009-03-26 16:17:51 +00002296 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002297 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002298 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002299 std::vector<TreePatternNode*> MaximalChildren;
2300 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2301
2302 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2303 // permutations.
2304 if (MaximalChildren.size() == 3) {
2305 // Find the variants of all of our maximal children.
2306 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002307 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2308 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2309 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002310
2311 // There are only two ways we can permute the tree:
2312 // (A op B) op C and A op (B op C)
2313 // Within these forms, we can also permute A/B/C.
2314
2315 // Generate legal pair permutations of A/B/C.
2316 std::vector<TreePatternNode*> ABVariants;
2317 std::vector<TreePatternNode*> BAVariants;
2318 std::vector<TreePatternNode*> ACVariants;
2319 std::vector<TreePatternNode*> CAVariants;
2320 std::vector<TreePatternNode*> BCVariants;
2321 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002322 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2323 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2324 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2325 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2326 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2327 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002328
2329 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002330 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2331 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2332 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2333 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2334 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2335 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002336
2337 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002338 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2339 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2340 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2341 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2342 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2343 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002344 return;
2345 }
2346 }
2347
2348 // Compute permutations of all children.
2349 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2350 ChildVariants.resize(N->getNumChildren());
2351 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002352 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002353
2354 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002355 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002356
2357 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002358 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2359 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2360 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2361 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002362 // Don't count children which are actually register references.
2363 unsigned NC = 0;
2364 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2365 TreePatternNode *Child = N->getChild(i);
2366 if (Child->isLeaf())
2367 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2368 Record *RR = DI->getDef();
2369 if (RR->isSubClassOf("Register"))
2370 continue;
2371 }
2372 NC++;
2373 }
2374 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002375 if (isCommIntrinsic) {
2376 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2377 // operands are the commutative operands, and there might be more operands
2378 // after those.
2379 assert(NC >= 3 &&
2380 "Commutative intrinsic should have at least 3 childrean!");
2381 std::vector<std::vector<TreePatternNode*> > Variants;
2382 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2383 Variants.push_back(ChildVariants[2]);
2384 Variants.push_back(ChildVariants[1]);
2385 for (unsigned i = 3; i != NC; ++i)
2386 Variants.push_back(ChildVariants[i]);
2387 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2388 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002389 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002390 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002391 }
2392}
2393
2394
2395// GenerateVariants - Generate variants. For example, commutative patterns can
2396// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002397void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00002398 DEBUG(errs() << "Generating instruction variants.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002399
2400 // Loop over all of the patterns we've collected, checking to see if we can
2401 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002402 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002403 // the .td file having to contain tons of variants of instructions.
2404 //
2405 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2406 // intentionally do not reconsider these. Any variants of added patterns have
2407 // already been added.
2408 //
2409 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002410 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002411 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002412 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00002413 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00002414 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00002415 DEBUG(errs() << "\n");
Scott Michel327d0652008-03-05 17:49:05 +00002416 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002417
2418 assert(!Variants.empty() && "Must create at least original variant!");
2419 Variants.erase(Variants.begin()); // Remove the original pattern.
2420
2421 if (Variants.empty()) // No variants for this pattern.
2422 continue;
2423
Chris Lattner569f1212009-08-23 04:44:11 +00002424 DEBUG(errs() << "FOUND VARIANTS OF: ";
2425 PatternsToMatch[i].getSrcPattern()->dump();
2426 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002427
2428 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2429 TreePatternNode *Variant = Variants[v];
2430
Chris Lattner569f1212009-08-23 04:44:11 +00002431 DEBUG(errs() << " VAR#" << v << ": ";
2432 Variant->dump();
2433 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002434
2435 // Scan to see if an instruction or explicit pattern already matches this.
2436 bool AlreadyExists = false;
2437 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00002438 // Skip if the top level predicates do not match.
2439 if (PatternsToMatch[i].getPredicates() !=
2440 PatternsToMatch[p].getPredicates())
2441 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00002442 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002443 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00002444 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002445 AlreadyExists = true;
2446 break;
2447 }
2448 }
2449 // If we already have it, ignore the variant.
2450 if (AlreadyExists) continue;
2451
2452 // Otherwise, add it to the list of patterns we have.
2453 PatternsToMatch.
2454 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2455 Variant, PatternsToMatch[i].getDstPattern(),
2456 PatternsToMatch[i].getDstRegs(),
2457 PatternsToMatch[i].getAddedComplexity()));
2458 }
2459
Chris Lattner569f1212009-08-23 04:44:11 +00002460 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002461 }
2462}
2463