blob: e987c2bc82e188d352027f01fcfdfaaa937fd455 [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 "llvm/Support/Streams.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000020#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000021#include <algorithm>
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>
Duncan Sands83ec4b62008-06-06 12:08:01 +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)
Duncan Sands83ec4b62008-06-06 12:08:01 +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>
Duncan Sands83ec4b62008-06-06 12:08:01 +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
Duncan Sands83ec4b62008-06-06 12:08:01 +000057static inline bool isInteger(MVT::SimpleValueType VT) {
58 return MVT(VT).isInteger();
59}
60
61static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
62 return MVT(VT).isFloatingPoint();
63}
64
65static inline bool isVector(MVT::SimpleValueType VT) {
66 return MVT(VT).isVector();
67}
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
78/// isExtIntegerVT - Return true if the specified extended value type vector
79/// contains isInt or an integer value type.
80namespace llvm {
Duncan Sands83ec4b62008-06-06 12:08:01 +000081namespace EMVT {
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!");
84 return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty());
85}
86
87/// isExtFloatingPointVT - Return true if the specified extended value type
88/// vector contains isFP or a FP value type.
89bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
90 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
91 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
92}
Duncan Sands83ec4b62008-06-06 12:08:01 +000093} // end namespace EMVT.
Chris Lattner6cefb772008-01-05 22:25:12 +000094} // end namespace llvm.
95
Scott Michel327d0652008-03-05 17:49:05 +000096
97/// Dependent variable map for CodeGenDAGPattern variant generation
98typedef std::map<std::string, int> DepVarMap;
99
100/// Const iterator shorthand for DepVarMap
101typedef DepVarMap::const_iterator DepVarMap_citer;
102
103namespace {
104void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
105 if (N->isLeaf()) {
106 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
107 DepMap[N->getName()]++;
108 }
109 } else {
110 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
111 FindDepVarsOf(N->getChild(i), DepMap);
112 }
113}
114
115//! Find dependent variables within child patterns
116/*!
117 */
118void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
119 DepVarMap depcounts;
120 FindDepVarsOf(N, depcounts);
121 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
122 if (i->second > 1) { // std::pair<std::string, int>
123 DepVars.insert(i->first);
124 }
125 }
126}
127
128//! Dump the dependent variable set:
129void DumpDepVars(MultipleUseVarSet &DepVars) {
130 if (DepVars.empty()) {
131 DOUT << "<empty set>";
132 } else {
133 DOUT << "[ ";
134 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
135 i != e; ++i) {
136 DOUT << (*i) << " ";
137 }
138 DOUT << "]";
139 }
140}
141}
142
Chris Lattner6cefb772008-01-05 22:25:12 +0000143//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000144// PatternToMatch implementation
145//
146
147/// getPredicateCheck - Return a single string containing all of this
148/// pattern's predicates concatenated with "&&" operators.
149///
150std::string PatternToMatch::getPredicateCheck() const {
151 std::string PredicateCheck;
152 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
153 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
154 Record *Def = Pred->getDef();
155 if (!Def->isSubClassOf("Predicate")) {
156#ifndef NDEBUG
157 Def->dump();
158#endif
159 assert(0 && "Unknown predicate type!");
160 }
161 if (!PredicateCheck.empty())
162 PredicateCheck += " && ";
163 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
164 }
165 }
166
167 return PredicateCheck;
168}
169
170//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000171// SDTypeConstraint implementation
172//
173
174SDTypeConstraint::SDTypeConstraint(Record *R) {
175 OperandNo = R->getValueAsInt("OperandNum");
176
177 if (R->isSubClassOf("SDTCisVT")) {
178 ConstraintType = SDTCisVT;
179 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
180 } else if (R->isSubClassOf("SDTCisPtrTy")) {
181 ConstraintType = SDTCisPtrTy;
182 } else if (R->isSubClassOf("SDTCisInt")) {
183 ConstraintType = SDTCisInt;
184 } else if (R->isSubClassOf("SDTCisFP")) {
185 ConstraintType = SDTCisFP;
186 } else if (R->isSubClassOf("SDTCisSameAs")) {
187 ConstraintType = SDTCisSameAs;
188 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
189 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
190 ConstraintType = SDTCisVTSmallerThanOp;
191 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
192 R->getValueAsInt("OtherOperandNum");
193 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
194 ConstraintType = SDTCisOpSmallerThanOp;
195 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
196 R->getValueAsInt("BigOperandNum");
197 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
198 ConstraintType = SDTCisIntVectorOfSameSize;
199 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
200 R->getValueAsInt("OtherOpNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000201 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
202 ConstraintType = SDTCisEltOfVec;
203 x.SDTCisEltOfVec_Info.OtherOperandNum =
204 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000205 } else {
206 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
207 exit(1);
208 }
209}
210
211/// getOperandNum - Return the node corresponding to operand #OpNo in tree
212/// N, which has NumResults results.
213TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
214 TreePatternNode *N,
215 unsigned NumResults) const {
216 assert(NumResults <= 1 &&
217 "We only work with nodes with zero or one result so far!");
218
219 if (OpNo >= (NumResults + N->getNumChildren())) {
220 cerr << "Invalid operand number " << OpNo << " ";
221 N->dump();
222 cerr << '\n';
223 exit(1);
224 }
225
226 if (OpNo < NumResults)
227 return N; // FIXME: need value #
228 else
229 return N->getChild(OpNo-NumResults);
230}
231
232/// ApplyTypeConstraint - Given a node in a pattern, apply this type
233/// constraint to the nodes operands. This returns true if it makes a
234/// change, false otherwise. If a type contradiction is found, throw an
235/// exception.
236bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
237 const SDNodeInfo &NodeInfo,
238 TreePattern &TP) const {
239 unsigned NumResults = NodeInfo.getNumResults();
240 assert(NumResults <= 1 &&
241 "We only work with nodes with zero or one result so far!");
242
243 // Check that the number of operands is sane. Negative operands -> varargs.
244 if (NodeInfo.getNumOperands() >= 0) {
245 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
246 TP.error(N->getOperator()->getName() + " node requires exactly " +
247 itostr(NodeInfo.getNumOperands()) + " operands!");
248 }
249
250 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
251
252 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
253
254 switch (ConstraintType) {
255 default: assert(0 && "Unknown constraint type!");
256 case SDTCisVT:
257 // Operand must be a particular type.
258 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
259 case SDTCisPtrTy: {
260 // Operand must be same as target pointer type.
261 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
262 }
263 case SDTCisInt: {
264 // If there is only one integer type supported, this must be it.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000265 std::vector<MVT::SimpleValueType> IntVTs =
266 FilterVTs(CGT.getLegalValueTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000267
268 // If we found exactly one supported integer type, apply it.
269 if (IntVTs.size() == 1)
270 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000271 return NodeToApply->UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000272 }
273 case SDTCisFP: {
274 // If there is only one FP type supported, this must be it.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000275 std::vector<MVT::SimpleValueType> FPVTs =
276 FilterVTs(CGT.getLegalValueTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000277
278 // If we found exactly one supported FP type, apply it.
279 if (FPVTs.size() == 1)
280 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000281 return NodeToApply->UpdateNodeType(EMVT::isFP, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000282 }
283 case SDTCisSameAs: {
284 TreePatternNode *OtherNode =
285 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
286 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
287 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
288 }
289 case SDTCisVTSmallerThanOp: {
290 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
291 // have an integer type that is smaller than the VT.
292 if (!NodeToApply->isLeaf() ||
293 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
294 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
295 ->isSubClassOf("ValueType"))
296 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000297 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000298 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Duncan Sands83ec4b62008-06-06 12:08:01 +0000299 if (!isInteger(VT))
Chris Lattner6cefb772008-01-05 22:25:12 +0000300 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
301
302 TreePatternNode *OtherNode =
303 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
304
305 // It must be integer.
306 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000307 MadeChange |= OtherNode->UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000308
309 // This code only handles nodes that have one type set. Assert here so
310 // that we can change this if we ever need to deal with multiple value
311 // types at this point.
312 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
313 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
314 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
315 return false;
316 }
317 case SDTCisOpSmallerThanOp: {
318 TreePatternNode *BigOperand =
319 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
320
321 // Both operands must be integer or FP, but we don't care which.
322 bool MadeChange = false;
323
324 // This code does not currently handle nodes which have multiple types,
325 // where some types are integer, and some are fp. Assert that this is not
326 // the case.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000327 assert(!(EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
328 EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
329 !(EMVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
330 EMVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000331 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000332 if (EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
333 MadeChange |= BigOperand->UpdateNodeType(EMVT::isInt, TP);
334 else if (EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
335 MadeChange |= BigOperand->UpdateNodeType(EMVT::isFP, TP);
336 if (EMVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
337 MadeChange |= NodeToApply->UpdateNodeType(EMVT::isInt, TP);
338 else if (EMVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
339 MadeChange |= NodeToApply->UpdateNodeType(EMVT::isFP, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000340
Duncan Sands83ec4b62008-06-06 12:08:01 +0000341 std::vector<MVT::SimpleValueType> VTs = CGT.getLegalValueTypes();
342
343 if (EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
344 VTs = FilterVTs(VTs, isInteger);
345 } else if (EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
346 VTs = FilterVTs(VTs, isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000347 } else {
348 VTs.clear();
349 }
350
351 switch (VTs.size()) {
352 default: // Too many VT's to pick from.
353 case 0: break; // No info yet.
354 case 1:
355 // Only one VT of this flavor. Cannot ever satisify the constraints.
356 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
357 case 2:
358 // If we have exactly two possible types, the little operand must be the
359 // small one, the big operand should be the big one. Common with
360 // float/double for example.
361 assert(VTs[0] < VTs[1] && "Should be sorted!");
362 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
363 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
364 break;
365 }
366 return MadeChange;
367 }
368 case SDTCisIntVectorOfSameSize: {
369 TreePatternNode *OtherOperand =
370 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
371 N, NumResults);
372 if (OtherOperand->hasTypeSet()) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000373 if (!isVector(OtherOperand->getTypeNum(0)))
Chris Lattner6cefb772008-01-05 22:25:12 +0000374 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000375 MVT IVT = OtherOperand->getTypeNum(0);
376 unsigned NumElements = IVT.getVectorNumElements();
377 IVT = MVT::getIntVectorWithNumElements(NumElements);
378 return NodeToApply->UpdateNodeType(IVT.getSimpleVT(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000379 }
380 return false;
381 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000382 case SDTCisEltOfVec: {
383 TreePatternNode *OtherOperand =
384 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
385 N, NumResults);
386 if (OtherOperand->hasTypeSet()) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000387 if (!isVector(OtherOperand->getTypeNum(0)))
Nate Begemanb5af3342008-02-09 01:37:05 +0000388 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000389 MVT IVT = OtherOperand->getTypeNum(0);
390 IVT = IVT.getVectorElementType();
391 return NodeToApply->UpdateNodeType(IVT.getSimpleVT(), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000392 }
393 return false;
394 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000395 }
396 return false;
397}
398
399//===----------------------------------------------------------------------===//
400// SDNodeInfo implementation
401//
402SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
403 EnumName = R->getValueAsString("Opcode");
404 SDClassName = R->getValueAsString("SDClass");
405 Record *TypeProfile = R->getValueAsDef("TypeProfile");
406 NumResults = TypeProfile->getValueAsInt("NumResults");
407 NumOperands = TypeProfile->getValueAsInt("NumOperands");
408
409 // Parse the properties.
410 Properties = 0;
411 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
412 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
413 if (PropList[i]->getName() == "SDNPCommutative") {
414 Properties |= 1 << SDNPCommutative;
415 } else if (PropList[i]->getName() == "SDNPAssociative") {
416 Properties |= 1 << SDNPAssociative;
417 } else if (PropList[i]->getName() == "SDNPHasChain") {
418 Properties |= 1 << SDNPHasChain;
419 } else if (PropList[i]->getName() == "SDNPOutFlag") {
420 Properties |= 1 << SDNPOutFlag;
421 } else if (PropList[i]->getName() == "SDNPInFlag") {
422 Properties |= 1 << SDNPInFlag;
423 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
424 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000425 } else if (PropList[i]->getName() == "SDNPMayStore") {
426 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000427 } else if (PropList[i]->getName() == "SDNPMayLoad") {
428 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000429 } else if (PropList[i]->getName() == "SDNPSideEffect") {
430 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000431 } else if (PropList[i]->getName() == "SDNPMemOperand") {
432 Properties |= 1 << SDNPMemOperand;
Chris Lattner6cefb772008-01-05 22:25:12 +0000433 } else {
434 cerr << "Unknown SD Node property '" << PropList[i]->getName()
435 << "' on node '" << R->getName() << "'!\n";
436 exit(1);
437 }
438 }
439
440
441 // Parse the type constraints.
442 std::vector<Record*> ConstraintList =
443 TypeProfile->getValueAsListOfDefs("Constraints");
444 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
445}
446
447//===----------------------------------------------------------------------===//
448// TreePatternNode implementation
449//
450
451TreePatternNode::~TreePatternNode() {
452#if 0 // FIXME: implement refcounted tree nodes!
453 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
454 delete getChild(i);
455#endif
456}
457
458/// UpdateNodeType - Set the node type of N to VT if VT contains
459/// information. If N already contains a conflicting type, then throw an
460/// exception. This returns true if any information was updated.
461///
462bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
463 TreePattern &TP) {
464 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
465
Duncan Sands83ec4b62008-06-06 12:08:01 +0000466 if (ExtVTs[0] == EMVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
Chris Lattner6cefb772008-01-05 22:25:12 +0000467 return false;
468 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
469 setTypes(ExtVTs);
470 return true;
471 }
472
Mon P Wange3b3a722008-07-30 04:36:53 +0000473 if (getExtTypeNum(0) == MVT::iPTR || getExtTypeNum(0) == MVT::iPTRAny) {
474 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny || ExtVTs[0] == EMVT::isInt)
Chris Lattner6cefb772008-01-05 22:25:12 +0000475 return false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000476 if (EMVT::isExtIntegerInVTs(ExtVTs)) {
477 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000478 if (FVTs.size()) {
479 setTypes(ExtVTs);
480 return true;
481 }
482 }
483 }
484
Duncan Sands83ec4b62008-06-06 12:08:01 +0000485 if (ExtVTs[0] == EMVT::isInt && EMVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000486 assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000487 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000488 if (getExtTypes() == FVTs)
489 return false;
490 setTypes(FVTs);
491 return true;
492 }
Mon P Wange3b3a722008-07-30 04:36:53 +0000493 if ((ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny) &&
494 EMVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000495 //assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000496 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000497 if (getExtTypes() == FVTs)
498 return false;
499 if (FVTs.size()) {
500 setTypes(FVTs);
501 return true;
502 }
503 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000504 if (ExtVTs[0] == EMVT::isFP && EMVT::isExtFloatingPointInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000505 assert(hasTypeSet() && "should be handled above!");
506 std::vector<unsigned char> FVTs =
Duncan Sands83ec4b62008-06-06 12:08:01 +0000507 FilterEVTs(getExtTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000508 if (getExtTypes() == FVTs)
509 return false;
510 setTypes(FVTs);
511 return true;
512 }
513
514 // If we know this is an int or fp type, and we are told it is a specific one,
515 // take the advice.
516 //
517 // Similarly, we should probably set the type here to the intersection of
518 // {isInt|isFP} and ExtVTs
Duncan Sands83ec4b62008-06-06 12:08:01 +0000519 if ((getExtTypeNum(0) == EMVT::isInt &&
520 EMVT::isExtIntegerInVTs(ExtVTs)) ||
521 (getExtTypeNum(0) == EMVT::isFP &&
522 EMVT::isExtFloatingPointInVTs(ExtVTs))) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000523 setTypes(ExtVTs);
524 return true;
525 }
Mon P Wange3b3a722008-07-30 04:36:53 +0000526 if (getExtTypeNum(0) == EMVT::isInt &&
527 (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000528 setTypes(ExtVTs);
529 return true;
530 }
531
532 if (isLeaf()) {
533 dump();
534 cerr << " ";
535 TP.error("Type inference contradiction found in node!");
536 } else {
537 TP.error("Type inference contradiction found in node " +
538 getOperator()->getName() + "!");
539 }
540 return true; // unreachable
541}
542
543
544void TreePatternNode::print(std::ostream &OS) const {
545 if (isLeaf()) {
546 OS << *getLeafValue();
547 } else {
548 OS << "(" << getOperator()->getName();
549 }
550
551 // FIXME: At some point we should handle printing all the value types for
552 // nodes that are multiply typed.
553 switch (getExtTypeNum(0)) {
554 case MVT::Other: OS << ":Other"; break;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000555 case EMVT::isInt: OS << ":isInt"; break;
556 case EMVT::isFP : OS << ":isFP"; break;
557 case EMVT::isUnknown: ; /*OS << ":?";*/ break;
Chris Lattner6cefb772008-01-05 22:25:12 +0000558 case MVT::iPTR: OS << ":iPTR"; break;
Mon P Wange3b3a722008-07-30 04:36:53 +0000559 case MVT::iPTRAny: OS << ":iPTRAny"; break;
Chris Lattner6cefb772008-01-05 22:25:12 +0000560 default: {
561 std::string VTName = llvm::getName(getTypeNum(0));
562 // Strip off MVT:: prefix if present.
563 if (VTName.substr(0,5) == "MVT::")
564 VTName = VTName.substr(5);
565 OS << ":" << VTName;
566 break;
567 }
568 }
569
570 if (!isLeaf()) {
571 if (getNumChildren() != 0) {
572 OS << " ";
573 getChild(0)->print(OS);
574 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
575 OS << ", ";
576 getChild(i)->print(OS);
577 }
578 }
579 OS << ")";
580 }
581
Dan Gohman0540e172008-10-15 06:17:21 +0000582 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
583 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000584 if (TransformFn)
585 OS << "<<X:" << TransformFn->getName() << ">>";
586 if (!getName().empty())
587 OS << ":$" << getName();
588
589}
590void TreePatternNode::dump() const {
591 print(*cerr.stream());
592}
593
Scott Michel327d0652008-03-05 17:49:05 +0000594/// isIsomorphicTo - Return true if this node is recursively
595/// isomorphic to the specified node. For this comparison, the node's
596/// entire state is considered. The assigned name is ignored, since
597/// nodes with differing names are considered isomorphic. However, if
598/// the assigned name is present in the dependent variable set, then
599/// the assigned name is considered significant and the node is
600/// isomorphic if the names match.
601bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
602 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000603 if (N == this) return true;
604 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000605 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000606 getTransformFn() != N->getTransformFn())
607 return false;
608
609 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000610 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
611 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000612 return ((DI->getDef() == NDI->getDef())
613 && (DepVars.find(getName()) == DepVars.end()
614 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000615 }
616 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000617 return getLeafValue() == N->getLeafValue();
618 }
619
620 if (N->getOperator() != getOperator() ||
621 N->getNumChildren() != getNumChildren()) return false;
622 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000623 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000624 return false;
625 return true;
626}
627
628/// clone - Make a copy of this tree and all of its children.
629///
630TreePatternNode *TreePatternNode::clone() const {
631 TreePatternNode *New;
632 if (isLeaf()) {
633 New = new TreePatternNode(getLeafValue());
634 } else {
635 std::vector<TreePatternNode*> CChildren;
636 CChildren.reserve(Children.size());
637 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
638 CChildren.push_back(getChild(i)->clone());
639 New = new TreePatternNode(getOperator(), CChildren);
640 }
641 New->setName(getName());
642 New->setTypes(getExtTypes());
Dan Gohman0540e172008-10-15 06:17:21 +0000643 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000644 New->setTransformFn(getTransformFn());
645 return New;
646}
647
648/// SubstituteFormalArguments - Replace the formal arguments in this tree
649/// with actual values specified by ArgMap.
650void TreePatternNode::
651SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
652 if (isLeaf()) return;
653
654 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
655 TreePatternNode *Child = getChild(i);
656 if (Child->isLeaf()) {
657 Init *Val = Child->getLeafValue();
658 if (dynamic_cast<DefInit*>(Val) &&
659 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
660 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000661 TreePatternNode *NewChild = ArgMap[Child->getName()];
662 assert(NewChild && "Couldn't find formal argument!");
663 assert((Child->getPredicateFns().empty() ||
664 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
665 "Non-empty child predicate clobbered!");
666 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000667 }
668 } else {
669 getChild(i)->SubstituteFormalArguments(ArgMap);
670 }
671 }
672}
673
674
675/// InlinePatternFragments - If this pattern refers to any pattern
676/// fragments, inline them into place, giving us a pattern without any
677/// PatFrag references.
678TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
679 if (isLeaf()) return this; // nothing to do.
680 Record *Op = getOperator();
681
682 if (!Op->isSubClassOf("PatFrag")) {
683 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000684 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
685 TreePatternNode *Child = getChild(i);
686 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
687
688 assert((Child->getPredicateFns().empty() ||
689 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
690 "Non-empty child predicate clobbered!");
691
692 setChild(i, NewChild);
693 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000694 return this;
695 }
696
697 // Otherwise, we found a reference to a fragment. First, look up its
698 // TreePattern record.
699 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
700
701 // Verify that we are passing the right number of operands.
702 if (Frag->getNumArgs() != Children.size())
703 TP.error("'" + Op->getName() + "' fragment requires " +
704 utostr(Frag->getNumArgs()) + " operands!");
705
706 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
707
Dan Gohman0540e172008-10-15 06:17:21 +0000708 std::string Code = Op->getValueAsCode("Predicate");
709 if (!Code.empty())
710 FragTree->addPredicateFn("Predicate_"+Op->getName());
711
Chris Lattner6cefb772008-01-05 22:25:12 +0000712 // Resolve formal arguments to their actual value.
713 if (Frag->getNumArgs()) {
714 // Compute the map of formal to actual arguments.
715 std::map<std::string, TreePatternNode*> ArgMap;
716 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
717 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
718
719 FragTree->SubstituteFormalArguments(ArgMap);
720 }
721
722 FragTree->setName(getName());
723 FragTree->UpdateNodeType(getExtTypes(), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000724
725 // Transfer in the old predicates.
726 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
727 FragTree->addPredicateFn(getPredicateFns()[i]);
728
Chris Lattner6cefb772008-01-05 22:25:12 +0000729 // Get a new copy of this fragment to stitch into here.
730 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000731
732 // The fragment we inlined could have recursive inlining that is needed. See
733 // if there are any pattern fragments in it and inline them as needed.
734 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000735}
736
737/// getImplicitType - Check to see if the specified record has an implicit
738/// type which should be applied to it. This infer the type of register
739/// references from the register file information, for example.
740///
741static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
742 TreePattern &TP) {
743 // Some common return values
Duncan Sands83ec4b62008-06-06 12:08:01 +0000744 std::vector<unsigned char> Unknown(1, EMVT::isUnknown);
Chris Lattner6cefb772008-01-05 22:25:12 +0000745 std::vector<unsigned char> Other(1, MVT::Other);
746
747 // Check to see if this is a register or a register class...
748 if (R->isSubClassOf("RegisterClass")) {
749 if (NotRegisters)
750 return Unknown;
751 const CodeGenRegisterClass &RC =
752 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
753 return ConvertVTs(RC.getValueTypes());
754 } else if (R->isSubClassOf("PatFrag")) {
755 // Pattern fragment types will be resolved when they are inlined.
756 return Unknown;
757 } else if (R->isSubClassOf("Register")) {
758 if (NotRegisters)
759 return Unknown;
760 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
761 return T.getRegisterVTs(R);
762 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
763 // Using a VTSDNode or CondCodeSDNode.
764 return Other;
765 } else if (R->isSubClassOf("ComplexPattern")) {
766 if (NotRegisters)
767 return Unknown;
768 std::vector<unsigned char>
769 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
770 return ComplexPat;
771 } else if (R->getName() == "ptr_rc") {
772 Other[0] = MVT::iPTR;
773 return Other;
774 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
775 R->getName() == "zero_reg") {
776 // Placeholder.
777 return Unknown;
778 }
779
780 TP.error("Unknown node flavor used in pattern: " + R->getName());
781 return Other;
782}
783
Chris Lattnere67bde52008-01-06 05:36:50 +0000784
785/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
786/// CodeGenIntrinsic information for it, otherwise return a null pointer.
787const CodeGenIntrinsic *TreePatternNode::
788getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
789 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
790 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
791 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
792 return 0;
793
794 unsigned IID =
795 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
796 return &CDP.getIntrinsicInfo(IID);
797}
798
Evan Cheng6bd95672008-06-16 20:29:38 +0000799/// isCommutativeIntrinsic - Return true if the node corresponds to a
800/// commutative intrinsic.
801bool
802TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
803 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
804 return Int->isCommutative;
805 return false;
806}
807
Chris Lattnere67bde52008-01-06 05:36:50 +0000808
Chris Lattner6cefb772008-01-05 22:25:12 +0000809/// ApplyTypeConstraints - Apply all of the type constraints relevent to
810/// this node and its children in the tree. This returns true if it makes a
811/// change, false otherwise. If a type contradiction is found, throw an
812/// exception.
813bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +0000814 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +0000815 if (isLeaf()) {
816 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
817 // If it's a regclass or something else known, include the type.
818 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
819 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
820 // Int inits are always integers. :)
Duncan Sands83ec4b62008-06-06 12:08:01 +0000821 bool MadeChange = UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000822
823 if (hasTypeSet()) {
824 // At some point, it may make sense for this tree pattern to have
825 // multiple types. Assert here that it does not, so we revisit this
826 // code when appropriate.
827 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000828 MVT::SimpleValueType VT = getTypeNum(0);
Chris Lattner6cefb772008-01-05 22:25:12 +0000829 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
830 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
831
832 VT = getTypeNum(0);
Mon P Wange3b3a722008-07-30 04:36:53 +0000833 if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000834 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattner6cefb772008-01-05 22:25:12 +0000835 // Make sure that the value is representable for this type.
836 if (Size < 32) {
837 int Val = (II->getValue() << (32-Size)) >> (32-Size);
Scott Michel0123b7d2008-02-15 23:05:48 +0000838 if (Val != II->getValue()) {
Bill Wendling27926af2008-02-26 10:45:29 +0000839 // If sign-extended doesn't fit, does it fit as unsigned?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000840 unsigned ValueMask;
841 unsigned UnsignedVal;
842 ValueMask = unsigned(MVT(VT).getIntegerVTBitMask());
843 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +0000844
Bill Wendling27926af2008-02-26 10:45:29 +0000845 if ((ValueMask & UnsignedVal) != UnsignedVal) {
846 TP.error("Integer value '" + itostr(II->getValue())+
847 "' is out of range for type '" +
848 getEnumName(getTypeNum(0)) + "'!");
849 }
850 }
851 }
852 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000853 }
854
855 return MadeChange;
856 }
857 return false;
858 }
859
860 // special handling for set, which isn't really an SDNode.
861 if (getOperator()->getName() == "set") {
862 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
863 unsigned NC = getNumChildren();
864 bool MadeChange = false;
865 for (unsigned i = 0; i < NC-1; ++i) {
866 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
867 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
868
869 // Types of operands must match.
870 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
871 TP);
872 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
873 TP);
874 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
875 }
876 return MadeChange;
877 } else if (getOperator()->getName() == "implicit" ||
878 getOperator()->getName() == "parallel") {
879 bool MadeChange = false;
880 for (unsigned i = 0; i < getNumChildren(); ++i)
881 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
882 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
883 return MadeChange;
Chris Lattnere67bde52008-01-06 05:36:50 +0000884 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000885 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000886
Chris Lattner6cefb772008-01-05 22:25:12 +0000887 // Apply the result type to the node.
Chris Lattnere67bde52008-01-06 05:36:50 +0000888 MadeChange = UpdateNodeType(Int->ArgVTs[0], TP);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000889
Chris Lattnere67bde52008-01-06 05:36:50 +0000890 if (getNumChildren() != Int->ArgVTs.size())
891 TP.error("Intrinsic '" + Int->Name + "' expects " +
892 utostr(Int->ArgVTs.size()-1) + " operands, not " +
Chris Lattner6cefb772008-01-05 22:25:12 +0000893 utostr(getNumChildren()-1) + " operands!");
894
895 // Apply type info to the intrinsic ID.
896 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
897
898 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000899 MVT::SimpleValueType OpVT = Int->ArgVTs[i];
Chris Lattner6cefb772008-01-05 22:25:12 +0000900 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
901 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
902 }
903 return MadeChange;
904 } else if (getOperator()->isSubClassOf("SDNode")) {
905 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
906
907 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
908 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
909 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
910 // Branch, etc. do not produce results and top-level forms in instr pattern
911 // must have void types.
912 if (NI.getNumResults() == 0)
913 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
914
915 // If this is a vector_shuffle operation, apply types to the build_vector
916 // operation. The types of the integers don't matter, but this ensures they
917 // won't get checked.
918 if (getOperator()->getName() == "vector_shuffle" &&
919 getChild(2)->getOperator()->getName() == "build_vector") {
920 TreePatternNode *BV = getChild(2);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000921 const std::vector<MVT::SimpleValueType> &LegalVTs
Chris Lattner6cefb772008-01-05 22:25:12 +0000922 = CDP.getTargetInfo().getLegalValueTypes();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000923 MVT::SimpleValueType LegalIntVT = MVT::Other;
Chris Lattner6cefb772008-01-05 22:25:12 +0000924 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +0000925 if (isInteger(LegalVTs[i]) && !isVector(LegalVTs[i])) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000926 LegalIntVT = LegalVTs[i];
927 break;
928 }
929 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
930
931 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
932 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
933 }
934 return MadeChange;
935 } else if (getOperator()->isSubClassOf("Instruction")) {
936 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
937 bool MadeChange = false;
938 unsigned NumResults = Inst.getNumResults();
939
940 assert(NumResults <= 1 &&
941 "Only supports zero or one result instrs!");
942
943 CodeGenInstruction &InstInfo =
944 CDP.getTargetInfo().getInstruction(getOperator()->getName());
945 // Apply the result type to the node
946 if (NumResults == 0 || InstInfo.NumDefs == 0) {
Christopher Lamb02f69372008-03-10 04:16:09 +0000947 MadeChange = UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000948 } else {
949 Record *ResultNode = Inst.getResult(0);
950
951 if (ResultNode->getName() == "ptr_rc") {
952 std::vector<unsigned char> VT;
953 VT.push_back(MVT::iPTR);
954 MadeChange = UpdateNodeType(VT, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +0000955 } else if (ResultNode->getName() == "unknown") {
956 std::vector<unsigned char> VT;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000957 VT.push_back(EMVT::isUnknown);
Christopher Lamb5b415372008-03-11 09:33:47 +0000958 MadeChange = UpdateNodeType(VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000959 } else {
960 assert(ResultNode->isSubClassOf("RegisterClass") &&
961 "Operands should be register classes!");
962
963 const CodeGenRegisterClass &RC =
964 CDP.getTargetInfo().getRegisterClass(ResultNode);
965 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
966 }
967 }
968
969 unsigned ChildNo = 0;
970 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
971 Record *OperandNode = Inst.getOperand(i);
972
973 // If the instruction expects a predicate or optional def operand, we
974 // codegen this by setting the operand to it's default value if it has a
975 // non-empty DefaultOps field.
976 if ((OperandNode->isSubClassOf("PredicateOperand") ||
977 OperandNode->isSubClassOf("OptionalDefOperand")) &&
978 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
979 continue;
980
981 // Verify that we didn't run out of provided operands.
982 if (ChildNo >= getNumChildren())
983 TP.error("Instruction '" + getOperator()->getName() +
984 "' expects more operands than were provided.");
985
Duncan Sands83ec4b62008-06-06 12:08:01 +0000986 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +0000987 TreePatternNode *Child = getChild(ChildNo++);
988 if (OperandNode->isSubClassOf("RegisterClass")) {
989 const CodeGenRegisterClass &RC =
990 CDP.getTargetInfo().getRegisterClass(OperandNode);
991 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
992 } else if (OperandNode->isSubClassOf("Operand")) {
993 VT = getValueType(OperandNode->getValueAsDef("Type"));
994 MadeChange |= Child->UpdateNodeType(VT, TP);
995 } else if (OperandNode->getName() == "ptr_rc") {
996 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +0000997 } else if (OperandNode->getName() == "unknown") {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000998 MadeChange |= Child->UpdateNodeType(EMVT::isUnknown, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000999 } else {
1000 assert(0 && "Unknown operand type!");
1001 abort();
1002 }
1003 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1004 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001005
Christopher Lamb02f69372008-03-10 04:16:09 +00001006 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001007 TP.error("Instruction '" + getOperator()->getName() +
1008 "' was provided too many operands!");
1009
1010 return MadeChange;
1011 } else {
1012 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1013
1014 // Node transforms always take one operand.
1015 if (getNumChildren() != 1)
1016 TP.error("Node transform '" + getOperator()->getName() +
1017 "' requires one operand!");
1018
1019 // If either the output or input of the xform does not have exact
1020 // type info. We assume they must be the same. Otherwise, it is perfectly
1021 // legal to transform from one type to a completely different type.
1022 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1023 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
1024 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
1025 return MadeChange;
1026 }
1027 return false;
1028 }
1029}
1030
1031/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1032/// RHS of a commutative operation, not the on LHS.
1033static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1034 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1035 return true;
1036 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1037 return true;
1038 return false;
1039}
1040
1041
1042/// canPatternMatch - If it is impossible for this pattern to match on this
1043/// target, fill in Reason and return false. Otherwise, return true. This is
1044/// used as a santity check for .td files (to prevent people from writing stuff
1045/// that can never possibly work), and to prevent the pattern permuter from
1046/// generating stuff that is useless.
1047bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001048 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001049 if (isLeaf()) return true;
1050
1051 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1052 if (!getChild(i)->canPatternMatch(Reason, CDP))
1053 return false;
1054
1055 // If this is an intrinsic, handle cases that would make it not match. For
1056 // example, if an operand is required to be an immediate.
1057 if (getOperator()->isSubClassOf("Intrinsic")) {
1058 // TODO:
1059 return true;
1060 }
1061
1062 // If this node is a commutative operator, check that the LHS isn't an
1063 // immediate.
1064 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001065 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1066 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001067 // Scan all of the operands of the node and make sure that only the last one
1068 // is a constant node, unless the RHS also is.
1069 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001070 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1071 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001072 if (OnlyOnRHSOfCommutative(getChild(i))) {
1073 Reason="Immediate value must be on the RHS of commutative operators!";
1074 return false;
1075 }
1076 }
1077 }
1078
1079 return true;
1080}
1081
1082//===----------------------------------------------------------------------===//
1083// TreePattern implementation
1084//
1085
1086TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001087 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001088 isInputPattern = isInput;
1089 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1090 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1091}
1092
1093TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001094 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001095 isInputPattern = isInput;
1096 Trees.push_back(ParseTreePattern(Pat));
1097}
1098
1099TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001100 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001101 isInputPattern = isInput;
1102 Trees.push_back(Pat);
1103}
1104
1105
1106
1107void TreePattern::error(const std::string &Msg) const {
1108 dump();
1109 throw "In " + TheRecord->getName() + ": " + Msg;
1110}
1111
1112TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1113 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1114 if (!OpDef) error("Pattern has unexpected operator type!");
1115 Record *Operator = OpDef->getDef();
1116
1117 if (Operator->isSubClassOf("ValueType")) {
1118 // If the operator is a ValueType, then this must be "type cast" of a leaf
1119 // node.
1120 if (Dag->getNumArgs() != 1)
1121 error("Type cast only takes one operand!");
1122
1123 Init *Arg = Dag->getArg(0);
1124 TreePatternNode *New;
1125 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1126 Record *R = DI->getDef();
1127 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1128 Dag->setArg(0, new DagInit(DI,
1129 std::vector<std::pair<Init*, std::string> >()));
1130 return ParseTreePattern(Dag);
1131 }
1132 New = new TreePatternNode(DI);
1133 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1134 New = ParseTreePattern(DI);
1135 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1136 New = new TreePatternNode(II);
1137 if (!Dag->getArgName(0).empty())
1138 error("Constant int argument should not have a name!");
1139 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1140 // Turn this into an IntInit.
1141 Init *II = BI->convertInitializerTo(new IntRecTy());
1142 if (II == 0 || !dynamic_cast<IntInit*>(II))
1143 error("Bits value must be constants!");
1144
1145 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1146 if (!Dag->getArgName(0).empty())
1147 error("Constant int argument should not have a name!");
1148 } else {
1149 Arg->dump();
1150 error("Unknown leaf value for tree pattern!");
1151 return 0;
1152 }
1153
1154 // Apply the type cast.
1155 New->UpdateNodeType(getValueType(Operator), *this);
1156 New->setName(Dag->getArgName(0));
1157 return New;
1158 }
1159
1160 // Verify that this is something that makes sense for an operator.
1161 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
1162 !Operator->isSubClassOf("Instruction") &&
1163 !Operator->isSubClassOf("SDNodeXForm") &&
1164 !Operator->isSubClassOf("Intrinsic") &&
1165 Operator->getName() != "set" &&
1166 Operator->getName() != "implicit" &&
1167 Operator->getName() != "parallel")
1168 error("Unrecognized node '" + Operator->getName() + "'!");
1169
1170 // Check to see if this is something that is illegal in an input pattern.
1171 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1172 Operator->isSubClassOf("SDNodeXForm")))
1173 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1174
1175 std::vector<TreePatternNode*> Children;
1176
1177 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1178 Init *Arg = Dag->getArg(i);
1179 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1180 Children.push_back(ParseTreePattern(DI));
1181 if (Children.back()->getName().empty())
1182 Children.back()->setName(Dag->getArgName(i));
1183 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1184 Record *R = DefI->getDef();
1185 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1186 // TreePatternNode if its own.
1187 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1188 Dag->setArg(i, new DagInit(DefI,
1189 std::vector<std::pair<Init*, std::string> >()));
1190 --i; // Revisit this node...
1191 } else {
1192 TreePatternNode *Node = new TreePatternNode(DefI);
1193 Node->setName(Dag->getArgName(i));
1194 Children.push_back(Node);
1195
1196 // Input argument?
1197 if (R->getName() == "node") {
1198 if (Dag->getArgName(i).empty())
1199 error("'node' argument requires a name to match with operand list");
1200 Args.push_back(Dag->getArgName(i));
1201 }
1202 }
1203 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1204 TreePatternNode *Node = new TreePatternNode(II);
1205 if (!Dag->getArgName(i).empty())
1206 error("Constant int argument should not have a name!");
1207 Children.push_back(Node);
1208 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1209 // Turn this into an IntInit.
1210 Init *II = BI->convertInitializerTo(new IntRecTy());
1211 if (II == 0 || !dynamic_cast<IntInit*>(II))
1212 error("Bits value must be constants!");
1213
1214 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1215 if (!Dag->getArgName(i).empty())
1216 error("Constant int argument should not have a name!");
1217 Children.push_back(Node);
1218 } else {
1219 cerr << '"';
1220 Arg->dump();
1221 cerr << "\": ";
1222 error("Unknown leaf value for tree pattern!");
1223 }
1224 }
1225
1226 // If the operator is an intrinsic, then this is just syntactic sugar for for
1227 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1228 // convert the intrinsic name to a number.
1229 if (Operator->isSubClassOf("Intrinsic")) {
1230 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1231 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1232
1233 // If this intrinsic returns void, it must have side-effects and thus a
1234 // chain.
1235 if (Int.ArgVTs[0] == MVT::isVoid) {
1236 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1237 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1238 // Has side-effects, requires chain.
1239 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1240 } else {
1241 // Otherwise, no chain.
1242 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1243 }
1244
1245 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1246 Children.insert(Children.begin(), IIDNode);
1247 }
1248
1249 return new TreePatternNode(Operator, Children);
1250}
1251
1252/// InferAllTypes - Infer/propagate as many types throughout the expression
1253/// patterns as possible. Return true if all types are infered, false
1254/// otherwise. Throw an exception if a type contradiction is found.
1255bool TreePattern::InferAllTypes() {
1256 bool MadeChange = true;
1257 while (MadeChange) {
1258 MadeChange = false;
1259 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1260 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1261 }
1262
1263 bool HasUnresolvedTypes = false;
1264 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1265 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1266 return !HasUnresolvedTypes;
1267}
1268
1269void TreePattern::print(std::ostream &OS) const {
1270 OS << getRecord()->getName();
1271 if (!Args.empty()) {
1272 OS << "(" << Args[0];
1273 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1274 OS << ", " << Args[i];
1275 OS << ")";
1276 }
1277 OS << ": ";
1278
1279 if (Trees.size() > 1)
1280 OS << "[\n";
1281 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1282 OS << "\t";
1283 Trees[i]->print(OS);
1284 OS << "\n";
1285 }
1286
1287 if (Trees.size() > 1)
1288 OS << "]\n";
1289}
1290
1291void TreePattern::dump() const { print(*cerr.stream()); }
1292
1293//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001294// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001295//
1296
1297// FIXME: REMOVE OSTREAM ARGUMENT
Chris Lattnerfe718932008-01-06 01:10:31 +00001298CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001299 Intrinsics = LoadIntrinsics(Records);
1300 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001301 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001302 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001303 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001304 ParseDefaultOperands();
1305 ParseInstructions();
1306 ParsePatterns();
1307
1308 // Generate variants. For example, commutative patterns can match
1309 // multiple ways. Add them to PatternsToMatch as well.
1310 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001311
1312 // Infer instruction flags. For example, we can detect loads,
1313 // stores, and side effects in many cases by examining an
1314 // instruction's pattern.
1315 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001316}
1317
Chris Lattnerfe718932008-01-06 01:10:31 +00001318CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001319 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1320 E = PatternFragments.end(); I != E; ++I)
1321 delete I->second;
1322}
1323
1324
Chris Lattnerfe718932008-01-06 01:10:31 +00001325Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001326 Record *N = Records.getDef(Name);
1327 if (!N || !N->isSubClassOf("SDNode")) {
1328 cerr << "Error getting SDNode '" << Name << "'!\n";
1329 exit(1);
1330 }
1331 return N;
1332}
1333
1334// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001335void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001336 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1337 while (!Nodes.empty()) {
1338 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1339 Nodes.pop_back();
1340 }
1341
1342 // Get the buildin intrinsic nodes.
1343 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1344 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1345 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1346}
1347
1348/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1349/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001350void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001351 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1352 while (!Xforms.empty()) {
1353 Record *XFormNode = Xforms.back();
1354 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1355 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001356 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001357
1358 Xforms.pop_back();
1359 }
1360}
1361
Chris Lattnerfe718932008-01-06 01:10:31 +00001362void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001363 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1364 while (!AMs.empty()) {
1365 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1366 AMs.pop_back();
1367 }
1368}
1369
1370
1371/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1372/// file, building up the PatternFragments map. After we've collected them all,
1373/// inline fragments together as necessary, so that there are no references left
1374/// inside a pattern fragment to a pattern fragment.
1375///
Chris Lattnerfe718932008-01-06 01:10:31 +00001376void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001377 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1378
Chris Lattnerdc32f982008-01-05 22:43:57 +00001379 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001380 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1381 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1382 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1383 PatternFragments[Fragments[i]] = P;
1384
Chris Lattnerdc32f982008-01-05 22:43:57 +00001385 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001386 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001387 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001388
Chris Lattnerdc32f982008-01-05 22:43:57 +00001389 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001390 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1391
1392 // Parse the operands list.
1393 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1394 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1395 // Special cases: ops == outs == ins. Different names are used to
1396 // improve readibility.
1397 if (!OpsOp ||
1398 (OpsOp->getDef()->getName() != "ops" &&
1399 OpsOp->getDef()->getName() != "outs" &&
1400 OpsOp->getDef()->getName() != "ins"))
1401 P->error("Operands list should start with '(ops ... '!");
1402
1403 // Copy over the arguments.
1404 Args.clear();
1405 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1406 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1407 static_cast<DefInit*>(OpsList->getArg(j))->
1408 getDef()->getName() != "node")
1409 P->error("Operands list should all be 'node' values.");
1410 if (OpsList->getArgName(j).empty())
1411 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001412 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001413 P->error("'" + OpsList->getArgName(j) +
1414 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001415 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001416 Args.push_back(OpsList->getArgName(j));
1417 }
1418
Chris Lattnerdc32f982008-01-05 22:43:57 +00001419 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001420 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001421 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001422
Chris Lattnerdc32f982008-01-05 22:43:57 +00001423 // If there is a code init for this fragment, keep track of the fact that
1424 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001425 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001426 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001427 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001428
1429 // If there is a node transformation corresponding to this, keep track of
1430 // it.
1431 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1432 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1433 P->getOnlyTree()->setTransformFn(Transform);
1434 }
1435
Chris Lattner6cefb772008-01-05 22:25:12 +00001436 // Now that we've parsed all of the tree fragments, do a closure on them so
1437 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001438 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1439 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001440 ThePat->InlinePatternFragments();
1441
1442 // Infer as many types as possible. Don't worry about it if we don't infer
1443 // all of them, some may depend on the inputs of the pattern.
1444 try {
1445 ThePat->InferAllTypes();
1446 } catch (...) {
1447 // If this pattern fragment is not supported by this target (no types can
1448 // satisfy its constraints), just ignore it. If the bogus pattern is
1449 // actually used by instructions, the type consistency error will be
1450 // reported there.
1451 }
1452
1453 // If debugging, print out the pattern fragment result.
1454 DEBUG(ThePat->dump());
1455 }
1456}
1457
Chris Lattnerfe718932008-01-06 01:10:31 +00001458void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001459 std::vector<Record*> DefaultOps[2];
1460 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1461 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1462
1463 // Find some SDNode.
1464 assert(!SDNodes.empty() && "No SDNodes parsed?");
1465 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1466
1467 for (unsigned iter = 0; iter != 2; ++iter) {
1468 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1469 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1470
1471 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1472 // SomeSDnode so that we can parse this.
1473 std::vector<std::pair<Init*, std::string> > Ops;
1474 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1475 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1476 DefaultInfo->getArgName(op)));
1477 DagInit *DI = new DagInit(SomeSDNode, Ops);
1478
1479 // Create a TreePattern to parse this.
1480 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1481 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1482
1483 // Copy the operands over into a DAGDefaultOperand.
1484 DAGDefaultOperand DefaultOpInfo;
1485
1486 TreePatternNode *T = P.getTree(0);
1487 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1488 TreePatternNode *TPN = T->getChild(op);
1489 while (TPN->ApplyTypeConstraints(P, false))
1490 /* Resolve all types */;
1491
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001492 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001493 if (iter == 0)
1494 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1495 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1496 else
1497 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1498 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001499 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001500 DefaultOpInfo.DefaultOps.push_back(TPN);
1501 }
1502
1503 // Insert it into the DefaultOperands map so we can find it later.
1504 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1505 }
1506 }
1507}
1508
1509/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1510/// instruction input. Return true if this is a real use.
1511static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1512 std::map<std::string, TreePatternNode*> &InstInputs,
1513 std::vector<Record*> &InstImpInputs) {
1514 // No name -> not interesting.
1515 if (Pat->getName().empty()) {
1516 if (Pat->isLeaf()) {
1517 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1518 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1519 I->error("Input " + DI->getDef()->getName() + " must be named!");
1520 else if (DI && DI->getDef()->isSubClassOf("Register"))
1521 InstImpInputs.push_back(DI->getDef());
1522 ;
1523 }
1524 return false;
1525 }
1526
1527 Record *Rec;
1528 if (Pat->isLeaf()) {
1529 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1530 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1531 Rec = DI->getDef();
1532 } else {
1533 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1534 Rec = Pat->getOperator();
1535 }
1536
1537 // SRCVALUE nodes are ignored.
1538 if (Rec->getName() == "srcvalue")
1539 return false;
1540
1541 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1542 if (!Slot) {
1543 Slot = Pat;
1544 } else {
1545 Record *SlotRec;
1546 if (Slot->isLeaf()) {
1547 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1548 } else {
1549 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1550 SlotRec = Slot->getOperator();
1551 }
1552
1553 // Ensure that the inputs agree if we've already seen this input.
1554 if (Rec != SlotRec)
1555 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1556 if (Slot->getExtTypes() != Pat->getExtTypes())
1557 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1558 }
1559 return true;
1560}
1561
1562/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1563/// part of "I", the instruction), computing the set of inputs and outputs of
1564/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001565void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001566FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1567 std::map<std::string, TreePatternNode*> &InstInputs,
1568 std::map<std::string, TreePatternNode*>&InstResults,
1569 std::vector<Record*> &InstImpInputs,
1570 std::vector<Record*> &InstImpResults) {
1571 if (Pat->isLeaf()) {
1572 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1573 if (!isUse && Pat->getTransformFn())
1574 I->error("Cannot specify a transform function for a non-input value!");
1575 return;
1576 } else if (Pat->getOperator()->getName() == "implicit") {
1577 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1578 TreePatternNode *Dest = Pat->getChild(i);
1579 if (!Dest->isLeaf())
1580 I->error("implicitly defined value should be a register!");
1581
1582 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1583 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1584 I->error("implicitly defined value should be a register!");
1585 InstImpResults.push_back(Val->getDef());
1586 }
1587 return;
1588 } else if (Pat->getOperator()->getName() != "set") {
1589 // If this is not a set, verify that the children nodes are not void typed,
1590 // and recurse.
1591 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1592 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1593 I->error("Cannot have void nodes inside of patterns!");
1594 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1595 InstImpInputs, InstImpResults);
1596 }
1597
1598 // If this is a non-leaf node with no children, treat it basically as if
1599 // it were a leaf. This handles nodes like (imm).
1600 bool isUse = false;
1601 if (Pat->getNumChildren() == 0)
1602 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1603
1604 if (!isUse && Pat->getTransformFn())
1605 I->error("Cannot specify a transform function for a non-input value!");
1606 return;
1607 }
1608
1609 // Otherwise, this is a set, validate and collect instruction results.
1610 if (Pat->getNumChildren() == 0)
1611 I->error("set requires operands!");
1612
1613 if (Pat->getTransformFn())
1614 I->error("Cannot specify a transform function on a set node!");
1615
1616 // Check the set destinations.
1617 unsigned NumDests = Pat->getNumChildren()-1;
1618 for (unsigned i = 0; i != NumDests; ++i) {
1619 TreePatternNode *Dest = Pat->getChild(i);
1620 if (!Dest->isLeaf())
1621 I->error("set destination should be a register!");
1622
1623 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1624 if (!Val)
1625 I->error("set destination should be a register!");
1626
1627 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1628 Val->getDef()->getName() == "ptr_rc") {
1629 if (Dest->getName().empty())
1630 I->error("set destination must have a name!");
1631 if (InstResults.count(Dest->getName()))
1632 I->error("cannot set '" + Dest->getName() +"' multiple times");
1633 InstResults[Dest->getName()] = Dest;
1634 } else if (Val->getDef()->isSubClassOf("Register")) {
1635 InstImpResults.push_back(Val->getDef());
1636 } else {
1637 I->error("set destination should be a register!");
1638 }
1639 }
1640
1641 // Verify and collect info from the computation.
1642 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1643 InstInputs, InstResults,
1644 InstImpInputs, InstImpResults);
1645}
1646
Dan Gohmanee4fa192008-04-03 00:02:49 +00001647//===----------------------------------------------------------------------===//
1648// Instruction Analysis
1649//===----------------------------------------------------------------------===//
1650
1651class InstAnalyzer {
1652 const CodeGenDAGPatterns &CDP;
1653 bool &mayStore;
1654 bool &mayLoad;
1655 bool &HasSideEffects;
1656public:
1657 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1658 bool &maystore, bool &mayload, bool &hse)
1659 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1660 }
1661
1662 /// Analyze - Analyze the specified instruction, returning true if the
1663 /// instruction had a pattern.
1664 bool Analyze(Record *InstRecord) {
1665 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1666 if (Pattern == 0) {
1667 HasSideEffects = 1;
1668 return false; // No pattern.
1669 }
1670
1671 // FIXME: Assume only the first tree is the pattern. The others are clobber
1672 // nodes.
1673 AnalyzeNode(Pattern->getTree(0));
1674 return true;
1675 }
1676
1677private:
1678 void AnalyzeNode(const TreePatternNode *N) {
1679 if (N->isLeaf()) {
1680 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1681 Record *LeafRec = DI->getDef();
1682 // Handle ComplexPattern leaves.
1683 if (LeafRec->isSubClassOf("ComplexPattern")) {
1684 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1685 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1686 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1687 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1688 }
1689 }
1690 return;
1691 }
1692
1693 // Analyze children.
1694 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1695 AnalyzeNode(N->getChild(i));
1696
1697 // Ignore set nodes, which are not SDNodes.
1698 if (N->getOperator()->getName() == "set")
1699 return;
1700
1701 // Get information about the SDNode for the operator.
1702 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1703
1704 // Notice properties of the node.
1705 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1706 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1707 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1708
1709 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1710 // If this is an intrinsic, analyze it.
1711 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1712 mayLoad = true;// These may load memory.
1713
1714 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1715 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1716
1717 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1718 // WriteMem intrinsics can have other strange effects.
1719 HasSideEffects = true;
1720 }
1721 }
1722
1723};
1724
1725static void InferFromPattern(const CodeGenInstruction &Inst,
1726 bool &MayStore, bool &MayLoad,
1727 bool &HasSideEffects,
1728 const CodeGenDAGPatterns &CDP) {
1729 MayStore = MayLoad = HasSideEffects = false;
1730
1731 bool HadPattern =
1732 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1733
1734 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1735 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1736 // If we decided that this is a store from the pattern, then the .td file
1737 // entry is redundant.
1738 if (MayStore)
1739 fprintf(stderr,
1740 "Warning: mayStore flag explicitly set on instruction '%s'"
1741 " but flag already inferred from pattern.\n",
1742 Inst.TheDef->getName().c_str());
1743 MayStore = true;
1744 }
1745
1746 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1747 // If we decided that this is a load from the pattern, then the .td file
1748 // entry is redundant.
1749 if (MayLoad)
1750 fprintf(stderr,
1751 "Warning: mayLoad flag explicitly set on instruction '%s'"
1752 " but flag already inferred from pattern.\n",
1753 Inst.TheDef->getName().c_str());
1754 MayLoad = true;
1755 }
1756
1757 if (Inst.neverHasSideEffects) {
1758 if (HadPattern)
1759 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1760 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1761 HasSideEffects = false;
1762 }
1763
1764 if (Inst.hasSideEffects) {
1765 if (HasSideEffects)
1766 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1767 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1768 HasSideEffects = true;
1769 }
1770}
1771
Chris Lattner6cefb772008-01-05 22:25:12 +00001772/// ParseInstructions - Parse all of the instructions, inlining and resolving
1773/// any fragments involved. This populates the Instructions list with fully
1774/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001775void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001776 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1777
1778 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1779 ListInit *LI = 0;
1780
1781 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1782 LI = Instrs[i]->getValueAsListInit("Pattern");
1783
1784 // If there is no pattern, only collect minimal information about the
1785 // instruction for its operand list. We have to assume that there is one
1786 // result, as we have no detailed info.
1787 if (!LI || LI->getSize() == 0) {
1788 std::vector<Record*> Results;
1789 std::vector<Record*> Operands;
1790
1791 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1792
1793 if (InstInfo.OperandList.size() != 0) {
1794 if (InstInfo.NumDefs == 0) {
1795 // These produce no results
1796 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1797 Operands.push_back(InstInfo.OperandList[j].Rec);
1798 } else {
1799 // Assume the first operand is the result.
1800 Results.push_back(InstInfo.OperandList[0].Rec);
1801
1802 // The rest are inputs.
1803 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1804 Operands.push_back(InstInfo.OperandList[j].Rec);
1805 }
1806 }
1807
1808 // Create and insert the instruction.
1809 std::vector<Record*> ImpResults;
1810 std::vector<Record*> ImpOperands;
1811 Instructions.insert(std::make_pair(Instrs[i],
1812 DAGInstruction(0, Results, Operands, ImpResults,
1813 ImpOperands)));
1814 continue; // no pattern.
1815 }
1816
1817 // Parse the instruction.
1818 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1819 // Inline pattern fragments into it.
1820 I->InlinePatternFragments();
1821
1822 // Infer as many types as possible. If we cannot infer all of them, we can
1823 // never do anything with this instruction pattern: report it to the user.
1824 if (!I->InferAllTypes())
1825 I->error("Could not infer all types in pattern!");
1826
1827 // InstInputs - Keep track of all of the inputs of the instruction, along
1828 // with the record they are declared as.
1829 std::map<std::string, TreePatternNode*> InstInputs;
1830
1831 // InstResults - Keep track of all the virtual registers that are 'set'
1832 // in the instruction, including what reg class they are.
1833 std::map<std::string, TreePatternNode*> InstResults;
1834
1835 std::vector<Record*> InstImpInputs;
1836 std::vector<Record*> InstImpResults;
1837
1838 // Verify that the top-level forms in the instruction are of void type, and
1839 // fill in the InstResults map.
1840 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1841 TreePatternNode *Pat = I->getTree(j);
1842 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1843 I->error("Top-level forms in instruction pattern should have"
1844 " void types");
1845
1846 // Find inputs and outputs, and verify the structure of the uses/defs.
1847 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1848 InstImpInputs, InstImpResults);
1849 }
1850
1851 // Now that we have inputs and outputs of the pattern, inspect the operands
1852 // list for the instruction. This determines the order that operands are
1853 // added to the machine instruction the node corresponds to.
1854 unsigned NumResults = InstResults.size();
1855
1856 // Parse the operands list from the (ops) list, validating it.
1857 assert(I->getArgList().empty() && "Args list should still be empty here!");
1858 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1859
1860 // Check that all of the results occur first in the list.
1861 std::vector<Record*> Results;
1862 TreePatternNode *Res0Node = NULL;
1863 for (unsigned i = 0; i != NumResults; ++i) {
1864 if (i == CGI.OperandList.size())
1865 I->error("'" + InstResults.begin()->first +
1866 "' set but does not appear in operand list!");
1867 const std::string &OpName = CGI.OperandList[i].Name;
1868
1869 // Check that it exists in InstResults.
1870 TreePatternNode *RNode = InstResults[OpName];
1871 if (RNode == 0)
1872 I->error("Operand $" + OpName + " does not exist in operand list!");
1873
1874 if (i == 0)
1875 Res0Node = RNode;
1876 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1877 if (R == 0)
1878 I->error("Operand $" + OpName + " should be a set destination: all "
1879 "outputs must occur before inputs in operand list!");
1880
1881 if (CGI.OperandList[i].Rec != R)
1882 I->error("Operand $" + OpName + " class mismatch!");
1883
1884 // Remember the return type.
1885 Results.push_back(CGI.OperandList[i].Rec);
1886
1887 // Okay, this one checks out.
1888 InstResults.erase(OpName);
1889 }
1890
1891 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1892 // the copy while we're checking the inputs.
1893 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1894
1895 std::vector<TreePatternNode*> ResultNodeOperands;
1896 std::vector<Record*> Operands;
1897 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1898 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1899 const std::string &OpName = Op.Name;
1900 if (OpName.empty())
1901 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1902
1903 if (!InstInputsCheck.count(OpName)) {
1904 // If this is an predicate operand or optional def operand with an
1905 // DefaultOps set filled in, we can ignore this. When we codegen it,
1906 // we will do so as always executed.
1907 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1908 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1909 // Does it have a non-empty DefaultOps field? If so, ignore this
1910 // operand.
1911 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1912 continue;
1913 }
1914 I->error("Operand $" + OpName +
1915 " does not appear in the instruction pattern");
1916 }
1917 TreePatternNode *InVal = InstInputsCheck[OpName];
1918 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1919
1920 if (InVal->isLeaf() &&
1921 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1922 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1923 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1924 I->error("Operand $" + OpName + "'s register class disagrees"
1925 " between the operand and pattern");
1926 }
1927 Operands.push_back(Op.Rec);
1928
1929 // Construct the result for the dest-pattern operand list.
1930 TreePatternNode *OpNode = InVal->clone();
1931
1932 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00001933 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001934
1935 // Promote the xform function to be an explicit node if set.
1936 if (Record *Xform = OpNode->getTransformFn()) {
1937 OpNode->setTransformFn(0);
1938 std::vector<TreePatternNode*> Children;
1939 Children.push_back(OpNode);
1940 OpNode = new TreePatternNode(Xform, Children);
1941 }
1942
1943 ResultNodeOperands.push_back(OpNode);
1944 }
1945
1946 if (!InstInputsCheck.empty())
1947 I->error("Input operand $" + InstInputsCheck.begin()->first +
1948 " occurs in pattern but not in operands list!");
1949
1950 TreePatternNode *ResultPattern =
1951 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1952 // Copy fully inferred output node type to instruction result pattern.
1953 if (NumResults > 0)
1954 ResultPattern->setTypes(Res0Node->getExtTypes());
1955
1956 // Create and insert the instruction.
1957 // FIXME: InstImpResults and InstImpInputs should not be part of
1958 // DAGInstruction.
1959 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1960 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1961
1962 // Use a temporary tree pattern to infer all types and make sure that the
1963 // constructed result is correct. This depends on the instruction already
1964 // being inserted into the Instructions map.
1965 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1966 Temp.InferAllTypes();
1967
1968 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1969 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1970
1971 DEBUG(I->dump());
1972 }
1973
1974 // If we can, convert the instructions to be patterns that are matched!
1975 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1976 E = Instructions.end(); II != E; ++II) {
1977 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00001978 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00001979 if (I == 0) continue; // No pattern.
1980
1981 // FIXME: Assume only the first tree is the pattern. The others are clobber
1982 // nodes.
1983 TreePatternNode *Pattern = I->getTree(0);
1984 TreePatternNode *SrcPattern;
1985 if (Pattern->getOperator()->getName() == "set") {
1986 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1987 } else{
1988 // Not a set (store or something?)
1989 SrcPattern = Pattern;
1990 }
1991
1992 std::string Reason;
1993 if (!SrcPattern->canPatternMatch(Reason, *this))
1994 I->error("Instruction can never match: " + Reason);
1995
1996 Record *Instr = II->first;
1997 TreePatternNode *DstPattern = TheInst.getResultPattern();
1998 PatternsToMatch.
1999 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
2000 SrcPattern, DstPattern, TheInst.getImpResults(),
2001 Instr->getValueAsInt("AddedComplexity")));
2002 }
2003}
2004
Dan Gohmanee4fa192008-04-03 00:02:49 +00002005
2006void CodeGenDAGPatterns::InferInstructionFlags() {
2007 std::map<std::string, CodeGenInstruction> &InstrDescs =
2008 Target.getInstructions();
2009 for (std::map<std::string, CodeGenInstruction>::iterator
2010 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2011 CodeGenInstruction &InstInfo = II->second;
2012 // Determine properties of the instruction from its pattern.
2013 bool MayStore, MayLoad, HasSideEffects;
2014 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2015 InstInfo.mayStore = MayStore;
2016 InstInfo.mayLoad = MayLoad;
2017 InstInfo.hasSideEffects = HasSideEffects;
2018 }
2019}
2020
Chris Lattnerfe718932008-01-06 01:10:31 +00002021void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002022 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2023
2024 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2025 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2026 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2027 Record *Operator = OpDef->getDef();
2028 TreePattern *Pattern;
2029 if (Operator->getName() != "parallel")
2030 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2031 else {
2032 std::vector<Init*> Values;
2033 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
2034 Values.push_back(Tree->getArg(j));
2035 ListInit *LI = new ListInit(Values);
2036 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2037 }
2038
2039 // Inline pattern fragments into it.
2040 Pattern->InlinePatternFragments();
2041
2042 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2043 if (LI->getSize() == 0) continue; // no pattern.
2044
2045 // Parse the instruction.
2046 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2047
2048 // Inline pattern fragments into it.
2049 Result->InlinePatternFragments();
2050
2051 if (Result->getNumTrees() != 1)
2052 Result->error("Cannot handle instructions producing instructions "
2053 "with temporaries yet!");
2054
2055 bool IterateInference;
2056 bool InferredAllPatternTypes, InferredAllResultTypes;
2057 do {
2058 // Infer as many types as possible. If we cannot infer all of them, we
2059 // can never do anything with this pattern: report it to the user.
2060 InferredAllPatternTypes = Pattern->InferAllTypes();
2061
2062 // Infer as many types as possible. If we cannot infer all of them, we
2063 // can never do anything with this pattern: report it to the user.
2064 InferredAllResultTypes = Result->InferAllTypes();
2065
2066 // Apply the type of the result to the source pattern. This helps us
2067 // resolve cases where the input type is known to be a pointer type (which
2068 // is considered resolved), but the result knows it needs to be 32- or
2069 // 64-bits. Infer the other way for good measure.
2070 IterateInference = Pattern->getTree(0)->
2071 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2072 IterateInference |= Result->getTree(0)->
2073 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2074 } while (IterateInference);
2075
2076 // Verify that we inferred enough types that we can do something with the
2077 // pattern and result. If these fire the user has to add type casts.
2078 if (!InferredAllPatternTypes)
2079 Pattern->error("Could not infer all types in pattern!");
2080 if (!InferredAllResultTypes)
2081 Result->error("Could not infer all types in pattern result!");
2082
2083 // Validate that the input pattern is correct.
2084 std::map<std::string, TreePatternNode*> InstInputs;
2085 std::map<std::string, TreePatternNode*> InstResults;
2086 std::vector<Record*> InstImpInputs;
2087 std::vector<Record*> InstImpResults;
2088 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2089 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2090 InstInputs, InstResults,
2091 InstImpInputs, InstImpResults);
2092
2093 // Promote the xform function to be an explicit node if set.
2094 TreePatternNode *DstPattern = Result->getOnlyTree();
2095 std::vector<TreePatternNode*> ResultNodeOperands;
2096 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2097 TreePatternNode *OpNode = DstPattern->getChild(ii);
2098 if (Record *Xform = OpNode->getTransformFn()) {
2099 OpNode->setTransformFn(0);
2100 std::vector<TreePatternNode*> Children;
2101 Children.push_back(OpNode);
2102 OpNode = new TreePatternNode(Xform, Children);
2103 }
2104 ResultNodeOperands.push_back(OpNode);
2105 }
2106 DstPattern = Result->getOnlyTree();
2107 if (!DstPattern->isLeaf())
2108 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2109 ResultNodeOperands);
2110 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2111 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2112 Temp.InferAllTypes();
2113
2114 std::string Reason;
2115 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2116 Pattern->error("Pattern can never match: " + Reason);
2117
2118 PatternsToMatch.
2119 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2120 Pattern->getTree(0),
2121 Temp.getOnlyTree(), InstImpResults,
2122 Patterns[i]->getValueAsInt("AddedComplexity")));
2123 }
2124}
2125
2126/// CombineChildVariants - Given a bunch of permutations of each child of the
2127/// 'operator' node, put them together in all possible ways.
2128static void CombineChildVariants(TreePatternNode *Orig,
2129 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2130 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002131 CodeGenDAGPatterns &CDP,
2132 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002133 // Make sure that each operand has at least one variant to choose from.
2134 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2135 if (ChildVariants[i].empty())
2136 return;
2137
2138 // The end result is an all-pairs construction of the resultant pattern.
2139 std::vector<unsigned> Idxs;
2140 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002141 bool NotDone;
2142 do {
2143#ifndef NDEBUG
2144 if (DebugFlag && !Idxs.empty()) {
2145 cerr << Orig->getOperator()->getName() << ": Idxs = [ ";
2146 for (unsigned i = 0; i < Idxs.size(); ++i) {
2147 cerr << Idxs[i] << " ";
2148 }
2149 cerr << "]\n";
2150 }
2151#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002152 // Create the variant and add it to the output list.
2153 std::vector<TreePatternNode*> NewChildren;
2154 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2155 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2156 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2157
2158 // Copy over properties.
2159 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002160 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002161 R->setTransformFn(Orig->getTransformFn());
2162 R->setTypes(Orig->getExtTypes());
2163
Scott Michel327d0652008-03-05 17:49:05 +00002164 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002165 std::string ErrString;
2166 if (!R->canPatternMatch(ErrString, CDP)) {
2167 delete R;
2168 } else {
2169 bool AlreadyExists = false;
2170
2171 // Scan to see if this pattern has already been emitted. We can get
2172 // duplication due to things like commuting:
2173 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2174 // which are the same pattern. Ignore the dups.
2175 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002176 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002177 AlreadyExists = true;
2178 break;
2179 }
2180
2181 if (AlreadyExists)
2182 delete R;
2183 else
2184 OutVariants.push_back(R);
2185 }
2186
Scott Michel327d0652008-03-05 17:49:05 +00002187 // Increment indices to the next permutation by incrementing the
2188 // indicies from last index backward, e.g., generate the sequence
2189 // [0, 0], [0, 1], [1, 0], [1, 1].
2190 int IdxsIdx;
2191 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2192 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2193 Idxs[IdxsIdx] = 0;
2194 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002195 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002196 }
Scott Michel327d0652008-03-05 17:49:05 +00002197 NotDone = (IdxsIdx >= 0);
2198 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002199}
2200
2201/// CombineChildVariants - A helper function for binary operators.
2202///
2203static void CombineChildVariants(TreePatternNode *Orig,
2204 const std::vector<TreePatternNode*> &LHS,
2205 const std::vector<TreePatternNode*> &RHS,
2206 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002207 CodeGenDAGPatterns &CDP,
2208 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002209 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2210 ChildVariants.push_back(LHS);
2211 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002212 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002213}
2214
2215
2216static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2217 std::vector<TreePatternNode *> &Children) {
2218 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2219 Record *Operator = N->getOperator();
2220
2221 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002222 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002223 N->getTransformFn()) {
2224 Children.push_back(N);
2225 return;
2226 }
2227
2228 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2229 Children.push_back(N->getChild(0));
2230 else
2231 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2232
2233 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2234 Children.push_back(N->getChild(1));
2235 else
2236 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2237}
2238
2239/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2240/// the (potentially recursive) pattern by using algebraic laws.
2241///
2242static void GenerateVariantsOf(TreePatternNode *N,
2243 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002244 CodeGenDAGPatterns &CDP,
2245 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002246 // We cannot permute leaves.
2247 if (N->isLeaf()) {
2248 OutVariants.push_back(N);
2249 return;
2250 }
2251
2252 // Look up interesting info about the node.
2253 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2254
2255 // If this node is associative, reassociate.
2256 if (NodeInfo.hasProperty(SDNPAssociative)) {
2257 // Reassociate by pulling together all of the linked operators
2258 std::vector<TreePatternNode*> MaximalChildren;
2259 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2260
2261 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2262 // permutations.
2263 if (MaximalChildren.size() == 3) {
2264 // Find the variants of all of our maximal children.
2265 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002266 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2267 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2268 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002269
2270 // There are only two ways we can permute the tree:
2271 // (A op B) op C and A op (B op C)
2272 // Within these forms, we can also permute A/B/C.
2273
2274 // Generate legal pair permutations of A/B/C.
2275 std::vector<TreePatternNode*> ABVariants;
2276 std::vector<TreePatternNode*> BAVariants;
2277 std::vector<TreePatternNode*> ACVariants;
2278 std::vector<TreePatternNode*> CAVariants;
2279 std::vector<TreePatternNode*> BCVariants;
2280 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002281 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2282 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2283 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2284 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2285 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2286 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002287
2288 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002289 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2290 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2291 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2292 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2293 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2294 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002295
2296 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002297 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2298 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2299 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2300 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2301 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2302 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002303 return;
2304 }
2305 }
2306
2307 // Compute permutations of all children.
2308 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2309 ChildVariants.resize(N->getNumChildren());
2310 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002311 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002312
2313 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002314 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002315
2316 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002317 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2318 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2319 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2320 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002321 // Don't count children which are actually register references.
2322 unsigned NC = 0;
2323 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2324 TreePatternNode *Child = N->getChild(i);
2325 if (Child->isLeaf())
2326 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2327 Record *RR = DI->getDef();
2328 if (RR->isSubClassOf("Register"))
2329 continue;
2330 }
2331 NC++;
2332 }
2333 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002334 if (isCommIntrinsic) {
2335 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2336 // operands are the commutative operands, and there might be more operands
2337 // after those.
2338 assert(NC >= 3 &&
2339 "Commutative intrinsic should have at least 3 childrean!");
2340 std::vector<std::vector<TreePatternNode*> > Variants;
2341 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2342 Variants.push_back(ChildVariants[2]);
2343 Variants.push_back(ChildVariants[1]);
2344 for (unsigned i = 3; i != NC; ++i)
2345 Variants.push_back(ChildVariants[i]);
2346 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2347 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002348 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002349 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002350 }
2351}
2352
2353
2354// GenerateVariants - Generate variants. For example, commutative patterns can
2355// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002356void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002357 DOUT << "Generating instruction variants.\n";
2358
2359 // Loop over all of the patterns we've collected, checking to see if we can
2360 // generate variants of the instruction, through the exploitation of
2361 // identities. This permits the target to provide agressive matching without
2362 // the .td file having to contain tons of variants of instructions.
2363 //
2364 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2365 // intentionally do not reconsider these. Any variants of added patterns have
2366 // already been added.
2367 //
2368 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002369 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002370 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002371 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2372 DOUT << "Dependent/multiply used variables: ";
2373 DEBUG(DumpDepVars(DepVars));
2374 DOUT << "\n";
2375 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002376
2377 assert(!Variants.empty() && "Must create at least original variant!");
2378 Variants.erase(Variants.begin()); // Remove the original pattern.
2379
2380 if (Variants.empty()) // No variants for this pattern.
2381 continue;
2382
2383 DOUT << "FOUND VARIANTS OF: ";
2384 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2385 DOUT << "\n";
2386
2387 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2388 TreePatternNode *Variant = Variants[v];
2389
2390 DOUT << " VAR#" << v << ": ";
2391 DEBUG(Variant->dump());
2392 DOUT << "\n";
2393
2394 // Scan to see if an instruction or explicit pattern already matches this.
2395 bool AlreadyExists = false;
2396 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2397 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002398 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002399 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2400 AlreadyExists = true;
2401 break;
2402 }
2403 }
2404 // If we already have it, ignore the variant.
2405 if (AlreadyExists) continue;
2406
2407 // Otherwise, add it to the list of patterns we have.
2408 PatternsToMatch.
2409 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2410 Variant, PatternsToMatch[i].getDstPattern(),
2411 PatternsToMatch[i].getDstRegs(),
2412 PatternsToMatch[i].getAddedComplexity()));
2413 }
2414
2415 DOUT << "\n";
2416 }
2417}
2418