blob: 3d29f64eaef55bc313a6dbb25fc2a533896eb6a6 [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.
Bill Wendling7529ece2009-12-25 13:35:40 +0000324 bool MadeChange = OtherNode->UpdateNodeType(MVT::iAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000325
326 // This code only handles nodes that have one type set. Assert here so
327 // that we can change this if we ever need to deal with multiple value
328 // types at this point.
329 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
330 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Owen Anderson825b72b2009-08-11 20:47:22 +0000331 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
Bill Wendling7529ece2009-12-25 13:35:40 +0000332 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +0000333 }
334 case SDTCisOpSmallerThanOp: {
335 TreePatternNode *BigOperand =
336 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
337
338 // Both operands must be integer or FP, but we don't care which.
339 bool MadeChange = false;
340
341 // This code does not currently handle nodes which have multiple types,
342 // where some types are integer, and some are fp. Assert that this is not
343 // the case.
Owen Andersone50ed302009-08-10 22:56:29 +0000344 assert(!(EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
345 EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
346 !(EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
347 EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000348 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
Owen Andersone50ed302009-08-10 22:56:29 +0000349 if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000350 MadeChange |= BigOperand->UpdateNodeType(MVT::iAny, TP);
Owen Andersone50ed302009-08-10 22:56:29 +0000351 else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000352 MadeChange |= BigOperand->UpdateNodeType(MVT::fAny, TP);
Owen Andersone50ed302009-08-10 22:56:29 +0000353 if (EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000354 MadeChange |= NodeToApply->UpdateNodeType(MVT::iAny, TP);
Owen Andersone50ed302009-08-10 22:56:29 +0000355 else if (EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000356 MadeChange |= NodeToApply->UpdateNodeType(MVT::fAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000357
Owen Anderson825b72b2009-08-11 20:47:22 +0000358 std::vector<MVT::SimpleValueType> VTs = CGT.getLegalValueTypes();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000359
Owen Andersone50ed302009-08-10 22:56:29 +0000360 if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000361 VTs = FilterVTs(VTs, isInteger);
Owen Andersone50ed302009-08-10 22:56:29 +0000362 } else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000363 VTs = FilterVTs(VTs, isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000364 } else {
365 VTs.clear();
366 }
367
368 switch (VTs.size()) {
369 default: // Too many VT's to pick from.
370 case 0: break; // No info yet.
371 case 1:
Jim Grosbachda4231f2009-03-26 16:17:51 +0000372 // Only one VT of this flavor. Cannot ever satisfy the constraints.
Owen Anderson825b72b2009-08-11 20:47:22 +0000373 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
Chris Lattner6cefb772008-01-05 22:25:12 +0000374 case 2:
375 // If we have exactly two possible types, the little operand must be the
376 // small one, the big operand should be the big one. Common with
377 // float/double for example.
378 assert(VTs[0] < VTs[1] && "Should be sorted!");
379 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
380 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
381 break;
382 }
383 return MadeChange;
384 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000385 case SDTCisEltOfVec: {
386 TreePatternNode *OtherOperand =
Nate Begeman9008ca62009-04-27 18:41:29 +0000387 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum,
Nate Begemanb5af3342008-02-09 01:37:05 +0000388 N, NumResults);
389 if (OtherOperand->hasTypeSet()) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000390 if (!isVector(OtherOperand->getTypeNum(0)))
Nate Begemanb5af3342008-02-09 01:37:05 +0000391 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Owen Andersone50ed302009-08-10 22:56:29 +0000392 EVT IVT = OtherOperand->getTypeNum(0);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000393 IVT = IVT.getVectorElementType();
Owen Anderson825b72b2009-08-11 20:47:22 +0000394 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000395 }
396 return false;
397 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000398 }
399 return false;
400}
401
402//===----------------------------------------------------------------------===//
403// SDNodeInfo implementation
404//
405SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
406 EnumName = R->getValueAsString("Opcode");
407 SDClassName = R->getValueAsString("SDClass");
408 Record *TypeProfile = R->getValueAsDef("TypeProfile");
409 NumResults = TypeProfile->getValueAsInt("NumResults");
410 NumOperands = TypeProfile->getValueAsInt("NumOperands");
411
412 // Parse the properties.
413 Properties = 0;
414 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
415 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
416 if (PropList[i]->getName() == "SDNPCommutative") {
417 Properties |= 1 << SDNPCommutative;
418 } else if (PropList[i]->getName() == "SDNPAssociative") {
419 Properties |= 1 << SDNPAssociative;
420 } else if (PropList[i]->getName() == "SDNPHasChain") {
421 Properties |= 1 << SDNPHasChain;
422 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen874ae252009-06-02 03:12:52 +0000423 Properties |= 1 << SDNPOutFlag;
Chris Lattner6cefb772008-01-05 22:25:12 +0000424 } else if (PropList[i]->getName() == "SDNPInFlag") {
425 Properties |= 1 << SDNPInFlag;
426 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
427 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000428 } else if (PropList[i]->getName() == "SDNPMayStore") {
429 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000430 } else if (PropList[i]->getName() == "SDNPMayLoad") {
431 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000432 } else if (PropList[i]->getName() == "SDNPSideEffect") {
433 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000434 } else if (PropList[i]->getName() == "SDNPMemOperand") {
435 Properties |= 1 << SDNPMemOperand;
Chris Lattner6cefb772008-01-05 22:25:12 +0000436 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000437 errs() << "Unknown SD Node property '" << PropList[i]->getName()
438 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000439 exit(1);
440 }
441 }
442
443
444 // Parse the type constraints.
445 std::vector<Record*> ConstraintList =
446 TypeProfile->getValueAsListOfDefs("Constraints");
447 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
448}
449
450//===----------------------------------------------------------------------===//
451// TreePatternNode implementation
452//
453
454TreePatternNode::~TreePatternNode() {
455#if 0 // FIXME: implement refcounted tree nodes!
456 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
457 delete getChild(i);
458#endif
459}
460
461/// UpdateNodeType - Set the node type of N to VT if VT contains
462/// information. If N already contains a conflicting type, then throw an
463/// exception. This returns true if any information was updated.
464///
465bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
466 TreePattern &TP) {
467 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
468
Owen Andersone50ed302009-08-10 22:56:29 +0000469 if (ExtVTs[0] == EEVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
Chris Lattner6cefb772008-01-05 22:25:12 +0000470 return false;
471 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
472 setTypes(ExtVTs);
473 return true;
474 }
475
Owen Anderson825b72b2009-08-11 20:47:22 +0000476 if (getExtTypeNum(0) == MVT::iPTR || getExtTypeNum(0) == MVT::iPTRAny) {
477 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny ||
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000478 ExtVTs[0] == MVT::iAny)
Chris Lattner6cefb772008-01-05 22:25:12 +0000479 return false;
Owen Andersone50ed302009-08-10 22:56:29 +0000480 if (EEVT::isExtIntegerInVTs(ExtVTs)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000481 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000482 if (FVTs.size()) {
483 setTypes(ExtVTs);
484 return true;
485 }
486 }
487 }
Bob Wilsone035fa52009-01-05 17:52:54 +0000488
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000489 // Merge vAny with iAny/fAny. The latter include vector types so keep them
490 // as the more specific information.
491 if (ExtVTs[0] == MVT::vAny &&
492 (getExtTypeNum(0) == MVT::iAny || getExtTypeNum(0) == MVT::fAny))
493 return false;
494 if (getExtTypeNum(0) == MVT::vAny &&
495 (ExtVTs[0] == MVT::iAny || ExtVTs[0] == MVT::fAny)) {
496 setTypes(ExtVTs);
497 return true;
498 }
499
500 if (ExtVTs[0] == MVT::iAny &&
Owen Andersone50ed302009-08-10 22:56:29 +0000501 EEVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000502 assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000503 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000504 if (getExtTypes() == FVTs)
505 return false;
506 setTypes(FVTs);
507 return true;
508 }
Owen Anderson825b72b2009-08-11 20:47:22 +0000509 if ((ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny) &&
Owen Andersone50ed302009-08-10 22:56:29 +0000510 EEVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000511 //assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000512 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000513 if (getExtTypes() == FVTs)
514 return false;
515 if (FVTs.size()) {
516 setTypes(FVTs);
517 return true;
518 }
519 }
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000520 if (ExtVTs[0] == MVT::fAny &&
Owen Andersone50ed302009-08-10 22:56:29 +0000521 EEVT::isExtFloatingPointInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000522 assert(hasTypeSet() && "should be handled above!");
523 std::vector<unsigned char> FVTs =
Duncan Sands83ec4b62008-06-06 12:08:01 +0000524 FilterEVTs(getExtTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000525 if (getExtTypes() == FVTs)
526 return false;
527 setTypes(FVTs);
528 return true;
529 }
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000530 if (ExtVTs[0] == MVT::vAny &&
Bob Wilson36e3e662009-08-12 22:30:59 +0000531 EEVT::isExtVectorInVTs(getExtTypes())) {
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000532 assert(hasTypeSet() && "should be handled above!");
533 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isVector);
534 if (getExtTypes() == FVTs)
535 return false;
536 setTypes(FVTs);
537 return true;
538 }
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000539
Bob Wilson36e3e662009-08-12 22:30:59 +0000540 // If we know this is an int, FP, or vector type, and we are told it is a
541 // specific one, take the advice.
Chris Lattner6cefb772008-01-05 22:25:12 +0000542 //
543 // Similarly, we should probably set the type here to the intersection of
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000544 // {iAny|fAny|vAny} and ExtVTs
545 if ((getExtTypeNum(0) == MVT::iAny &&
Owen Andersone50ed302009-08-10 22:56:29 +0000546 EEVT::isExtIntegerInVTs(ExtVTs)) ||
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000547 (getExtTypeNum(0) == MVT::fAny &&
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000548 EEVT::isExtFloatingPointInVTs(ExtVTs)) ||
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000549 (getExtTypeNum(0) == MVT::vAny &&
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000550 EEVT::isExtVectorInVTs(ExtVTs))) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000551 setTypes(ExtVTs);
552 return true;
553 }
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000554 if (getExtTypeNum(0) == MVT::iAny &&
Owen Anderson825b72b2009-08-11 20:47:22 +0000555 (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000556 setTypes(ExtVTs);
557 return true;
558 }
559
560 if (isLeaf()) {
561 dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000562 errs() << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000563 TP.error("Type inference contradiction found in node!");
564 } else {
565 TP.error("Type inference contradiction found in node " +
566 getOperator()->getName() + "!");
567 }
568 return true; // unreachable
569}
570
571
Daniel Dunbar1a551802009-07-03 00:10:29 +0000572void TreePatternNode::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000573 if (isLeaf()) {
574 OS << *getLeafValue();
575 } else {
576 OS << "(" << getOperator()->getName();
577 }
578
579 // FIXME: At some point we should handle printing all the value types for
580 // nodes that are multiply typed.
581 switch (getExtTypeNum(0)) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000582 case MVT::Other: OS << ":Other"; break;
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000583 case MVT::iAny: OS << ":iAny"; break;
584 case MVT::fAny : OS << ":fAny"; break;
585 case MVT::vAny: OS << ":vAny"; break;
Owen Andersone50ed302009-08-10 22:56:29 +0000586 case EEVT::isUnknown: ; /*OS << ":?";*/ break;
Owen Anderson825b72b2009-08-11 20:47:22 +0000587 case MVT::iPTR: OS << ":iPTR"; break;
588 case MVT::iPTRAny: OS << ":iPTRAny"; break;
Chris Lattner6cefb772008-01-05 22:25:12 +0000589 default: {
590 std::string VTName = llvm::getName(getTypeNum(0));
Owen Andersone50ed302009-08-10 22:56:29 +0000591 // Strip off EVT:: prefix if present.
Owen Anderson825b72b2009-08-11 20:47:22 +0000592 if (VTName.substr(0,5) == "MVT::")
Chris Lattner6cefb772008-01-05 22:25:12 +0000593 VTName = VTName.substr(5);
594 OS << ":" << VTName;
595 break;
596 }
597 }
598
599 if (!isLeaf()) {
600 if (getNumChildren() != 0) {
601 OS << " ";
602 getChild(0)->print(OS);
603 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
604 OS << ", ";
605 getChild(i)->print(OS);
606 }
607 }
608 OS << ")";
609 }
610
Dan Gohman0540e172008-10-15 06:17:21 +0000611 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
612 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000613 if (TransformFn)
614 OS << "<<X:" << TransformFn->getName() << ">>";
615 if (!getName().empty())
616 OS << ":$" << getName();
617
618}
619void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000620 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000621}
622
Scott Michel327d0652008-03-05 17:49:05 +0000623/// isIsomorphicTo - Return true if this node is recursively
624/// isomorphic to the specified node. For this comparison, the node's
625/// entire state is considered. The assigned name is ignored, since
626/// nodes with differing names are considered isomorphic. However, if
627/// the assigned name is present in the dependent variable set, then
628/// the assigned name is considered significant and the node is
629/// isomorphic if the names match.
630bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
631 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000632 if (N == this) return true;
633 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000634 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000635 getTransformFn() != N->getTransformFn())
636 return false;
637
638 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000639 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
640 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000641 return ((DI->getDef() == NDI->getDef())
642 && (DepVars.find(getName()) == DepVars.end()
643 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000644 }
645 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000646 return getLeafValue() == N->getLeafValue();
647 }
648
649 if (N->getOperator() != getOperator() ||
650 N->getNumChildren() != getNumChildren()) return false;
651 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000652 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000653 return false;
654 return true;
655}
656
657/// clone - Make a copy of this tree and all of its children.
658///
659TreePatternNode *TreePatternNode::clone() const {
660 TreePatternNode *New;
661 if (isLeaf()) {
662 New = new TreePatternNode(getLeafValue());
663 } else {
664 std::vector<TreePatternNode*> CChildren;
665 CChildren.reserve(Children.size());
666 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
667 CChildren.push_back(getChild(i)->clone());
668 New = new TreePatternNode(getOperator(), CChildren);
669 }
670 New->setName(getName());
671 New->setTypes(getExtTypes());
Dan Gohman0540e172008-10-15 06:17:21 +0000672 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000673 New->setTransformFn(getTransformFn());
674 return New;
675}
676
Chris Lattner47661322010-02-14 22:22:58 +0000677/// RemoveAllTypes - Recursively strip all the types of this tree.
678void TreePatternNode::RemoveAllTypes() {
679 removeTypes();
680 if (isLeaf()) return;
681 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
682 getChild(i)->RemoveAllTypes();
683}
684
685
Chris Lattner6cefb772008-01-05 22:25:12 +0000686/// SubstituteFormalArguments - Replace the formal arguments in this tree
687/// with actual values specified by ArgMap.
688void TreePatternNode::
689SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
690 if (isLeaf()) return;
691
692 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
693 TreePatternNode *Child = getChild(i);
694 if (Child->isLeaf()) {
695 Init *Val = Child->getLeafValue();
696 if (dynamic_cast<DefInit*>(Val) &&
697 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
698 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000699 TreePatternNode *NewChild = ArgMap[Child->getName()];
700 assert(NewChild && "Couldn't find formal argument!");
701 assert((Child->getPredicateFns().empty() ||
702 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
703 "Non-empty child predicate clobbered!");
704 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000705 }
706 } else {
707 getChild(i)->SubstituteFormalArguments(ArgMap);
708 }
709 }
710}
711
712
713/// InlinePatternFragments - If this pattern refers to any pattern
714/// fragments, inline them into place, giving us a pattern without any
715/// PatFrag references.
716TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
717 if (isLeaf()) return this; // nothing to do.
718 Record *Op = getOperator();
719
720 if (!Op->isSubClassOf("PatFrag")) {
721 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000722 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
723 TreePatternNode *Child = getChild(i);
724 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
725
726 assert((Child->getPredicateFns().empty() ||
727 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
728 "Non-empty child predicate clobbered!");
729
730 setChild(i, NewChild);
731 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000732 return this;
733 }
734
735 // Otherwise, we found a reference to a fragment. First, look up its
736 // TreePattern record.
737 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
738
739 // Verify that we are passing the right number of operands.
740 if (Frag->getNumArgs() != Children.size())
741 TP.error("'" + Op->getName() + "' fragment requires " +
742 utostr(Frag->getNumArgs()) + " operands!");
743
744 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
745
Dan Gohman0540e172008-10-15 06:17:21 +0000746 std::string Code = Op->getValueAsCode("Predicate");
747 if (!Code.empty())
748 FragTree->addPredicateFn("Predicate_"+Op->getName());
749
Chris Lattner6cefb772008-01-05 22:25:12 +0000750 // Resolve formal arguments to their actual value.
751 if (Frag->getNumArgs()) {
752 // Compute the map of formal to actual arguments.
753 std::map<std::string, TreePatternNode*> ArgMap;
754 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
755 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
756
757 FragTree->SubstituteFormalArguments(ArgMap);
758 }
759
760 FragTree->setName(getName());
761 FragTree->UpdateNodeType(getExtTypes(), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000762
763 // Transfer in the old predicates.
764 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
765 FragTree->addPredicateFn(getPredicateFns()[i]);
766
Chris Lattner6cefb772008-01-05 22:25:12 +0000767 // Get a new copy of this fragment to stitch into here.
768 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000769
770 // The fragment we inlined could have recursive inlining that is needed. See
771 // if there are any pattern fragments in it and inline them as needed.
772 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000773}
774
775/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000776/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +0000777/// references from the register file information, for example.
778///
779static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
Chris Lattner523f6a52010-02-14 21:10:15 +0000780 TreePattern &TP) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000781 // Some common return values
Owen Andersone50ed302009-08-10 22:56:29 +0000782 std::vector<unsigned char> Unknown(1, EEVT::isUnknown);
Owen Anderson825b72b2009-08-11 20:47:22 +0000783 std::vector<unsigned char> Other(1, MVT::Other);
Chris Lattner6cefb772008-01-05 22:25:12 +0000784
785 // Check to see if this is a register or a register class...
786 if (R->isSubClassOf("RegisterClass")) {
787 if (NotRegisters)
788 return Unknown;
789 const CodeGenRegisterClass &RC =
790 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
791 return ConvertVTs(RC.getValueTypes());
792 } else if (R->isSubClassOf("PatFrag")) {
793 // Pattern fragment types will be resolved when they are inlined.
794 return Unknown;
795 } else if (R->isSubClassOf("Register")) {
796 if (NotRegisters)
797 return Unknown;
798 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
799 return T.getRegisterVTs(R);
800 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
801 // Using a VTSDNode or CondCodeSDNode.
802 return Other;
803 } else if (R->isSubClassOf("ComplexPattern")) {
804 if (NotRegisters)
805 return Unknown;
806 std::vector<unsigned char>
807 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
808 return ComplexPat;
Chris Lattnera938ac62009-07-29 20:43:05 +0000809 } else if (R->isSubClassOf("PointerLikeRegClass")) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000810 Other[0] = MVT::iPTR;
Chris Lattner6cefb772008-01-05 22:25:12 +0000811 return Other;
812 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
813 R->getName() == "zero_reg") {
814 // Placeholder.
815 return Unknown;
816 }
817
818 TP.error("Unknown node flavor used in pattern: " + R->getName());
819 return Other;
820}
821
Chris Lattnere67bde52008-01-06 05:36:50 +0000822
823/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
824/// CodeGenIntrinsic information for it, otherwise return a null pointer.
825const CodeGenIntrinsic *TreePatternNode::
826getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
827 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
828 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
829 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
830 return 0;
831
832 unsigned IID =
833 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
834 return &CDP.getIntrinsicInfo(IID);
835}
836
Chris Lattner47661322010-02-14 22:22:58 +0000837/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
838/// return the ComplexPattern information, otherwise return null.
839const ComplexPattern *
840TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
841 if (!isLeaf()) return 0;
842
843 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
844 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
845 return &CGP.getComplexPattern(DI->getDef());
846 return 0;
847}
848
849/// NodeHasProperty - Return true if this node has the specified property.
850bool TreePatternNode::NodeHasProperty(SDNP Property,
851 CodeGenDAGPatterns &CGP) const {
852 if (isLeaf()) {
853 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
854 return CP->hasProperty(Property);
855 return false;
856 }
857
858 Record *Operator = getOperator();
859 if (!Operator->isSubClassOf("SDNode")) return false;
860
861 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
862}
863
864
865
866
867/// TreeHasProperty - Return true if any node in this tree has the specified
868/// property.
869bool TreePatternNode::TreeHasProperty(SDNP Property,
870 CodeGenDAGPatterns &CGP) const {
871 if (NodeHasProperty(Property, CGP))
872 return true;
873 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
874 if (getChild(i)->TreeHasProperty(Property, CGP))
875 return true;
876 return false;
877}
878
Evan Cheng6bd95672008-06-16 20:29:38 +0000879/// isCommutativeIntrinsic - Return true if the node corresponds to a
880/// commutative intrinsic.
881bool
882TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
883 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
884 return Int->isCommutative;
885 return false;
886}
887
Chris Lattnere67bde52008-01-06 05:36:50 +0000888
Bob Wilson6c01ca92009-01-05 17:23:09 +0000889/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +0000890/// this node and its children in the tree. This returns true if it makes a
891/// change, false otherwise. If a type contradiction is found, throw an
892/// exception.
893bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +0000894 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +0000895 if (isLeaf()) {
896 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
897 // If it's a regclass or something else known, include the type.
898 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner523f6a52010-02-14 21:10:15 +0000899 }
900
901 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000902 // Int inits are always integers. :)
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000903 bool MadeChange = UpdateNodeType(MVT::iAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000904
905 if (hasTypeSet()) {
906 // At some point, it may make sense for this tree pattern to have
907 // multiple types. Assert here that it does not, so we revisit this
908 // code when appropriate.
909 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000910 MVT::SimpleValueType VT = getTypeNum(0);
Chris Lattner6cefb772008-01-05 22:25:12 +0000911 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
912 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
913
914 VT = getTypeNum(0);
Owen Anderson825b72b2009-08-11 20:47:22 +0000915 if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
Owen Andersone50ed302009-08-10 22:56:29 +0000916 unsigned Size = EVT(VT).getSizeInBits();
Chris Lattner6cefb772008-01-05 22:25:12 +0000917 // Make sure that the value is representable for this type.
918 if (Size < 32) {
919 int Val = (II->getValue() << (32-Size)) >> (32-Size);
Scott Michel0123b7d2008-02-15 23:05:48 +0000920 if (Val != II->getValue()) {
Bill Wendling27926af2008-02-26 10:45:29 +0000921 // If sign-extended doesn't fit, does it fit as unsigned?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000922 unsigned ValueMask;
923 unsigned UnsignedVal;
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +0000924 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
Duncan Sands83ec4b62008-06-06 12:08:01 +0000925 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +0000926
Bill Wendling27926af2008-02-26 10:45:29 +0000927 if ((ValueMask & UnsignedVal) != UnsignedVal) {
928 TP.error("Integer value '" + itostr(II->getValue())+
929 "' is out of range for type '" +
930 getEnumName(getTypeNum(0)) + "'!");
931 }
932 }
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000933 }
934 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000935 }
936
937 return MadeChange;
938 }
939 return false;
940 }
941
942 // special handling for set, which isn't really an SDNode.
943 if (getOperator()->getName() == "set") {
944 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
945 unsigned NC = getNumChildren();
946 bool MadeChange = false;
947 for (unsigned i = 0; i < NC-1; ++i) {
948 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
949 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
950
951 // Types of operands must match.
952 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
953 TP);
954 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
955 TP);
Owen Anderson825b72b2009-08-11 20:47:22 +0000956 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000957 }
958 return MadeChange;
959 } else if (getOperator()->getName() == "implicit" ||
960 getOperator()->getName() == "parallel") {
961 bool MadeChange = false;
962 for (unsigned i = 0; i < getNumChildren(); ++i)
963 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Owen Anderson825b72b2009-08-11 20:47:22 +0000964 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000965 return MadeChange;
Dan Gohman88c7af02009-04-13 21:06:25 +0000966 } else if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +0000967 bool MadeChange = false;
968 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
969 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Dan Gohmanf8c73942009-04-13 15:38:05 +0000970 return MadeChange;
Chris Lattnere67bde52008-01-06 05:36:50 +0000971 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000972 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000973
Chris Lattner6cefb772008-01-05 22:25:12 +0000974 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000975 unsigned NumRetVTs = Int->IS.RetVTs.size();
976 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000977
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000978 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
979 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
980
981 if (getNumChildren() != NumParamVTs + NumRetVTs)
Chris Lattnere67bde52008-01-06 05:36:50 +0000982 TP.error("Intrinsic '" + Int->Name + "' expects " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000983 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
984 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +0000985
986 // Apply type info to the intrinsic ID.
Owen Anderson825b72b2009-08-11 20:47:22 +0000987 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000988
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000989 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000990 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
Chris Lattner6cefb772008-01-05 22:25:12 +0000991 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
992 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
993 }
994 return MadeChange;
995 } else if (getOperator()->isSubClassOf("SDNode")) {
996 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
997
998 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
999 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1000 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1001 // Branch, etc. do not produce results and top-level forms in instr pattern
1002 // must have void types.
1003 if (NI.getNumResults() == 0)
Owen Anderson825b72b2009-08-11 20:47:22 +00001004 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001005
Chris Lattner6cefb772008-01-05 22:25:12 +00001006 return MadeChange;
1007 } else if (getOperator()->isSubClassOf("Instruction")) {
1008 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1009 bool MadeChange = false;
1010 unsigned NumResults = Inst.getNumResults();
1011
1012 assert(NumResults <= 1 &&
1013 "Only supports zero or one result instrs!");
1014
1015 CodeGenInstruction &InstInfo =
1016 CDP.getTargetInfo().getInstruction(getOperator()->getName());
1017 // Apply the result type to the node
1018 if (NumResults == 0 || InstInfo.NumDefs == 0) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001019 MadeChange = UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001020 } else {
1021 Record *ResultNode = Inst.getResult(0);
1022
Chris Lattnera938ac62009-07-29 20:43:05 +00001023 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001024 std::vector<unsigned char> VT;
Owen Anderson825b72b2009-08-11 20:47:22 +00001025 VT.push_back(MVT::iPTR);
Chris Lattner6cefb772008-01-05 22:25:12 +00001026 MadeChange = UpdateNodeType(VT, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001027 } else if (ResultNode->getName() == "unknown") {
1028 std::vector<unsigned char> VT;
Owen Andersone50ed302009-08-10 22:56:29 +00001029 VT.push_back(EEVT::isUnknown);
Christopher Lamb5b415372008-03-11 09:33:47 +00001030 MadeChange = UpdateNodeType(VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001031 } else {
1032 assert(ResultNode->isSubClassOf("RegisterClass") &&
1033 "Operands should be register classes!");
1034
1035 const CodeGenRegisterClass &RC =
1036 CDP.getTargetInfo().getRegisterClass(ResultNode);
1037 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
1038 }
1039 }
1040
1041 unsigned ChildNo = 0;
1042 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1043 Record *OperandNode = Inst.getOperand(i);
1044
1045 // If the instruction expects a predicate or optional def operand, we
1046 // codegen this by setting the operand to it's default value if it has a
1047 // non-empty DefaultOps field.
1048 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1049 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1050 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1051 continue;
1052
1053 // Verify that we didn't run out of provided operands.
1054 if (ChildNo >= getNumChildren())
1055 TP.error("Instruction '" + getOperator()->getName() +
1056 "' expects more operands than were provided.");
1057
Owen Anderson825b72b2009-08-11 20:47:22 +00001058 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001059 TreePatternNode *Child = getChild(ChildNo++);
1060 if (OperandNode->isSubClassOf("RegisterClass")) {
1061 const CodeGenRegisterClass &RC =
1062 CDP.getTargetInfo().getRegisterClass(OperandNode);
1063 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
1064 } else if (OperandNode->isSubClassOf("Operand")) {
1065 VT = getValueType(OperandNode->getValueAsDef("Type"));
1066 MadeChange |= Child->UpdateNodeType(VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001067 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001068 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001069 } else if (OperandNode->getName() == "unknown") {
Owen Andersone50ed302009-08-10 22:56:29 +00001070 MadeChange |= Child->UpdateNodeType(EEVT::isUnknown, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001071 } else {
1072 assert(0 && "Unknown operand type!");
1073 abort();
1074 }
1075 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1076 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001077
Christopher Lamb02f69372008-03-10 04:16:09 +00001078 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001079 TP.error("Instruction '" + getOperator()->getName() +
1080 "' was provided too many operands!");
1081
1082 return MadeChange;
1083 } else {
1084 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1085
1086 // Node transforms always take one operand.
1087 if (getNumChildren() != 1)
1088 TP.error("Node transform '" + getOperator()->getName() +
1089 "' requires one operand!");
1090
1091 // If either the output or input of the xform does not have exact
1092 // type info. We assume they must be the same. Otherwise, it is perfectly
1093 // legal to transform from one type to a completely different type.
1094 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1095 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
1096 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
1097 return MadeChange;
1098 }
1099 return false;
1100 }
1101}
1102
1103/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1104/// RHS of a commutative operation, not the on LHS.
1105static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1106 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1107 return true;
1108 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1109 return true;
1110 return false;
1111}
1112
1113
1114/// canPatternMatch - If it is impossible for this pattern to match on this
1115/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001116/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001117/// that can never possibly work), and to prevent the pattern permuter from
1118/// generating stuff that is useless.
1119bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001120 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001121 if (isLeaf()) return true;
1122
1123 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1124 if (!getChild(i)->canPatternMatch(Reason, CDP))
1125 return false;
1126
1127 // If this is an intrinsic, handle cases that would make it not match. For
1128 // example, if an operand is required to be an immediate.
1129 if (getOperator()->isSubClassOf("Intrinsic")) {
1130 // TODO:
1131 return true;
1132 }
1133
1134 // If this node is a commutative operator, check that the LHS isn't an
1135 // immediate.
1136 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001137 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1138 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001139 // Scan all of the operands of the node and make sure that only the last one
1140 // is a constant node, unless the RHS also is.
1141 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001142 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1143 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001144 if (OnlyOnRHSOfCommutative(getChild(i))) {
1145 Reason="Immediate value must be on the RHS of commutative operators!";
1146 return false;
1147 }
1148 }
1149 }
1150
1151 return true;
1152}
1153
1154//===----------------------------------------------------------------------===//
1155// TreePattern implementation
1156//
1157
1158TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001159 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001160 isInputPattern = isInput;
1161 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1162 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1163}
1164
1165TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001166 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001167 isInputPattern = isInput;
1168 Trees.push_back(ParseTreePattern(Pat));
1169}
1170
1171TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001172 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001173 isInputPattern = isInput;
1174 Trees.push_back(Pat);
1175}
1176
1177
1178
1179void TreePattern::error(const std::string &Msg) const {
1180 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001181 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001182}
1183
1184TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1185 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1186 if (!OpDef) error("Pattern has unexpected operator type!");
1187 Record *Operator = OpDef->getDef();
1188
1189 if (Operator->isSubClassOf("ValueType")) {
1190 // If the operator is a ValueType, then this must be "type cast" of a leaf
1191 // node.
1192 if (Dag->getNumArgs() != 1)
1193 error("Type cast only takes one operand!");
1194
1195 Init *Arg = Dag->getArg(0);
1196 TreePatternNode *New;
1197 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1198 Record *R = DI->getDef();
1199 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001200 Dag->setArg(0, new DagInit(DI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001201 std::vector<std::pair<Init*, std::string> >()));
1202 return ParseTreePattern(Dag);
1203 }
1204 New = new TreePatternNode(DI);
1205 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1206 New = ParseTreePattern(DI);
1207 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1208 New = new TreePatternNode(II);
1209 if (!Dag->getArgName(0).empty())
1210 error("Constant int argument should not have a name!");
1211 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1212 // Turn this into an IntInit.
1213 Init *II = BI->convertInitializerTo(new IntRecTy());
1214 if (II == 0 || !dynamic_cast<IntInit*>(II))
1215 error("Bits value must be constants!");
1216
1217 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1218 if (!Dag->getArgName(0).empty())
1219 error("Constant int argument should not have a name!");
1220 } else {
1221 Arg->dump();
1222 error("Unknown leaf value for tree pattern!");
1223 return 0;
1224 }
1225
1226 // Apply the type cast.
1227 New->UpdateNodeType(getValueType(Operator), *this);
Nate Begeman7cee8172009-03-19 05:21:56 +00001228 if (New->getNumChildren() == 0)
1229 New->setName(Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001230 return New;
1231 }
1232
1233 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001234 if (!Operator->isSubClassOf("PatFrag") &&
1235 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001236 !Operator->isSubClassOf("Instruction") &&
1237 !Operator->isSubClassOf("SDNodeXForm") &&
1238 !Operator->isSubClassOf("Intrinsic") &&
1239 Operator->getName() != "set" &&
1240 Operator->getName() != "implicit" &&
1241 Operator->getName() != "parallel")
1242 error("Unrecognized node '" + Operator->getName() + "'!");
1243
1244 // Check to see if this is something that is illegal in an input pattern.
1245 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1246 Operator->isSubClassOf("SDNodeXForm")))
1247 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1248
1249 std::vector<TreePatternNode*> Children;
1250
1251 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1252 Init *Arg = Dag->getArg(i);
1253 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1254 Children.push_back(ParseTreePattern(DI));
1255 if (Children.back()->getName().empty())
1256 Children.back()->setName(Dag->getArgName(i));
1257 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1258 Record *R = DefI->getDef();
1259 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1260 // TreePatternNode if its own.
1261 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001262 Dag->setArg(i, new DagInit(DefI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001263 std::vector<std::pair<Init*, std::string> >()));
1264 --i; // Revisit this node...
1265 } else {
1266 TreePatternNode *Node = new TreePatternNode(DefI);
1267 Node->setName(Dag->getArgName(i));
1268 Children.push_back(Node);
1269
1270 // Input argument?
1271 if (R->getName() == "node") {
1272 if (Dag->getArgName(i).empty())
1273 error("'node' argument requires a name to match with operand list");
1274 Args.push_back(Dag->getArgName(i));
1275 }
1276 }
1277 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1278 TreePatternNode *Node = new TreePatternNode(II);
1279 if (!Dag->getArgName(i).empty())
1280 error("Constant int argument should not have a name!");
1281 Children.push_back(Node);
1282 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1283 // Turn this into an IntInit.
1284 Init *II = BI->convertInitializerTo(new IntRecTy());
1285 if (II == 0 || !dynamic_cast<IntInit*>(II))
1286 error("Bits value must be constants!");
1287
1288 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1289 if (!Dag->getArgName(i).empty())
1290 error("Constant int argument should not have a name!");
1291 Children.push_back(Node);
1292 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001293 errs() << '"';
Chris Lattner6cefb772008-01-05 22:25:12 +00001294 Arg->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001295 errs() << "\": ";
Chris Lattner6cefb772008-01-05 22:25:12 +00001296 error("Unknown leaf value for tree pattern!");
1297 }
1298 }
1299
1300 // If the operator is an intrinsic, then this is just syntactic sugar for for
1301 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1302 // convert the intrinsic name to a number.
1303 if (Operator->isSubClassOf("Intrinsic")) {
1304 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1305 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1306
1307 // If this intrinsic returns void, it must have side-effects and thus a
1308 // chain.
Owen Anderson825b72b2009-08-11 20:47:22 +00001309 if (Int.IS.RetVTs[0] == MVT::isVoid) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001310 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1311 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1312 // Has side-effects, requires chain.
1313 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1314 } else {
1315 // Otherwise, no chain.
1316 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1317 }
1318
1319 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1320 Children.insert(Children.begin(), IIDNode);
1321 }
1322
Nate Begeman7cee8172009-03-19 05:21:56 +00001323 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1324 Result->setName(Dag->getName());
1325 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001326}
1327
1328/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001329/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001330/// otherwise. Throw an exception if a type contradiction is found.
1331bool TreePattern::InferAllTypes() {
1332 bool MadeChange = true;
1333 while (MadeChange) {
1334 MadeChange = false;
1335 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1336 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1337 }
1338
1339 bool HasUnresolvedTypes = false;
1340 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1341 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1342 return !HasUnresolvedTypes;
1343}
1344
Daniel Dunbar1a551802009-07-03 00:10:29 +00001345void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001346 OS << getRecord()->getName();
1347 if (!Args.empty()) {
1348 OS << "(" << Args[0];
1349 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1350 OS << ", " << Args[i];
1351 OS << ")";
1352 }
1353 OS << ": ";
1354
1355 if (Trees.size() > 1)
1356 OS << "[\n";
1357 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1358 OS << "\t";
1359 Trees[i]->print(OS);
1360 OS << "\n";
1361 }
1362
1363 if (Trees.size() > 1)
1364 OS << "]\n";
1365}
1366
Daniel Dunbar1a551802009-07-03 00:10:29 +00001367void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001368
1369//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001370// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001371//
1372
1373// FIXME: REMOVE OSTREAM ARGUMENT
Chris Lattnerfe718932008-01-06 01:10:31 +00001374CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001375 Intrinsics = LoadIntrinsics(Records, false);
1376 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001377 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001378 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001379 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001380 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001381 ParseDefaultOperands();
1382 ParseInstructions();
1383 ParsePatterns();
1384
1385 // Generate variants. For example, commutative patterns can match
1386 // multiple ways. Add them to PatternsToMatch as well.
1387 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001388
1389 // Infer instruction flags. For example, we can detect loads,
1390 // stores, and side effects in many cases by examining an
1391 // instruction's pattern.
1392 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001393}
1394
Chris Lattnerfe718932008-01-06 01:10:31 +00001395CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001396 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001397 E = PatternFragments.end(); I != E; ++I)
1398 delete I->second;
1399}
1400
1401
Chris Lattnerfe718932008-01-06 01:10:31 +00001402Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001403 Record *N = Records.getDef(Name);
1404 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001405 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001406 exit(1);
1407 }
1408 return N;
1409}
1410
1411// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001412void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001413 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1414 while (!Nodes.empty()) {
1415 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1416 Nodes.pop_back();
1417 }
1418
Jim Grosbachda4231f2009-03-26 16:17:51 +00001419 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001420 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1421 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1422 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1423}
1424
1425/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1426/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001427void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001428 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1429 while (!Xforms.empty()) {
1430 Record *XFormNode = Xforms.back();
1431 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1432 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001433 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001434
1435 Xforms.pop_back();
1436 }
1437}
1438
Chris Lattnerfe718932008-01-06 01:10:31 +00001439void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001440 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1441 while (!AMs.empty()) {
1442 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1443 AMs.pop_back();
1444 }
1445}
1446
1447
1448/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1449/// file, building up the PatternFragments map. After we've collected them all,
1450/// inline fragments together as necessary, so that there are no references left
1451/// inside a pattern fragment to a pattern fragment.
1452///
Chris Lattnerfe718932008-01-06 01:10:31 +00001453void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001454 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1455
Chris Lattnerdc32f982008-01-05 22:43:57 +00001456 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001457 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1458 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1459 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1460 PatternFragments[Fragments[i]] = P;
1461
Chris Lattnerdc32f982008-01-05 22:43:57 +00001462 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001463 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001464 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001465
Chris Lattnerdc32f982008-01-05 22:43:57 +00001466 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001467 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1468
1469 // Parse the operands list.
1470 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1471 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1472 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001473 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001474 if (!OpsOp ||
1475 (OpsOp->getDef()->getName() != "ops" &&
1476 OpsOp->getDef()->getName() != "outs" &&
1477 OpsOp->getDef()->getName() != "ins"))
1478 P->error("Operands list should start with '(ops ... '!");
1479
1480 // Copy over the arguments.
1481 Args.clear();
1482 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1483 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1484 static_cast<DefInit*>(OpsList->getArg(j))->
1485 getDef()->getName() != "node")
1486 P->error("Operands list should all be 'node' values.");
1487 if (OpsList->getArgName(j).empty())
1488 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001489 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001490 P->error("'" + OpsList->getArgName(j) +
1491 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001492 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001493 Args.push_back(OpsList->getArgName(j));
1494 }
1495
Chris Lattnerdc32f982008-01-05 22:43:57 +00001496 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001497 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001498 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001499
Chris Lattnerdc32f982008-01-05 22:43:57 +00001500 // If there is a code init for this fragment, keep track of the fact that
1501 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001502 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001503 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001504 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001505
1506 // If there is a node transformation corresponding to this, keep track of
1507 // it.
1508 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1509 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1510 P->getOnlyTree()->setTransformFn(Transform);
1511 }
1512
Chris Lattner6cefb772008-01-05 22:25:12 +00001513 // Now that we've parsed all of the tree fragments, do a closure on them so
1514 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001515 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1516 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001517 ThePat->InlinePatternFragments();
1518
1519 // Infer as many types as possible. Don't worry about it if we don't infer
1520 // all of them, some may depend on the inputs of the pattern.
1521 try {
1522 ThePat->InferAllTypes();
1523 } catch (...) {
1524 // If this pattern fragment is not supported by this target (no types can
1525 // satisfy its constraints), just ignore it. If the bogus pattern is
1526 // actually used by instructions, the type consistency error will be
1527 // reported there.
1528 }
1529
1530 // If debugging, print out the pattern fragment result.
1531 DEBUG(ThePat->dump());
1532 }
1533}
1534
Chris Lattnerfe718932008-01-06 01:10:31 +00001535void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001536 std::vector<Record*> DefaultOps[2];
1537 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1538 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1539
1540 // Find some SDNode.
1541 assert(!SDNodes.empty() && "No SDNodes parsed?");
1542 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1543
1544 for (unsigned iter = 0; iter != 2; ++iter) {
1545 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1546 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1547
1548 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1549 // SomeSDnode so that we can parse this.
1550 std::vector<std::pair<Init*, std::string> > Ops;
1551 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1552 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1553 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001554 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001555
1556 // Create a TreePattern to parse this.
1557 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1558 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1559
1560 // Copy the operands over into a DAGDefaultOperand.
1561 DAGDefaultOperand DefaultOpInfo;
1562
1563 TreePatternNode *T = P.getTree(0);
1564 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1565 TreePatternNode *TPN = T->getChild(op);
1566 while (TPN->ApplyTypeConstraints(P, false))
1567 /* Resolve all types */;
1568
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001569 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001570 if (iter == 0)
1571 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1572 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1573 else
1574 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1575 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001576 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001577 DefaultOpInfo.DefaultOps.push_back(TPN);
1578 }
1579
1580 // Insert it into the DefaultOperands map so we can find it later.
1581 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1582 }
1583 }
1584}
1585
1586/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1587/// instruction input. Return true if this is a real use.
1588static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1589 std::map<std::string, TreePatternNode*> &InstInputs,
1590 std::vector<Record*> &InstImpInputs) {
1591 // No name -> not interesting.
1592 if (Pat->getName().empty()) {
1593 if (Pat->isLeaf()) {
1594 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1595 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1596 I->error("Input " + DI->getDef()->getName() + " must be named!");
1597 else if (DI && DI->getDef()->isSubClassOf("Register"))
1598 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001599 }
1600 return false;
1601 }
1602
1603 Record *Rec;
1604 if (Pat->isLeaf()) {
1605 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1606 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1607 Rec = DI->getDef();
1608 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001609 Rec = Pat->getOperator();
1610 }
1611
1612 // SRCVALUE nodes are ignored.
1613 if (Rec->getName() == "srcvalue")
1614 return false;
1615
1616 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1617 if (!Slot) {
1618 Slot = Pat;
1619 } else {
1620 Record *SlotRec;
1621 if (Slot->isLeaf()) {
1622 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1623 } else {
1624 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1625 SlotRec = Slot->getOperator();
1626 }
1627
1628 // Ensure that the inputs agree if we've already seen this input.
1629 if (Rec != SlotRec)
1630 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1631 if (Slot->getExtTypes() != Pat->getExtTypes())
1632 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1633 }
1634 return true;
1635}
1636
1637/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1638/// part of "I", the instruction), computing the set of inputs and outputs of
1639/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001640void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001641FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1642 std::map<std::string, TreePatternNode*> &InstInputs,
1643 std::map<std::string, TreePatternNode*>&InstResults,
1644 std::vector<Record*> &InstImpInputs,
1645 std::vector<Record*> &InstImpResults) {
1646 if (Pat->isLeaf()) {
1647 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1648 if (!isUse && Pat->getTransformFn())
1649 I->error("Cannot specify a transform function for a non-input value!");
1650 return;
1651 } else if (Pat->getOperator()->getName() == "implicit") {
1652 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1653 TreePatternNode *Dest = Pat->getChild(i);
1654 if (!Dest->isLeaf())
1655 I->error("implicitly defined value should be a register!");
1656
1657 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1658 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1659 I->error("implicitly defined value should be a register!");
1660 InstImpResults.push_back(Val->getDef());
1661 }
1662 return;
1663 } else if (Pat->getOperator()->getName() != "set") {
1664 // If this is not a set, verify that the children nodes are not void typed,
1665 // and recurse.
1666 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001667 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00001668 I->error("Cannot have void nodes inside of patterns!");
1669 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1670 InstImpInputs, InstImpResults);
1671 }
1672
1673 // If this is a non-leaf node with no children, treat it basically as if
1674 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00001675 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00001676
1677 if (!isUse && Pat->getTransformFn())
1678 I->error("Cannot specify a transform function for a non-input value!");
1679 return;
1680 }
1681
1682 // Otherwise, this is a set, validate and collect instruction results.
1683 if (Pat->getNumChildren() == 0)
1684 I->error("set requires operands!");
1685
1686 if (Pat->getTransformFn())
1687 I->error("Cannot specify a transform function on a set node!");
1688
1689 // Check the set destinations.
1690 unsigned NumDests = Pat->getNumChildren()-1;
1691 for (unsigned i = 0; i != NumDests; ++i) {
1692 TreePatternNode *Dest = Pat->getChild(i);
1693 if (!Dest->isLeaf())
1694 I->error("set destination should be a register!");
1695
1696 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1697 if (!Val)
1698 I->error("set destination should be a register!");
1699
1700 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00001701 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001702 if (Dest->getName().empty())
1703 I->error("set destination must have a name!");
1704 if (InstResults.count(Dest->getName()))
1705 I->error("cannot set '" + Dest->getName() +"' multiple times");
1706 InstResults[Dest->getName()] = Dest;
1707 } else if (Val->getDef()->isSubClassOf("Register")) {
1708 InstImpResults.push_back(Val->getDef());
1709 } else {
1710 I->error("set destination should be a register!");
1711 }
1712 }
1713
1714 // Verify and collect info from the computation.
1715 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1716 InstInputs, InstResults,
1717 InstImpInputs, InstImpResults);
1718}
1719
Dan Gohmanee4fa192008-04-03 00:02:49 +00001720//===----------------------------------------------------------------------===//
1721// Instruction Analysis
1722//===----------------------------------------------------------------------===//
1723
1724class InstAnalyzer {
1725 const CodeGenDAGPatterns &CDP;
1726 bool &mayStore;
1727 bool &mayLoad;
1728 bool &HasSideEffects;
1729public:
1730 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1731 bool &maystore, bool &mayload, bool &hse)
1732 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1733 }
1734
1735 /// Analyze - Analyze the specified instruction, returning true if the
1736 /// instruction had a pattern.
1737 bool Analyze(Record *InstRecord) {
1738 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1739 if (Pattern == 0) {
1740 HasSideEffects = 1;
1741 return false; // No pattern.
1742 }
1743
1744 // FIXME: Assume only the first tree is the pattern. The others are clobber
1745 // nodes.
1746 AnalyzeNode(Pattern->getTree(0));
1747 return true;
1748 }
1749
1750private:
1751 void AnalyzeNode(const TreePatternNode *N) {
1752 if (N->isLeaf()) {
1753 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1754 Record *LeafRec = DI->getDef();
1755 // Handle ComplexPattern leaves.
1756 if (LeafRec->isSubClassOf("ComplexPattern")) {
1757 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1758 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1759 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1760 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1761 }
1762 }
1763 return;
1764 }
1765
1766 // Analyze children.
1767 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1768 AnalyzeNode(N->getChild(i));
1769
1770 // Ignore set nodes, which are not SDNodes.
1771 if (N->getOperator()->getName() == "set")
1772 return;
1773
1774 // Get information about the SDNode for the operator.
1775 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1776
1777 // Notice properties of the node.
1778 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1779 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1780 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1781
1782 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1783 // If this is an intrinsic, analyze it.
1784 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1785 mayLoad = true;// These may load memory.
1786
1787 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1788 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1789
1790 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1791 // WriteMem intrinsics can have other strange effects.
1792 HasSideEffects = true;
1793 }
1794 }
1795
1796};
1797
1798static void InferFromPattern(const CodeGenInstruction &Inst,
1799 bool &MayStore, bool &MayLoad,
1800 bool &HasSideEffects,
1801 const CodeGenDAGPatterns &CDP) {
1802 MayStore = MayLoad = HasSideEffects = false;
1803
1804 bool HadPattern =
1805 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1806
1807 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1808 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1809 // If we decided that this is a store from the pattern, then the .td file
1810 // entry is redundant.
1811 if (MayStore)
1812 fprintf(stderr,
1813 "Warning: mayStore flag explicitly set on instruction '%s'"
1814 " but flag already inferred from pattern.\n",
1815 Inst.TheDef->getName().c_str());
1816 MayStore = true;
1817 }
1818
1819 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1820 // If we decided that this is a load from the pattern, then the .td file
1821 // entry is redundant.
1822 if (MayLoad)
1823 fprintf(stderr,
1824 "Warning: mayLoad flag explicitly set on instruction '%s'"
1825 " but flag already inferred from pattern.\n",
1826 Inst.TheDef->getName().c_str());
1827 MayLoad = true;
1828 }
1829
1830 if (Inst.neverHasSideEffects) {
1831 if (HadPattern)
1832 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1833 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1834 HasSideEffects = false;
1835 }
1836
1837 if (Inst.hasSideEffects) {
1838 if (HasSideEffects)
1839 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1840 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1841 HasSideEffects = true;
1842 }
1843}
1844
Chris Lattner6cefb772008-01-05 22:25:12 +00001845/// ParseInstructions - Parse all of the instructions, inlining and resolving
1846/// any fragments involved. This populates the Instructions list with fully
1847/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001848void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001849 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1850
1851 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1852 ListInit *LI = 0;
1853
1854 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1855 LI = Instrs[i]->getValueAsListInit("Pattern");
1856
1857 // If there is no pattern, only collect minimal information about the
1858 // instruction for its operand list. We have to assume that there is one
1859 // result, as we have no detailed info.
1860 if (!LI || LI->getSize() == 0) {
1861 std::vector<Record*> Results;
1862 std::vector<Record*> Operands;
1863
1864 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1865
1866 if (InstInfo.OperandList.size() != 0) {
1867 if (InstInfo.NumDefs == 0) {
1868 // These produce no results
1869 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1870 Operands.push_back(InstInfo.OperandList[j].Rec);
1871 } else {
1872 // Assume the first operand is the result.
1873 Results.push_back(InstInfo.OperandList[0].Rec);
1874
1875 // The rest are inputs.
1876 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1877 Operands.push_back(InstInfo.OperandList[j].Rec);
1878 }
1879 }
1880
1881 // Create and insert the instruction.
1882 std::vector<Record*> ImpResults;
1883 std::vector<Record*> ImpOperands;
1884 Instructions.insert(std::make_pair(Instrs[i],
1885 DAGInstruction(0, Results, Operands, ImpResults,
1886 ImpOperands)));
1887 continue; // no pattern.
1888 }
1889
1890 // Parse the instruction.
1891 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1892 // Inline pattern fragments into it.
1893 I->InlinePatternFragments();
1894
1895 // Infer as many types as possible. If we cannot infer all of them, we can
1896 // never do anything with this instruction pattern: report it to the user.
1897 if (!I->InferAllTypes())
1898 I->error("Could not infer all types in pattern!");
1899
1900 // InstInputs - Keep track of all of the inputs of the instruction, along
1901 // with the record they are declared as.
1902 std::map<std::string, TreePatternNode*> InstInputs;
1903
1904 // InstResults - Keep track of all the virtual registers that are 'set'
1905 // in the instruction, including what reg class they are.
1906 std::map<std::string, TreePatternNode*> InstResults;
1907
1908 std::vector<Record*> InstImpInputs;
1909 std::vector<Record*> InstImpResults;
1910
1911 // Verify that the top-level forms in the instruction are of void type, and
1912 // fill in the InstResults map.
1913 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1914 TreePatternNode *Pat = I->getTree(j);
Owen Anderson825b72b2009-08-11 20:47:22 +00001915 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00001916 I->error("Top-level forms in instruction pattern should have"
1917 " void types");
1918
1919 // Find inputs and outputs, and verify the structure of the uses/defs.
1920 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1921 InstImpInputs, InstImpResults);
1922 }
1923
1924 // Now that we have inputs and outputs of the pattern, inspect the operands
1925 // list for the instruction. This determines the order that operands are
1926 // added to the machine instruction the node corresponds to.
1927 unsigned NumResults = InstResults.size();
1928
1929 // Parse the operands list from the (ops) list, validating it.
1930 assert(I->getArgList().empty() && "Args list should still be empty here!");
1931 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1932
1933 // Check that all of the results occur first in the list.
1934 std::vector<Record*> Results;
1935 TreePatternNode *Res0Node = NULL;
1936 for (unsigned i = 0; i != NumResults; ++i) {
1937 if (i == CGI.OperandList.size())
1938 I->error("'" + InstResults.begin()->first +
1939 "' set but does not appear in operand list!");
1940 const std::string &OpName = CGI.OperandList[i].Name;
1941
1942 // Check that it exists in InstResults.
1943 TreePatternNode *RNode = InstResults[OpName];
1944 if (RNode == 0)
1945 I->error("Operand $" + OpName + " does not exist in operand list!");
1946
1947 if (i == 0)
1948 Res0Node = RNode;
1949 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1950 if (R == 0)
1951 I->error("Operand $" + OpName + " should be a set destination: all "
1952 "outputs must occur before inputs in operand list!");
1953
1954 if (CGI.OperandList[i].Rec != R)
1955 I->error("Operand $" + OpName + " class mismatch!");
1956
1957 // Remember the return type.
1958 Results.push_back(CGI.OperandList[i].Rec);
1959
1960 // Okay, this one checks out.
1961 InstResults.erase(OpName);
1962 }
1963
1964 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1965 // the copy while we're checking the inputs.
1966 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1967
1968 std::vector<TreePatternNode*> ResultNodeOperands;
1969 std::vector<Record*> Operands;
1970 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1971 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1972 const std::string &OpName = Op.Name;
1973 if (OpName.empty())
1974 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1975
1976 if (!InstInputsCheck.count(OpName)) {
1977 // If this is an predicate operand or optional def operand with an
1978 // DefaultOps set filled in, we can ignore this. When we codegen it,
1979 // we will do so as always executed.
1980 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1981 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1982 // Does it have a non-empty DefaultOps field? If so, ignore this
1983 // operand.
1984 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1985 continue;
1986 }
1987 I->error("Operand $" + OpName +
1988 " does not appear in the instruction pattern");
1989 }
1990 TreePatternNode *InVal = InstInputsCheck[OpName];
1991 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1992
1993 if (InVal->isLeaf() &&
1994 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1995 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1996 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1997 I->error("Operand $" + OpName + "'s register class disagrees"
1998 " between the operand and pattern");
1999 }
2000 Operands.push_back(Op.Rec);
2001
2002 // Construct the result for the dest-pattern operand list.
2003 TreePatternNode *OpNode = InVal->clone();
2004
2005 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002006 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00002007
2008 // Promote the xform function to be an explicit node if set.
2009 if (Record *Xform = OpNode->getTransformFn()) {
2010 OpNode->setTransformFn(0);
2011 std::vector<TreePatternNode*> Children;
2012 Children.push_back(OpNode);
2013 OpNode = new TreePatternNode(Xform, Children);
2014 }
2015
2016 ResultNodeOperands.push_back(OpNode);
2017 }
2018
2019 if (!InstInputsCheck.empty())
2020 I->error("Input operand $" + InstInputsCheck.begin()->first +
2021 " occurs in pattern but not in operands list!");
2022
2023 TreePatternNode *ResultPattern =
2024 new TreePatternNode(I->getRecord(), ResultNodeOperands);
2025 // Copy fully inferred output node type to instruction result pattern.
2026 if (NumResults > 0)
2027 ResultPattern->setTypes(Res0Node->getExtTypes());
2028
2029 // Create and insert the instruction.
2030 // FIXME: InstImpResults and InstImpInputs should not be part of
2031 // DAGInstruction.
2032 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2033 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2034
2035 // Use a temporary tree pattern to infer all types and make sure that the
2036 // constructed result is correct. This depends on the instruction already
2037 // being inserted into the Instructions map.
2038 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2039 Temp.InferAllTypes();
2040
2041 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2042 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2043
2044 DEBUG(I->dump());
2045 }
2046
2047 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002048 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2049 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002050 E = Instructions.end(); II != E; ++II) {
2051 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002052 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002053 if (I == 0) continue; // No pattern.
2054
2055 // FIXME: Assume only the first tree is the pattern. The others are clobber
2056 // nodes.
2057 TreePatternNode *Pattern = I->getTree(0);
2058 TreePatternNode *SrcPattern;
2059 if (Pattern->getOperator()->getName() == "set") {
2060 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2061 } else{
2062 // Not a set (store or something?)
2063 SrcPattern = Pattern;
2064 }
2065
2066 std::string Reason;
2067 if (!SrcPattern->canPatternMatch(Reason, *this))
2068 I->error("Instruction can never match: " + Reason);
2069
2070 Record *Instr = II->first;
2071 TreePatternNode *DstPattern = TheInst.getResultPattern();
2072 PatternsToMatch.
2073 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
2074 SrcPattern, DstPattern, TheInst.getImpResults(),
2075 Instr->getValueAsInt("AddedComplexity")));
2076 }
2077}
2078
Dan Gohmanee4fa192008-04-03 00:02:49 +00002079
2080void CodeGenDAGPatterns::InferInstructionFlags() {
2081 std::map<std::string, CodeGenInstruction> &InstrDescs =
2082 Target.getInstructions();
2083 for (std::map<std::string, CodeGenInstruction>::iterator
2084 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2085 CodeGenInstruction &InstInfo = II->second;
2086 // Determine properties of the instruction from its pattern.
2087 bool MayStore, MayLoad, HasSideEffects;
2088 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2089 InstInfo.mayStore = MayStore;
2090 InstInfo.mayLoad = MayLoad;
2091 InstInfo.hasSideEffects = HasSideEffects;
2092 }
2093}
2094
Chris Lattnerfe718932008-01-06 01:10:31 +00002095void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002096 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2097
2098 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2099 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2100 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2101 Record *Operator = OpDef->getDef();
2102 TreePattern *Pattern;
2103 if (Operator->getName() != "parallel")
2104 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2105 else {
2106 std::vector<Init*> Values;
David Greenee1b46912009-06-08 20:23:18 +00002107 RecTy *ListTy = 0;
2108 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002109 Values.push_back(Tree->getArg(j));
David Greenee1b46912009-06-08 20:23:18 +00002110 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2111 if (TArg == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002112 errs() << "In dag: " << Tree->getAsString();
2113 errs() << " -- Untyped argument in pattern\n";
David Greenee1b46912009-06-08 20:23:18 +00002114 assert(0 && "Untyped argument in pattern");
2115 }
2116 if (ListTy != 0) {
2117 ListTy = resolveTypes(ListTy, TArg->getType());
2118 if (ListTy == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002119 errs() << "In dag: " << Tree->getAsString();
2120 errs() << " -- Incompatible types in pattern arguments\n";
David Greenee1b46912009-06-08 20:23:18 +00002121 assert(0 && "Incompatible types in pattern arguments");
2122 }
2123 }
2124 else {
Bill Wendlingee1f6b02009-06-09 18:49:42 +00002125 ListTy = TArg->getType();
David Greenee1b46912009-06-08 20:23:18 +00002126 }
2127 }
2128 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
Chris Lattner6cefb772008-01-05 22:25:12 +00002129 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2130 }
2131
2132 // Inline pattern fragments into it.
2133 Pattern->InlinePatternFragments();
2134
2135 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2136 if (LI->getSize() == 0) continue; // no pattern.
2137
2138 // Parse the instruction.
2139 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2140
2141 // Inline pattern fragments into it.
2142 Result->InlinePatternFragments();
2143
2144 if (Result->getNumTrees() != 1)
2145 Result->error("Cannot handle instructions producing instructions "
2146 "with temporaries yet!");
2147
2148 bool IterateInference;
2149 bool InferredAllPatternTypes, InferredAllResultTypes;
2150 do {
2151 // Infer as many types as possible. If we cannot infer all of them, we
2152 // can never do anything with this pattern: report it to the user.
2153 InferredAllPatternTypes = Pattern->InferAllTypes();
2154
2155 // Infer as many types as possible. If we cannot infer all of them, we
2156 // can never do anything with this pattern: report it to the user.
2157 InferredAllResultTypes = Result->InferAllTypes();
2158
2159 // Apply the type of the result to the source pattern. This helps us
2160 // resolve cases where the input type is known to be a pointer type (which
2161 // is considered resolved), but the result knows it needs to be 32- or
2162 // 64-bits. Infer the other way for good measure.
2163 IterateInference = Pattern->getTree(0)->
2164 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2165 IterateInference |= Result->getTree(0)->
2166 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2167 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002168
Chris Lattner6cefb772008-01-05 22:25:12 +00002169 // Verify that we inferred enough types that we can do something with the
2170 // pattern and result. If these fire the user has to add type casts.
2171 if (!InferredAllPatternTypes)
2172 Pattern->error("Could not infer all types in pattern!");
2173 if (!InferredAllResultTypes)
2174 Result->error("Could not infer all types in pattern result!");
2175
2176 // Validate that the input pattern is correct.
2177 std::map<std::string, TreePatternNode*> InstInputs;
2178 std::map<std::string, TreePatternNode*> InstResults;
2179 std::vector<Record*> InstImpInputs;
2180 std::vector<Record*> InstImpResults;
2181 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2182 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2183 InstInputs, InstResults,
2184 InstImpInputs, InstImpResults);
2185
2186 // Promote the xform function to be an explicit node if set.
2187 TreePatternNode *DstPattern = Result->getOnlyTree();
2188 std::vector<TreePatternNode*> ResultNodeOperands;
2189 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2190 TreePatternNode *OpNode = DstPattern->getChild(ii);
2191 if (Record *Xform = OpNode->getTransformFn()) {
2192 OpNode->setTransformFn(0);
2193 std::vector<TreePatternNode*> Children;
2194 Children.push_back(OpNode);
2195 OpNode = new TreePatternNode(Xform, Children);
2196 }
2197 ResultNodeOperands.push_back(OpNode);
2198 }
2199 DstPattern = Result->getOnlyTree();
2200 if (!DstPattern->isLeaf())
2201 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2202 ResultNodeOperands);
2203 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2204 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2205 Temp.InferAllTypes();
2206
2207 std::string Reason;
2208 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2209 Pattern->error("Pattern can never match: " + Reason);
2210
2211 PatternsToMatch.
2212 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2213 Pattern->getTree(0),
2214 Temp.getOnlyTree(), InstImpResults,
2215 Patterns[i]->getValueAsInt("AddedComplexity")));
2216 }
2217}
2218
2219/// CombineChildVariants - Given a bunch of permutations of each child of the
2220/// 'operator' node, put them together in all possible ways.
2221static void CombineChildVariants(TreePatternNode *Orig,
2222 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2223 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002224 CodeGenDAGPatterns &CDP,
2225 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002226 // Make sure that each operand has at least one variant to choose from.
2227 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2228 if (ChildVariants[i].empty())
2229 return;
2230
2231 // The end result is an all-pairs construction of the resultant pattern.
2232 std::vector<unsigned> Idxs;
2233 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002234 bool NotDone;
2235 do {
2236#ifndef NDEBUG
2237 if (DebugFlag && !Idxs.empty()) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002238 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Scott Michel327d0652008-03-05 17:49:05 +00002239 for (unsigned i = 0; i < Idxs.size(); ++i) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002240 errs() << Idxs[i] << " ";
Scott Michel327d0652008-03-05 17:49:05 +00002241 }
Daniel Dunbar1a551802009-07-03 00:10:29 +00002242 errs() << "]\n";
Scott Michel327d0652008-03-05 17:49:05 +00002243 }
2244#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002245 // Create the variant and add it to the output list.
2246 std::vector<TreePatternNode*> NewChildren;
2247 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2248 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2249 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2250
2251 // Copy over properties.
2252 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002253 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002254 R->setTransformFn(Orig->getTransformFn());
2255 R->setTypes(Orig->getExtTypes());
2256
Scott Michel327d0652008-03-05 17:49:05 +00002257 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002258 std::string ErrString;
2259 if (!R->canPatternMatch(ErrString, CDP)) {
2260 delete R;
2261 } else {
2262 bool AlreadyExists = false;
2263
2264 // Scan to see if this pattern has already been emitted. We can get
2265 // duplication due to things like commuting:
2266 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2267 // which are the same pattern. Ignore the dups.
2268 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002269 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002270 AlreadyExists = true;
2271 break;
2272 }
2273
2274 if (AlreadyExists)
2275 delete R;
2276 else
2277 OutVariants.push_back(R);
2278 }
2279
Scott Michel327d0652008-03-05 17:49:05 +00002280 // Increment indices to the next permutation by incrementing the
2281 // indicies from last index backward, e.g., generate the sequence
2282 // [0, 0], [0, 1], [1, 0], [1, 1].
2283 int IdxsIdx;
2284 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2285 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2286 Idxs[IdxsIdx] = 0;
2287 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002288 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002289 }
Scott Michel327d0652008-03-05 17:49:05 +00002290 NotDone = (IdxsIdx >= 0);
2291 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002292}
2293
2294/// CombineChildVariants - A helper function for binary operators.
2295///
2296static void CombineChildVariants(TreePatternNode *Orig,
2297 const std::vector<TreePatternNode*> &LHS,
2298 const std::vector<TreePatternNode*> &RHS,
2299 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002300 CodeGenDAGPatterns &CDP,
2301 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002302 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2303 ChildVariants.push_back(LHS);
2304 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002305 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002306}
2307
2308
2309static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2310 std::vector<TreePatternNode *> &Children) {
2311 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2312 Record *Operator = N->getOperator();
2313
2314 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002315 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002316 N->getTransformFn()) {
2317 Children.push_back(N);
2318 return;
2319 }
2320
2321 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2322 Children.push_back(N->getChild(0));
2323 else
2324 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2325
2326 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2327 Children.push_back(N->getChild(1));
2328 else
2329 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2330}
2331
2332/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2333/// the (potentially recursive) pattern by using algebraic laws.
2334///
2335static void GenerateVariantsOf(TreePatternNode *N,
2336 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002337 CodeGenDAGPatterns &CDP,
2338 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002339 // We cannot permute leaves.
2340 if (N->isLeaf()) {
2341 OutVariants.push_back(N);
2342 return;
2343 }
2344
2345 // Look up interesting info about the node.
2346 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2347
Jim Grosbachda4231f2009-03-26 16:17:51 +00002348 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002349 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002350 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002351 std::vector<TreePatternNode*> MaximalChildren;
2352 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2353
2354 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2355 // permutations.
2356 if (MaximalChildren.size() == 3) {
2357 // Find the variants of all of our maximal children.
2358 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002359 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2360 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2361 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002362
2363 // There are only two ways we can permute the tree:
2364 // (A op B) op C and A op (B op C)
2365 // Within these forms, we can also permute A/B/C.
2366
2367 // Generate legal pair permutations of A/B/C.
2368 std::vector<TreePatternNode*> ABVariants;
2369 std::vector<TreePatternNode*> BAVariants;
2370 std::vector<TreePatternNode*> ACVariants;
2371 std::vector<TreePatternNode*> CAVariants;
2372 std::vector<TreePatternNode*> BCVariants;
2373 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002374 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2375 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2376 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2377 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2378 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2379 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002380
2381 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002382 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2383 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2384 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2385 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2386 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2387 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002388
2389 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002390 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2391 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2392 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2393 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2394 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2395 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002396 return;
2397 }
2398 }
2399
2400 // Compute permutations of all children.
2401 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2402 ChildVariants.resize(N->getNumChildren());
2403 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002404 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002405
2406 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002407 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002408
2409 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002410 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2411 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2412 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2413 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002414 // Don't count children which are actually register references.
2415 unsigned NC = 0;
2416 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2417 TreePatternNode *Child = N->getChild(i);
2418 if (Child->isLeaf())
2419 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2420 Record *RR = DI->getDef();
2421 if (RR->isSubClassOf("Register"))
2422 continue;
2423 }
2424 NC++;
2425 }
2426 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002427 if (isCommIntrinsic) {
2428 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2429 // operands are the commutative operands, and there might be more operands
2430 // after those.
2431 assert(NC >= 3 &&
2432 "Commutative intrinsic should have at least 3 childrean!");
2433 std::vector<std::vector<TreePatternNode*> > Variants;
2434 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2435 Variants.push_back(ChildVariants[2]);
2436 Variants.push_back(ChildVariants[1]);
2437 for (unsigned i = 3; i != NC; ++i)
2438 Variants.push_back(ChildVariants[i]);
2439 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2440 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002441 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002442 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002443 }
2444}
2445
2446
2447// GenerateVariants - Generate variants. For example, commutative patterns can
2448// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002449void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00002450 DEBUG(errs() << "Generating instruction variants.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002451
2452 // Loop over all of the patterns we've collected, checking to see if we can
2453 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002454 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002455 // the .td file having to contain tons of variants of instructions.
2456 //
2457 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2458 // intentionally do not reconsider these. Any variants of added patterns have
2459 // already been added.
2460 //
2461 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002462 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002463 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002464 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00002465 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00002466 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00002467 DEBUG(errs() << "\n");
Scott Michel327d0652008-03-05 17:49:05 +00002468 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002469
2470 assert(!Variants.empty() && "Must create at least original variant!");
2471 Variants.erase(Variants.begin()); // Remove the original pattern.
2472
2473 if (Variants.empty()) // No variants for this pattern.
2474 continue;
2475
Chris Lattner569f1212009-08-23 04:44:11 +00002476 DEBUG(errs() << "FOUND VARIANTS OF: ";
2477 PatternsToMatch[i].getSrcPattern()->dump();
2478 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002479
2480 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2481 TreePatternNode *Variant = Variants[v];
2482
Chris Lattner569f1212009-08-23 04:44:11 +00002483 DEBUG(errs() << " VAR#" << v << ": ";
2484 Variant->dump();
2485 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002486
2487 // Scan to see if an instruction or explicit pattern already matches this.
2488 bool AlreadyExists = false;
2489 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00002490 // Skip if the top level predicates do not match.
2491 if (PatternsToMatch[i].getPredicates() !=
2492 PatternsToMatch[p].getPredicates())
2493 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00002494 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002495 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00002496 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002497 AlreadyExists = true;
2498 break;
2499 }
2500 }
2501 // If we already have it, ignore the variant.
2502 if (AlreadyExists) continue;
2503
2504 // Otherwise, add it to the list of patterns we have.
2505 PatternsToMatch.
2506 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2507 Variant, PatternsToMatch[i].getDstPattern(),
2508 PatternsToMatch[i].getDstRegs(),
2509 PatternsToMatch[i].getAddedComplexity()));
2510 }
2511
Chris Lattner569f1212009-08-23 04:44:11 +00002512 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002513 }
2514}
2515