blob: 1b388428b71246c541f847225ccba50652fcac87 [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"
Chris Lattner2cacec52010-03-15 06:00:16 +000018#include "llvm/ADT/STLExtras.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include "llvm/Support/Debug.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//===----------------------------------------------------------------------===//
Chris Lattner2cacec52010-03-15 06:00:16 +000025// EEVT::TypeSet Implementation
26//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +000027
Owen Anderson825b72b2009-08-11 20:47:22 +000028static inline bool isInteger(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000029 return EVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000030}
31
Owen Anderson825b72b2009-08-11 20:47:22 +000032static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000033 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000034}
35
Owen Anderson825b72b2009-08-11 20:47:22 +000036static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000037 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000038}
39
Chris Lattner2cacec52010-03-15 06:00:16 +000040EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
41 if (VT == MVT::iAny)
42 EnforceInteger(TP);
43 else if (VT == MVT::fAny)
44 EnforceFloatingPoint(TP);
45 else if (VT == MVT::vAny)
46 EnforceVector(TP);
47 else {
48 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
49 VT == MVT::iPTRAny) && "Not a concrete type!");
50 TypeVec.push_back(VT);
51 }
Chris Lattner6cefb772008-01-05 22:25:12 +000052}
53
Chris Lattner2cacec52010-03-15 06:00:16 +000054
55EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
56 assert(!VTList.empty() && "empty list?");
57 TypeVec.append(VTList.begin(), VTList.end());
58
59 if (!VTList.empty())
60 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
61 VTList[0] != MVT::fAny);
62
63 // Remove duplicates.
64 array_pod_sort(TypeVec.begin(), TypeVec.end());
65 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Chris Lattner6cefb772008-01-05 22:25:12 +000066}
67
Chris Lattner2cacec52010-03-15 06:00:16 +000068
69/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
70/// integer value type.
71bool EEVT::TypeSet::hasIntegerTypes() const {
72 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
73 if (isInteger(TypeVec[i]))
74 return true;
75 return false;
76}
77
78/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
79/// a floating point value type.
80bool EEVT::TypeSet::hasFloatingPointTypes() const {
81 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
82 if (isFloatingPoint(TypeVec[i]))
83 return true;
84 return false;
85}
86
87/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
88/// value type.
89bool EEVT::TypeSet::hasVectorTypes() const {
90 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
91 if (isVector(TypeVec[i]))
92 return true;
93 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +000094}
Bob Wilson61fc4cf2009-08-11 01:14:02 +000095
Chris Lattner2cacec52010-03-15 06:00:16 +000096
97std::string EEVT::TypeSet::getName() const {
Chris Lattneraac5b5b2010-03-19 01:14:27 +000098 if (TypeVec.empty()) return "<empty>";
Chris Lattner2cacec52010-03-15 06:00:16 +000099
100 std::string Result;
101
102 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
103 std::string VTName = llvm::getEnumName(TypeVec[i]);
104 // Strip off MVT:: prefix if present.
105 if (VTName.substr(0,5) == "MVT::")
106 VTName = VTName.substr(5);
107 if (i) Result += ':';
108 Result += VTName;
109 }
110
111 if (TypeVec.size() == 1)
112 return Result;
113 return "{" + Result + "}";
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000114}
Chris Lattner2cacec52010-03-15 06:00:16 +0000115
116/// MergeInTypeInfo - This merges in type information from the specified
117/// argument. If 'this' changes, it returns true. If the two types are
118/// contradictory (e.g. merge f32 into i32) then this throws an exception.
119bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
120 if (InVT.isCompletelyUnknown() || *this == InVT)
121 return false;
122
123 if (isCompletelyUnknown()) {
124 *this = InVT;
125 return true;
126 }
127
128 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
129
130 // Handle the abstract cases, seeing if we can resolve them better.
131 switch (TypeVec[0]) {
132 default: break;
133 case MVT::iPTR:
134 case MVT::iPTRAny:
135 if (InVT.hasIntegerTypes()) {
136 EEVT::TypeSet InCopy(InVT);
137 InCopy.EnforceInteger(TP);
138 InCopy.EnforceScalar(TP);
139
140 if (InCopy.isConcrete()) {
141 // If the RHS has one integer type, upgrade iPTR to i32.
142 TypeVec[0] = InVT.TypeVec[0];
143 return true;
144 }
145
146 // If the input has multiple scalar integers, this doesn't add any info.
147 if (!InCopy.isCompletelyUnknown())
148 return false;
149 }
150 break;
151 }
152
153 // If the input constraint is iAny/iPTR and this is an integer type list,
154 // remove non-integer types from the list.
155 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
156 hasIntegerTypes()) {
157 bool MadeChange = EnforceInteger(TP);
158
159 // If we're merging in iPTR/iPTRAny and the node currently has a list of
160 // multiple different integer types, replace them with a single iPTR.
161 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
162 TypeVec.size() != 1) {
163 TypeVec.resize(1);
164 TypeVec[0] = InVT.TypeVec[0];
165 MadeChange = true;
166 }
167
168 return MadeChange;
169 }
170
171 // If this is a type list and the RHS is a typelist as well, eliminate entries
172 // from this list that aren't in the other one.
173 bool MadeChange = false;
174 TypeSet InputSet(*this);
175
176 for (unsigned i = 0; i != TypeVec.size(); ++i) {
177 bool InInVT = false;
178 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
179 if (TypeVec[i] == InVT.TypeVec[j]) {
180 InInVT = true;
181 break;
182 }
183
184 if (InInVT) continue;
185 TypeVec.erase(TypeVec.begin()+i--);
186 MadeChange = true;
187 }
188
189 // If we removed all of our types, we have a type contradiction.
190 if (!TypeVec.empty())
191 return MadeChange;
192
193 // FIXME: Really want an SMLoc here!
194 TP.error("Type inference contradiction found, merging '" +
195 InVT.getName() + "' into '" + InputSet.getName() + "'");
196 return true; // unreachable
197}
198
199/// EnforceInteger - Remove all non-integer types from this set.
200bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
201 TypeSet InputSet(*this);
202 bool MadeChange = false;
203
204 // If we know nothing, then get the full set.
205 if (TypeVec.empty()) {
206 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
207 MadeChange = true;
208 }
209
210 if (!hasFloatingPointTypes())
211 return MadeChange;
212
213 // Filter out all the fp types.
214 for (unsigned i = 0; i != TypeVec.size(); ++i)
215 if (isFloatingPoint(TypeVec[i]))
216 TypeVec.erase(TypeVec.begin()+i--);
217
218 if (TypeVec.empty())
219 TP.error("Type inference contradiction found, '" +
220 InputSet.getName() + "' needs to be integer");
221 return MadeChange;
222}
223
224/// EnforceFloatingPoint - Remove all integer types from this set.
225bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
226 TypeSet InputSet(*this);
227 bool MadeChange = false;
228
229 // If we know nothing, then get the full set.
230 if (TypeVec.empty()) {
231 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
232 MadeChange = true;
233 }
234
235 if (!hasIntegerTypes())
236 return MadeChange;
237
238 // Filter out all the fp types.
239 for (unsigned i = 0; i != TypeVec.size(); ++i)
240 if (isInteger(TypeVec[i]))
241 TypeVec.erase(TypeVec.begin()+i--);
242
243 if (TypeVec.empty())
244 TP.error("Type inference contradiction found, '" +
245 InputSet.getName() + "' needs to be floating point");
246 return MadeChange;
247}
248
249/// EnforceScalar - Remove all vector types from this.
250bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
251 TypeSet InputSet(*this);
252 bool MadeChange = false;
253
254 // If we know nothing, then get the full set.
255 if (TypeVec.empty()) {
256 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
257 MadeChange = true;
258 }
259
260 if (!hasVectorTypes())
261 return MadeChange;
262
263 // Filter out all the vector types.
264 for (unsigned i = 0; i != TypeVec.size(); ++i)
265 if (isVector(TypeVec[i]))
266 TypeVec.erase(TypeVec.begin()+i--);
267
268 if (TypeVec.empty())
269 TP.error("Type inference contradiction found, '" +
270 InputSet.getName() + "' needs to be scalar");
271 return MadeChange;
272}
273
274/// EnforceVector - Remove all vector types from this.
275bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
276 TypeSet InputSet(*this);
277 bool MadeChange = false;
278
279 // If we know nothing, then get the full set.
280 if (TypeVec.empty()) {
281 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
282 MadeChange = true;
283 }
284
285 // Filter out all the scalar types.
286 for (unsigned i = 0; i != TypeVec.size(); ++i)
287 if (!isVector(TypeVec[i]))
288 TypeVec.erase(TypeVec.begin()+i--);
289
290 if (TypeVec.empty())
291 TP.error("Type inference contradiction found, '" +
292 InputSet.getName() + "' needs to be a vector");
293 return MadeChange;
294}
295
296
297/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
298/// this an other based on this information.
299bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
300 // Both operands must be integer or FP, but we don't care which.
301 bool MadeChange = false;
302
303 // This code does not currently handle nodes which have multiple types,
304 // where some types are integer, and some are fp. Assert that this is not
305 // the case.
306 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
307 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
308 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
309 // If one side is known to be integer or known to be FP but the other side has
310 // no information, get at least the type integrality info in there.
311 if (hasIntegerTypes())
312 MadeChange |= Other.EnforceInteger(TP);
313 else if (hasFloatingPointTypes())
314 MadeChange |= Other.EnforceFloatingPoint(TP);
315 if (Other.hasIntegerTypes())
316 MadeChange |= EnforceInteger(TP);
317 else if (Other.hasFloatingPointTypes())
318 MadeChange |= EnforceFloatingPoint(TP);
319
320 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
321 "Should have a type list now");
322
323 // If one contains vectors but the other doesn't pull vectors out.
324 if (!hasVectorTypes() && Other.hasVectorTypes())
325 MadeChange |= Other.EnforceScalar(TP);
326 if (hasVectorTypes() && !Other.hasVectorTypes())
327 MadeChange |= EnforceScalar(TP);
328
329 // FIXME: This is a bone-headed way to do this.
330
331 // Get the set of legal VTs and filter it based on the known integrality.
332 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
333 TypeSet LegalVTs = CGT.getLegalValueTypes();
334
335 // TODO: If one or the other side is known to be a specific VT, we could prune
336 // LegalVTs.
337 if (hasIntegerTypes())
338 LegalVTs.EnforceInteger(TP);
339 else if (hasFloatingPointTypes())
340 LegalVTs.EnforceFloatingPoint(TP);
341 else
342 return MadeChange;
343
344 switch (LegalVTs.TypeVec.size()) {
345 case 0: assert(0 && "No legal VTs?");
346 default: // Too many VT's to pick from.
347 // TODO: If the biggest type in LegalVTs is in this set, we could remove it.
348 // If one or the other side is known to be a specific VT, we could prune
349 // LegalVTs.
350 return MadeChange;
351 case 1:
352 // Only one VT of this flavor. Cannot ever satisfy the constraints.
353 return MergeInTypeInfo(MVT::Other, TP); // throw
354 case 2:
355 // If we have exactly two possible types, the little operand must be the
356 // small one, the big operand should be the big one. This is common with
357 // float/double for example.
358 assert(LegalVTs.TypeVec[0] < LegalVTs.TypeVec[1] && "Should be sorted!");
359 MadeChange |= MergeInTypeInfo(LegalVTs.TypeVec[0], TP);
360 MadeChange |= Other.MergeInTypeInfo(LegalVTs.TypeVec[1], TP);
361 return MadeChange;
362 }
363}
364
365/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
366/// whose element is VT.
367bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
368 TreePattern &TP) {
369 TypeSet InputSet(*this);
370 bool MadeChange = false;
371
372 // If we know nothing, then get the full set.
373 if (TypeVec.empty()) {
374 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
375 MadeChange = true;
376 }
377
378 // Filter out all the non-vector types and types which don't have the right
379 // element type.
380 for (unsigned i = 0; i != TypeVec.size(); ++i)
381 if (!isVector(TypeVec[i]) ||
382 EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
383 TypeVec.erase(TypeVec.begin()+i--);
384 MadeChange = true;
385 }
386
387 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
388 TP.error("Type inference contradiction found, forcing '" +
389 InputSet.getName() + "' to have a vector element");
390 return MadeChange;
391}
392
393//===----------------------------------------------------------------------===//
394// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000395
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000396bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
397 return LHS->getID() < RHS->getID();
398}
Scott Michel327d0652008-03-05 17:49:05 +0000399
400/// Dependent variable map for CodeGenDAGPattern variant generation
401typedef std::map<std::string, int> DepVarMap;
402
403/// Const iterator shorthand for DepVarMap
404typedef DepVarMap::const_iterator DepVarMap_citer;
405
406namespace {
407void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
408 if (N->isLeaf()) {
409 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
410 DepMap[N->getName()]++;
411 }
412 } else {
413 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
414 FindDepVarsOf(N->getChild(i), DepMap);
415 }
416}
417
418//! Find dependent variables within child patterns
419/*!
420 */
421void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
422 DepVarMap depcounts;
423 FindDepVarsOf(N, depcounts);
424 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
425 if (i->second > 1) { // std::pair<std::string, int>
426 DepVars.insert(i->first);
427 }
428 }
429}
430
431//! Dump the dependent variable set:
432void DumpDepVars(MultipleUseVarSet &DepVars) {
433 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000434 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000435 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000436 DEBUG(errs() << "[ ");
Scott Michel327d0652008-03-05 17:49:05 +0000437 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
438 i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000439 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000440 }
Chris Lattner569f1212009-08-23 04:44:11 +0000441 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000442 }
443}
444}
445
Chris Lattner6cefb772008-01-05 22:25:12 +0000446//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000447// PatternToMatch implementation
448//
449
450/// getPredicateCheck - Return a single string containing all of this
451/// pattern's predicates concatenated with "&&" operators.
452///
453std::string PatternToMatch::getPredicateCheck() const {
454 std::string PredicateCheck;
455 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
456 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
457 Record *Def = Pred->getDef();
458 if (!Def->isSubClassOf("Predicate")) {
459#ifndef NDEBUG
460 Def->dump();
461#endif
462 assert(0 && "Unknown predicate type!");
463 }
464 if (!PredicateCheck.empty())
465 PredicateCheck += " && ";
466 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
467 }
468 }
469
470 return PredicateCheck;
471}
472
473//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000474// SDTypeConstraint implementation
475//
476
477SDTypeConstraint::SDTypeConstraint(Record *R) {
478 OperandNo = R->getValueAsInt("OperandNum");
479
480 if (R->isSubClassOf("SDTCisVT")) {
481 ConstraintType = SDTCisVT;
482 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
483 } else if (R->isSubClassOf("SDTCisPtrTy")) {
484 ConstraintType = SDTCisPtrTy;
485 } else if (R->isSubClassOf("SDTCisInt")) {
486 ConstraintType = SDTCisInt;
487 } else if (R->isSubClassOf("SDTCisFP")) {
488 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000489 } else if (R->isSubClassOf("SDTCisVec")) {
490 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000491 } else if (R->isSubClassOf("SDTCisSameAs")) {
492 ConstraintType = SDTCisSameAs;
493 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
494 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
495 ConstraintType = SDTCisVTSmallerThanOp;
496 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
497 R->getValueAsInt("OtherOperandNum");
498 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
499 ConstraintType = SDTCisOpSmallerThanOp;
500 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
501 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000502 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
503 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000504 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000505 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000506 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000507 exit(1);
508 }
509}
510
511/// getOperandNum - Return the node corresponding to operand #OpNo in tree
512/// N, which has NumResults results.
513TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
514 TreePatternNode *N,
515 unsigned NumResults) const {
516 assert(NumResults <= 1 &&
517 "We only work with nodes with zero or one result so far!");
518
519 if (OpNo >= (NumResults + N->getNumChildren())) {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000520 errs() << "Invalid operand number " << OpNo << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000521 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000522 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000523 exit(1);
524 }
525
526 if (OpNo < NumResults)
527 return N; // FIXME: need value #
528 else
529 return N->getChild(OpNo-NumResults);
530}
531
532/// ApplyTypeConstraint - Given a node in a pattern, apply this type
533/// constraint to the nodes operands. This returns true if it makes a
534/// change, false otherwise. If a type contradiction is found, throw an
535/// exception.
536bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
537 const SDNodeInfo &NodeInfo,
538 TreePattern &TP) const {
539 unsigned NumResults = NodeInfo.getNumResults();
540 assert(NumResults <= 1 &&
541 "We only work with nodes with zero or one result so far!");
542
543 // Check that the number of operands is sane. Negative operands -> varargs.
544 if (NodeInfo.getNumOperands() >= 0) {
545 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
546 TP.error(N->getOperator()->getName() + " node requires exactly " +
547 itostr(NodeInfo.getNumOperands()) + " operands!");
548 }
549
Chris Lattner6cefb772008-01-05 22:25:12 +0000550 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
551
552 switch (ConstraintType) {
553 default: assert(0 && "Unknown constraint type!");
554 case SDTCisVT:
555 // Operand must be a particular type.
556 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000557 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000558 // Operand must be same as target pointer type.
Owen Anderson825b72b2009-08-11 20:47:22 +0000559 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000560 case SDTCisInt:
561 // Require it to be one of the legal integer VTs.
562 return NodeToApply->getExtType().EnforceInteger(TP);
563 case SDTCisFP:
564 // Require it to be one of the legal fp VTs.
565 return NodeToApply->getExtType().EnforceFloatingPoint(TP);
566 case SDTCisVec:
567 // Require it to be one of the legal vector VTs.
568 return NodeToApply->getExtType().EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000569 case SDTCisSameAs: {
570 TreePatternNode *OtherNode =
571 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Chris Lattner2cacec52010-03-15 06:00:16 +0000572 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
573 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000574 }
575 case SDTCisVTSmallerThanOp: {
576 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
577 // have an integer type that is smaller than the VT.
578 if (!NodeToApply->isLeaf() ||
579 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
580 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
581 ->isSubClassOf("ValueType"))
582 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000583 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000584 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Duncan Sands83ec4b62008-06-06 12:08:01 +0000585 if (!isInteger(VT))
Chris Lattner6cefb772008-01-05 22:25:12 +0000586 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
587
588 TreePatternNode *OtherNode =
589 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
590
591 // It must be integer.
Chris Lattner2cacec52010-03-15 06:00:16 +0000592 bool MadeChange = OtherNode->getExtType().EnforceInteger(TP);
593
594 // This doesn't try to enforce any information on the OtherNode, it just
595 // validates it when information is determined.
596 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
Owen Anderson825b72b2009-08-11 20:47:22 +0000597 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
Bill Wendling7529ece2009-12-25 13:35:40 +0000598 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +0000599 }
600 case SDTCisOpSmallerThanOp: {
601 TreePatternNode *BigOperand =
602 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
Chris Lattner2cacec52010-03-15 06:00:16 +0000603 return NodeToApply->getExtType().
604 EnforceSmallerThan(BigOperand->getExtType(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000605 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000606 case SDTCisEltOfVec: {
Chris Lattner2cacec52010-03-15 06:00:16 +0000607 TreePatternNode *VecOperand =
608 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NumResults);
609 if (VecOperand->hasTypeSet()) {
610 if (!isVector(VecOperand->getType()))
Nate Begemanb5af3342008-02-09 01:37:05 +0000611 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Chris Lattner2cacec52010-03-15 06:00:16 +0000612 EVT IVT = VecOperand->getType();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000613 IVT = IVT.getVectorElementType();
Owen Anderson825b72b2009-08-11 20:47:22 +0000614 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000615 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000616
617 if (NodeToApply->hasTypeSet() && VecOperand->getExtType().hasVectorTypes()){
618 // Filter vector types out of VecOperand that don't have the right element
619 // type.
620 return VecOperand->getExtType().
621 EnforceVectorEltTypeIs(NodeToApply->getType(), TP);
622 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000623 return false;
624 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000625 }
626 return false;
627}
628
629//===----------------------------------------------------------------------===//
630// SDNodeInfo implementation
631//
632SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
633 EnumName = R->getValueAsString("Opcode");
634 SDClassName = R->getValueAsString("SDClass");
635 Record *TypeProfile = R->getValueAsDef("TypeProfile");
636 NumResults = TypeProfile->getValueAsInt("NumResults");
637 NumOperands = TypeProfile->getValueAsInt("NumOperands");
638
639 // Parse the properties.
640 Properties = 0;
641 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
642 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
643 if (PropList[i]->getName() == "SDNPCommutative") {
644 Properties |= 1 << SDNPCommutative;
645 } else if (PropList[i]->getName() == "SDNPAssociative") {
646 Properties |= 1 << SDNPAssociative;
647 } else if (PropList[i]->getName() == "SDNPHasChain") {
648 Properties |= 1 << SDNPHasChain;
649 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen874ae252009-06-02 03:12:52 +0000650 Properties |= 1 << SDNPOutFlag;
Chris Lattner6cefb772008-01-05 22:25:12 +0000651 } else if (PropList[i]->getName() == "SDNPInFlag") {
652 Properties |= 1 << SDNPInFlag;
653 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
654 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000655 } else if (PropList[i]->getName() == "SDNPMayStore") {
656 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000657 } else if (PropList[i]->getName() == "SDNPMayLoad") {
658 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000659 } else if (PropList[i]->getName() == "SDNPSideEffect") {
660 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000661 } else if (PropList[i]->getName() == "SDNPMemOperand") {
662 Properties |= 1 << SDNPMemOperand;
Chris Lattner6cefb772008-01-05 22:25:12 +0000663 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000664 errs() << "Unknown SD Node property '" << PropList[i]->getName()
665 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000666 exit(1);
667 }
668 }
669
670
671 // Parse the type constraints.
672 std::vector<Record*> ConstraintList =
673 TypeProfile->getValueAsListOfDefs("Constraints");
674 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
675}
676
Chris Lattner22579812010-02-28 00:22:30 +0000677/// getKnownType - If the type constraints on this node imply a fixed type
678/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000679/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
680MVT::SimpleValueType SDNodeInfo::getKnownType() const {
Chris Lattner22579812010-02-28 00:22:30 +0000681 unsigned NumResults = getNumResults();
682 assert(NumResults <= 1 &&
683 "We only work with nodes with zero or one result so far!");
684
685 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
686 // Make sure that this applies to the correct node result.
687 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
688 continue;
689
690 switch (TypeConstraints[i].ConstraintType) {
691 default: break;
692 case SDTypeConstraint::SDTCisVT:
693 return TypeConstraints[i].x.SDTCisVT_Info.VT;
694 case SDTypeConstraint::SDTCisPtrTy:
695 return MVT::iPTR;
696 }
697 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000698 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000699}
700
Chris Lattner6cefb772008-01-05 22:25:12 +0000701//===----------------------------------------------------------------------===//
702// TreePatternNode implementation
703//
704
705TreePatternNode::~TreePatternNode() {
706#if 0 // FIXME: implement refcounted tree nodes!
707 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
708 delete getChild(i);
709#endif
710}
711
Chris Lattnerba1cff42010-02-23 07:50:58 +0000712
Chris Lattner6cefb772008-01-05 22:25:12 +0000713
Daniel Dunbar1a551802009-07-03 00:10:29 +0000714void TreePatternNode::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000715 if (isLeaf()) {
716 OS << *getLeafValue();
717 } else {
Chris Lattnerba1cff42010-02-23 07:50:58 +0000718 OS << '(' << getOperator()->getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000719 }
720
Chris Lattner2cacec52010-03-15 06:00:16 +0000721 if (!isTypeCompletelyUnknown())
722 OS << ':' << getExtType().getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000723
724 if (!isLeaf()) {
725 if (getNumChildren() != 0) {
726 OS << " ";
727 getChild(0)->print(OS);
728 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
729 OS << ", ";
730 getChild(i)->print(OS);
731 }
732 }
733 OS << ")";
734 }
735
Dan Gohman0540e172008-10-15 06:17:21 +0000736 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
737 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000738 if (TransformFn)
739 OS << "<<X:" << TransformFn->getName() << ">>";
740 if (!getName().empty())
741 OS << ":$" << getName();
742
743}
744void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000745 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000746}
747
Scott Michel327d0652008-03-05 17:49:05 +0000748/// isIsomorphicTo - Return true if this node is recursively
749/// isomorphic to the specified node. For this comparison, the node's
750/// entire state is considered. The assigned name is ignored, since
751/// nodes with differing names are considered isomorphic. However, if
752/// the assigned name is present in the dependent variable set, then
753/// the assigned name is considered significant and the node is
754/// isomorphic if the names match.
755bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
756 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000757 if (N == this) return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000758 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000759 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000760 getTransformFn() != N->getTransformFn())
761 return false;
762
763 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000764 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
765 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000766 return ((DI->getDef() == NDI->getDef())
767 && (DepVars.find(getName()) == DepVars.end()
768 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000769 }
770 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000771 return getLeafValue() == N->getLeafValue();
772 }
773
774 if (N->getOperator() != getOperator() ||
775 N->getNumChildren() != getNumChildren()) return false;
776 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000777 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000778 return false;
779 return true;
780}
781
782/// clone - Make a copy of this tree and all of its children.
783///
784TreePatternNode *TreePatternNode::clone() const {
785 TreePatternNode *New;
786 if (isLeaf()) {
787 New = new TreePatternNode(getLeafValue());
788 } else {
789 std::vector<TreePatternNode*> CChildren;
790 CChildren.reserve(Children.size());
791 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
792 CChildren.push_back(getChild(i)->clone());
793 New = new TreePatternNode(getOperator(), CChildren);
794 }
795 New->setName(getName());
Chris Lattner2cacec52010-03-15 06:00:16 +0000796 New->setType(getExtType());
Dan Gohman0540e172008-10-15 06:17:21 +0000797 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000798 New->setTransformFn(getTransformFn());
799 return New;
800}
801
Chris Lattner47661322010-02-14 22:22:58 +0000802/// RemoveAllTypes - Recursively strip all the types of this tree.
803void TreePatternNode::RemoveAllTypes() {
Chris Lattner2cacec52010-03-15 06:00:16 +0000804 setType(EEVT::TypeSet()); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +0000805 if (isLeaf()) return;
806 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
807 getChild(i)->RemoveAllTypes();
808}
809
810
Chris Lattner6cefb772008-01-05 22:25:12 +0000811/// SubstituteFormalArguments - Replace the formal arguments in this tree
812/// with actual values specified by ArgMap.
813void TreePatternNode::
814SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
815 if (isLeaf()) return;
816
817 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
818 TreePatternNode *Child = getChild(i);
819 if (Child->isLeaf()) {
820 Init *Val = Child->getLeafValue();
821 if (dynamic_cast<DefInit*>(Val) &&
822 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
823 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000824 TreePatternNode *NewChild = ArgMap[Child->getName()];
825 assert(NewChild && "Couldn't find formal argument!");
826 assert((Child->getPredicateFns().empty() ||
827 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
828 "Non-empty child predicate clobbered!");
829 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000830 }
831 } else {
832 getChild(i)->SubstituteFormalArguments(ArgMap);
833 }
834 }
835}
836
837
838/// InlinePatternFragments - If this pattern refers to any pattern
839/// fragments, inline them into place, giving us a pattern without any
840/// PatFrag references.
841TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
842 if (isLeaf()) return this; // nothing to do.
843 Record *Op = getOperator();
844
845 if (!Op->isSubClassOf("PatFrag")) {
846 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000847 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
848 TreePatternNode *Child = getChild(i);
849 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
850
851 assert((Child->getPredicateFns().empty() ||
852 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
853 "Non-empty child predicate clobbered!");
854
855 setChild(i, NewChild);
856 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000857 return this;
858 }
859
860 // Otherwise, we found a reference to a fragment. First, look up its
861 // TreePattern record.
862 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
863
864 // Verify that we are passing the right number of operands.
865 if (Frag->getNumArgs() != Children.size())
866 TP.error("'" + Op->getName() + "' fragment requires " +
867 utostr(Frag->getNumArgs()) + " operands!");
868
869 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
870
Dan Gohman0540e172008-10-15 06:17:21 +0000871 std::string Code = Op->getValueAsCode("Predicate");
872 if (!Code.empty())
873 FragTree->addPredicateFn("Predicate_"+Op->getName());
874
Chris Lattner6cefb772008-01-05 22:25:12 +0000875 // Resolve formal arguments to their actual value.
876 if (Frag->getNumArgs()) {
877 // Compute the map of formal to actual arguments.
878 std::map<std::string, TreePatternNode*> ArgMap;
879 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
880 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
881
882 FragTree->SubstituteFormalArguments(ArgMap);
883 }
884
885 FragTree->setName(getName());
Chris Lattner2cacec52010-03-15 06:00:16 +0000886 FragTree->UpdateNodeType(getExtType(), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000887
888 // Transfer in the old predicates.
889 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
890 FragTree->addPredicateFn(getPredicateFns()[i]);
891
Chris Lattner6cefb772008-01-05 22:25:12 +0000892 // Get a new copy of this fragment to stitch into here.
893 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000894
895 // The fragment we inlined could have recursive inlining that is needed. See
896 // if there are any pattern fragments in it and inline them as needed.
897 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000898}
899
900/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000901/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +0000902/// references from the register file information, for example.
903///
Chris Lattner2cacec52010-03-15 06:00:16 +0000904static EEVT::TypeSet getImplicitType(Record *R, bool NotRegisters,
905 TreePattern &TP) {
906 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +0000907 if (R->isSubClassOf("RegisterClass")) {
908 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000909 return EEVT::TypeSet(); // Unknown.
910 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
911 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000912 } else if (R->isSubClassOf("PatFrag")) {
913 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +0000914 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +0000915 } else if (R->isSubClassOf("Register")) {
916 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000917 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +0000918 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +0000919 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6cefb772008-01-05 22:25:12 +0000920 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
921 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +0000922 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000923 } else if (R->isSubClassOf("ComplexPattern")) {
924 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000925 return EEVT::TypeSet(); // Unknown.
926 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
927 TP);
Chris Lattnera938ac62009-07-29 20:43:05 +0000928 } else if (R->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000929 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000930 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
931 R->getName() == "zero_reg") {
932 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +0000933 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +0000934 }
935
936 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +0000937 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000938}
939
Chris Lattnere67bde52008-01-06 05:36:50 +0000940
941/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
942/// CodeGenIntrinsic information for it, otherwise return a null pointer.
943const CodeGenIntrinsic *TreePatternNode::
944getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
945 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
946 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
947 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
948 return 0;
949
950 unsigned IID =
951 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
952 return &CDP.getIntrinsicInfo(IID);
953}
954
Chris Lattner47661322010-02-14 22:22:58 +0000955/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
956/// return the ComplexPattern information, otherwise return null.
957const ComplexPattern *
958TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
959 if (!isLeaf()) return 0;
960
961 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
962 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
963 return &CGP.getComplexPattern(DI->getDef());
964 return 0;
965}
966
967/// NodeHasProperty - Return true if this node has the specified property.
968bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +0000969 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +0000970 if (isLeaf()) {
971 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
972 return CP->hasProperty(Property);
973 return false;
974 }
975
976 Record *Operator = getOperator();
977 if (!Operator->isSubClassOf("SDNode")) return false;
978
979 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
980}
981
982
983
984
985/// TreeHasProperty - Return true if any node in this tree has the specified
986/// property.
987bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +0000988 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +0000989 if (NodeHasProperty(Property, CGP))
990 return true;
991 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
992 if (getChild(i)->TreeHasProperty(Property, CGP))
993 return true;
994 return false;
995}
996
Evan Cheng6bd95672008-06-16 20:29:38 +0000997/// isCommutativeIntrinsic - Return true if the node corresponds to a
998/// commutative intrinsic.
999bool
1000TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1001 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1002 return Int->isCommutative;
1003 return false;
1004}
1005
Chris Lattnere67bde52008-01-06 05:36:50 +00001006
Bob Wilson6c01ca92009-01-05 17:23:09 +00001007/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001008/// this node and its children in the tree. This returns true if it makes a
1009/// change, false otherwise. If a type contradiction is found, throw an
1010/// exception.
1011bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001012 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001013 if (isLeaf()) {
1014 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1015 // If it's a regclass or something else known, include the type.
1016 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner523f6a52010-02-14 21:10:15 +00001017 }
1018
1019 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001020 // Int inits are always integers. :)
Chris Lattner2cacec52010-03-15 06:00:16 +00001021 bool MadeChange = Type.EnforceInteger(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001022
Chris Lattner2cacec52010-03-15 06:00:16 +00001023 if (!hasTypeSet())
1024 return MadeChange;
1025
1026 MVT::SimpleValueType VT = getType();
1027 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1028 return MadeChange;
1029
1030 unsigned Size = EVT(VT).getSizeInBits();
1031 // Make sure that the value is representable for this type.
1032 if (Size >= 32) return MadeChange;
1033
1034 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1035 if (Val == II->getValue()) return MadeChange;
1036
1037 // If sign-extended doesn't fit, does it fit as unsigned?
1038 unsigned ValueMask;
1039 unsigned UnsignedVal;
1040 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1041 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001042
Chris Lattner2cacec52010-03-15 06:00:16 +00001043 if ((ValueMask & UnsignedVal) == UnsignedVal)
1044 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001045
Chris Lattner2cacec52010-03-15 06:00:16 +00001046 TP.error("Integer value '" + itostr(II->getValue())+
1047 "' is out of range for type '" + getEnumName(getType()) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001048 return MadeChange;
1049 }
1050 return false;
1051 }
1052
1053 // special handling for set, which isn't really an SDNode.
1054 if (getOperator()->getName() == "set") {
1055 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
1056 unsigned NC = getNumChildren();
1057 bool MadeChange = false;
1058 for (unsigned i = 0; i < NC-1; ++i) {
1059 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1060 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
1061
1062 // Types of operands must match.
Chris Lattner2cacec52010-03-15 06:00:16 +00001063 MadeChange |=getChild(i)->UpdateNodeType(getChild(NC-1)->getExtType(),TP);
1064 MadeChange |=getChild(NC-1)->UpdateNodeType(getChild(i)->getExtType(),TP);
1065 MadeChange |=UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001066 }
1067 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001068 }
1069
1070 if (getOperator()->getName() == "implicit" ||
1071 getOperator()->getName() == "parallel") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001072 bool MadeChange = false;
1073 for (unsigned i = 0; i < getNumChildren(); ++i)
1074 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Owen Anderson825b72b2009-08-11 20:47:22 +00001075 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001076 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001077 }
1078
1079 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001080 bool MadeChange = false;
1081 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1082 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner2cacec52010-03-15 06:00:16 +00001083
1084 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1085 // what type it gets, so if it didn't get a concrete type just give it the
1086 // first viable type from the reg class.
1087 if (!getChild(1)->hasTypeSet() &&
1088 !getChild(1)->getExtType().isCompletelyUnknown()) {
1089 MVT::SimpleValueType RCVT = getChild(1)->getExtType().getTypeList()[0];
1090 MadeChange |= getChild(1)->UpdateNodeType(RCVT, TP);
1091 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001092 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001093 }
1094
1095 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001096 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001097
Chris Lattner6cefb772008-01-05 22:25:12 +00001098 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001099 unsigned NumRetVTs = Int->IS.RetVTs.size();
1100 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001101
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001102 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1103 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
1104
1105 if (getNumChildren() != NumParamVTs + NumRetVTs)
Chris Lattnere67bde52008-01-06 05:36:50 +00001106 TP.error("Intrinsic '" + Int->Name + "' expects " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001107 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
1108 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001109
1110 // Apply type info to the intrinsic ID.
Owen Anderson825b72b2009-08-11 20:47:22 +00001111 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001112
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001113 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001114 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
Chris Lattner6cefb772008-01-05 22:25:12 +00001115 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
1116 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1117 }
1118 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001119 }
1120
1121 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001122 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1123
1124 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1125 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1126 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1127 // Branch, etc. do not produce results and top-level forms in instr pattern
1128 // must have void types.
1129 if (NI.getNumResults() == 0)
Owen Anderson825b72b2009-08-11 20:47:22 +00001130 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001131
Chris Lattner6cefb772008-01-05 22:25:12 +00001132 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001133 }
1134
1135 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001136 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001137 unsigned NumResults = Inst.getNumResults();
Chris Lattner6cefb772008-01-05 22:25:12 +00001138 assert(NumResults <= 1 &&
1139 "Only supports zero or one result instrs!");
1140
1141 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001142 CDP.getTargetInfo().getInstruction(getOperator());
Chris Lattner6c6ba362010-03-18 23:15:10 +00001143
1144 EEVT::TypeSet ResultType;
1145
Chris Lattner6cefb772008-01-05 22:25:12 +00001146 // Apply the result type to the node
Chris Lattner6c6ba362010-03-18 23:15:10 +00001147 if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
Chris Lattner6cefb772008-01-05 22:25:12 +00001148 Record *ResultNode = Inst.getResult(0);
1149
Chris Lattnera938ac62009-07-29 20:43:05 +00001150 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00001151 ResultType = EEVT::TypeSet(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001152 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001153 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001154 } else {
1155 assert(ResultNode->isSubClassOf("RegisterClass") &&
1156 "Operands should be register classes!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001157 const CodeGenRegisterClass &RC =
1158 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner6c6ba362010-03-18 23:15:10 +00001159 ResultType = RC.getValueTypes();
Chris Lattner6cefb772008-01-05 22:25:12 +00001160 }
Chris Lattner6c6ba362010-03-18 23:15:10 +00001161 } else if (!InstInfo.ImplicitDefs.empty()) {
1162 // If the instruction has implicit defs, the first one defines the result
1163 // type.
Chris Lattner6c6ba362010-03-18 23:15:10 +00001164 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
Chris Lattner92879532010-03-18 23:57:40 +00001165 assert(FirstImplicitDef->isSubClassOf("Register"));
Chris Lattner6c6ba362010-03-18 23:15:10 +00001166 const std::vector<MVT::SimpleValueType> &RegVTs =
1167 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
Chris Lattner92879532010-03-18 23:57:40 +00001168 if (RegVTs.size() == 1)
Chris Lattner6c6ba362010-03-18 23:15:10 +00001169 ResultType = EEVT::TypeSet(RegVTs);
Chris Lattner92879532010-03-18 23:57:40 +00001170 else
1171 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
Chris Lattner6c6ba362010-03-18 23:15:10 +00001172 } else {
1173 // Otherwise, the instruction produces no value result.
1174 // FIXME: Model "no result" different than "one result that is void"
1175 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001176 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001177
Chris Lattner6c6ba362010-03-18 23:15:10 +00001178 bool MadeChange = UpdateNodeType(ResultType, TP);
1179
Chris Lattner2cacec52010-03-15 06:00:16 +00001180 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1181 // be the same.
1182 if (getOperator()->getName() == "INSERT_SUBREG") {
1183 MadeChange |= UpdateNodeType(getChild(0)->getExtType(), TP);
1184 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1185 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001186
1187 unsigned ChildNo = 0;
1188 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1189 Record *OperandNode = Inst.getOperand(i);
1190
1191 // If the instruction expects a predicate or optional def operand, we
1192 // codegen this by setting the operand to it's default value if it has a
1193 // non-empty DefaultOps field.
1194 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1195 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1196 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1197 continue;
1198
1199 // Verify that we didn't run out of provided operands.
1200 if (ChildNo >= getNumChildren())
1201 TP.error("Instruction '" + getOperator()->getName() +
1202 "' expects more operands than were provided.");
1203
Owen Anderson825b72b2009-08-11 20:47:22 +00001204 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001205 TreePatternNode *Child = getChild(ChildNo++);
1206 if (OperandNode->isSubClassOf("RegisterClass")) {
1207 const CodeGenRegisterClass &RC =
1208 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner2cacec52010-03-15 06:00:16 +00001209 MadeChange |= Child->UpdateNodeType(RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001210 } else if (OperandNode->isSubClassOf("Operand")) {
1211 VT = getValueType(OperandNode->getValueAsDef("Type"));
1212 MadeChange |= Child->UpdateNodeType(VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001213 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001214 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001215 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001216 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001217 } else {
1218 assert(0 && "Unknown operand type!");
1219 abort();
1220 }
1221 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1222 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001223
Christopher Lamb02f69372008-03-10 04:16:09 +00001224 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001225 TP.error("Instruction '" + getOperator()->getName() +
1226 "' was provided too many operands!");
1227
1228 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001229 }
Chris Lattner6eb30122010-02-23 05:51:07 +00001230
1231 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1232
1233 // Node transforms always take one operand.
1234 if (getNumChildren() != 1)
1235 TP.error("Node transform '" + getOperator()->getName() +
1236 "' requires one operand!");
1237
Chris Lattner2cacec52010-03-15 06:00:16 +00001238 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1239
1240
Chris Lattner6eb30122010-02-23 05:51:07 +00001241 // If either the output or input of the xform does not have exact
1242 // type info. We assume they must be the same. Otherwise, it is perfectly
1243 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001244#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001245 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001246 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1247 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001248 return MadeChange;
1249 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001250#endif
1251 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001252}
1253
1254/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1255/// RHS of a commutative operation, not the on LHS.
1256static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1257 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1258 return true;
1259 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1260 return true;
1261 return false;
1262}
1263
1264
1265/// canPatternMatch - If it is impossible for this pattern to match on this
1266/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001267/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001268/// that can never possibly work), and to prevent the pattern permuter from
1269/// generating stuff that is useless.
1270bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001271 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001272 if (isLeaf()) return true;
1273
1274 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1275 if (!getChild(i)->canPatternMatch(Reason, CDP))
1276 return false;
1277
1278 // If this is an intrinsic, handle cases that would make it not match. For
1279 // example, if an operand is required to be an immediate.
1280 if (getOperator()->isSubClassOf("Intrinsic")) {
1281 // TODO:
1282 return true;
1283 }
1284
1285 // If this node is a commutative operator, check that the LHS isn't an
1286 // immediate.
1287 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001288 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1289 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001290 // Scan all of the operands of the node and make sure that only the last one
1291 // is a constant node, unless the RHS also is.
1292 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001293 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1294 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001295 if (OnlyOnRHSOfCommutative(getChild(i))) {
1296 Reason="Immediate value must be on the RHS of commutative operators!";
1297 return false;
1298 }
1299 }
1300 }
1301
1302 return true;
1303}
1304
1305//===----------------------------------------------------------------------===//
1306// TreePattern implementation
1307//
1308
1309TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001310 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001311 isInputPattern = isInput;
1312 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1313 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001314}
1315
1316TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001317 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001318 isInputPattern = isInput;
1319 Trees.push_back(ParseTreePattern(Pat));
1320}
1321
1322TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001323 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001324 isInputPattern = isInput;
1325 Trees.push_back(Pat);
1326}
1327
Chris Lattner6cefb772008-01-05 22:25:12 +00001328void TreePattern::error(const std::string &Msg) const {
1329 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001330 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001331}
1332
Chris Lattner2cacec52010-03-15 06:00:16 +00001333void TreePattern::ComputeNamedNodes() {
1334 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1335 ComputeNamedNodes(Trees[i]);
1336}
1337
1338void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1339 if (!N->getName().empty())
1340 NamedNodes[N->getName()].push_back(N);
1341
1342 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1343 ComputeNamedNodes(N->getChild(i));
1344}
1345
Chris Lattner6cefb772008-01-05 22:25:12 +00001346TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1347 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1348 if (!OpDef) error("Pattern has unexpected operator type!");
1349 Record *Operator = OpDef->getDef();
1350
1351 if (Operator->isSubClassOf("ValueType")) {
1352 // If the operator is a ValueType, then this must be "type cast" of a leaf
1353 // node.
1354 if (Dag->getNumArgs() != 1)
1355 error("Type cast only takes one operand!");
1356
1357 Init *Arg = Dag->getArg(0);
1358 TreePatternNode *New;
1359 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1360 Record *R = DI->getDef();
1361 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001362 Dag->setArg(0, new DagInit(DI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001363 std::vector<std::pair<Init*, std::string> >()));
1364 return ParseTreePattern(Dag);
1365 }
Chris Lattner43e47542010-03-08 18:36:19 +00001366
1367 // Input argument?
1368 if (R->getName() == "node") {
1369 if (Dag->getArgName(0).empty())
1370 error("'node' argument requires a name to match with operand list");
1371 Args.push_back(Dag->getArgName(0));
1372 }
1373
Chris Lattner6cefb772008-01-05 22:25:12 +00001374 New = new TreePatternNode(DI);
1375 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1376 New = ParseTreePattern(DI);
1377 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1378 New = new TreePatternNode(II);
1379 if (!Dag->getArgName(0).empty())
1380 error("Constant int argument should not have a name!");
1381 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1382 // Turn this into an IntInit.
1383 Init *II = BI->convertInitializerTo(new IntRecTy());
1384 if (II == 0 || !dynamic_cast<IntInit*>(II))
1385 error("Bits value must be constants!");
1386
1387 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1388 if (!Dag->getArgName(0).empty())
1389 error("Constant int argument should not have a name!");
1390 } else {
1391 Arg->dump();
1392 error("Unknown leaf value for tree pattern!");
1393 return 0;
1394 }
1395
1396 // Apply the type cast.
1397 New->UpdateNodeType(getValueType(Operator), *this);
Nate Begeman7cee8172009-03-19 05:21:56 +00001398 if (New->getNumChildren() == 0)
1399 New->setName(Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001400 return New;
1401 }
1402
1403 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001404 if (!Operator->isSubClassOf("PatFrag") &&
1405 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001406 !Operator->isSubClassOf("Instruction") &&
1407 !Operator->isSubClassOf("SDNodeXForm") &&
1408 !Operator->isSubClassOf("Intrinsic") &&
1409 Operator->getName() != "set" &&
1410 Operator->getName() != "implicit" &&
1411 Operator->getName() != "parallel")
1412 error("Unrecognized node '" + Operator->getName() + "'!");
1413
1414 // Check to see if this is something that is illegal in an input pattern.
1415 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1416 Operator->isSubClassOf("SDNodeXForm")))
1417 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1418
1419 std::vector<TreePatternNode*> Children;
1420
1421 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1422 Init *Arg = Dag->getArg(i);
1423 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1424 Children.push_back(ParseTreePattern(DI));
1425 if (Children.back()->getName().empty())
1426 Children.back()->setName(Dag->getArgName(i));
1427 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1428 Record *R = DefI->getDef();
1429 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1430 // TreePatternNode if its own.
1431 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001432 Dag->setArg(i, new DagInit(DefI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001433 std::vector<std::pair<Init*, std::string> >()));
1434 --i; // Revisit this node...
1435 } else {
1436 TreePatternNode *Node = new TreePatternNode(DefI);
1437 Node->setName(Dag->getArgName(i));
1438 Children.push_back(Node);
1439
1440 // Input argument?
1441 if (R->getName() == "node") {
1442 if (Dag->getArgName(i).empty())
1443 error("'node' argument requires a name to match with operand list");
1444 Args.push_back(Dag->getArgName(i));
1445 }
1446 }
1447 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1448 TreePatternNode *Node = new TreePatternNode(II);
1449 if (!Dag->getArgName(i).empty())
1450 error("Constant int argument should not have a name!");
1451 Children.push_back(Node);
1452 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1453 // Turn this into an IntInit.
1454 Init *II = BI->convertInitializerTo(new IntRecTy());
1455 if (II == 0 || !dynamic_cast<IntInit*>(II))
1456 error("Bits value must be constants!");
1457
1458 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1459 if (!Dag->getArgName(i).empty())
1460 error("Constant int argument should not have a name!");
1461 Children.push_back(Node);
1462 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001463 errs() << '"';
Chris Lattner6cefb772008-01-05 22:25:12 +00001464 Arg->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001465 errs() << "\": ";
Chris Lattner6cefb772008-01-05 22:25:12 +00001466 error("Unknown leaf value for tree pattern!");
1467 }
1468 }
1469
1470 // If the operator is an intrinsic, then this is just syntactic sugar for for
1471 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1472 // convert the intrinsic name to a number.
1473 if (Operator->isSubClassOf("Intrinsic")) {
1474 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1475 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1476
1477 // If this intrinsic returns void, it must have side-effects and thus a
1478 // chain.
Owen Anderson825b72b2009-08-11 20:47:22 +00001479 if (Int.IS.RetVTs[0] == MVT::isVoid) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001480 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1481 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1482 // Has side-effects, requires chain.
1483 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1484 } else {
1485 // Otherwise, no chain.
1486 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1487 }
1488
1489 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1490 Children.insert(Children.begin(), IIDNode);
1491 }
1492
Nate Begeman7cee8172009-03-19 05:21:56 +00001493 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1494 Result->setName(Dag->getName());
1495 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001496}
1497
1498/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001499/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001500/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001501bool TreePattern::
1502InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1503 if (NamedNodes.empty())
1504 ComputeNamedNodes();
1505
Chris Lattner6cefb772008-01-05 22:25:12 +00001506 bool MadeChange = true;
1507 while (MadeChange) {
1508 MadeChange = false;
1509 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1510 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner2cacec52010-03-15 06:00:16 +00001511
1512 // If there are constraints on our named nodes, apply them.
1513 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1514 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1515 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1516
1517 // If we have input named node types, propagate their types to the named
1518 // values here.
1519 if (InNamedTypes) {
1520 // FIXME: Should be error?
1521 assert(InNamedTypes->count(I->getKey()) &&
1522 "Named node in output pattern but not input pattern?");
1523
1524 const SmallVectorImpl<TreePatternNode*> &InNodes =
1525 InNamedTypes->find(I->getKey())->second;
1526
1527 // The input types should be fully resolved by now.
1528 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1529 // If this node is a register class, and it is the root of the pattern
1530 // then we're mapping something onto an input register. We allow
1531 // changing the type of the input register in this case. This allows
1532 // us to match things like:
1533 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1534 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1535 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1536 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1537 continue;
1538 }
1539
1540 MadeChange |=Nodes[i]->UpdateNodeType(InNodes[0]->getExtType(),*this);
1541 }
1542 }
1543
1544 // If there are multiple nodes with the same name, they must all have the
1545 // same type.
1546 if (I->second.size() > 1) {
1547 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1548 MadeChange |=Nodes[i]->UpdateNodeType(Nodes[i+1]->getExtType(),*this);
1549 MadeChange |=Nodes[i+1]->UpdateNodeType(Nodes[i]->getExtType(),*this);
1550 }
1551 }
1552 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001553 }
1554
1555 bool HasUnresolvedTypes = false;
1556 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1557 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1558 return !HasUnresolvedTypes;
1559}
1560
Daniel Dunbar1a551802009-07-03 00:10:29 +00001561void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001562 OS << getRecord()->getName();
1563 if (!Args.empty()) {
1564 OS << "(" << Args[0];
1565 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1566 OS << ", " << Args[i];
1567 OS << ")";
1568 }
1569 OS << ": ";
1570
1571 if (Trees.size() > 1)
1572 OS << "[\n";
1573 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1574 OS << "\t";
1575 Trees[i]->print(OS);
1576 OS << "\n";
1577 }
1578
1579 if (Trees.size() > 1)
1580 OS << "]\n";
1581}
1582
Daniel Dunbar1a551802009-07-03 00:10:29 +00001583void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001584
1585//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001586// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001587//
1588
Chris Lattnerfe718932008-01-06 01:10:31 +00001589CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001590 Intrinsics = LoadIntrinsics(Records, false);
1591 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001592 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001593 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001594 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001595 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001596 ParseDefaultOperands();
1597 ParseInstructions();
1598 ParsePatterns();
1599
1600 // Generate variants. For example, commutative patterns can match
1601 // multiple ways. Add them to PatternsToMatch as well.
1602 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001603
1604 // Infer instruction flags. For example, we can detect loads,
1605 // stores, and side effects in many cases by examining an
1606 // instruction's pattern.
1607 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001608}
1609
Chris Lattnerfe718932008-01-06 01:10:31 +00001610CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001611 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001612 E = PatternFragments.end(); I != E; ++I)
1613 delete I->second;
1614}
1615
1616
Chris Lattnerfe718932008-01-06 01:10:31 +00001617Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001618 Record *N = Records.getDef(Name);
1619 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001620 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001621 exit(1);
1622 }
1623 return N;
1624}
1625
1626// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001627void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001628 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1629 while (!Nodes.empty()) {
1630 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1631 Nodes.pop_back();
1632 }
1633
Jim Grosbachda4231f2009-03-26 16:17:51 +00001634 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001635 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1636 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1637 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1638}
1639
1640/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1641/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001642void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001643 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1644 while (!Xforms.empty()) {
1645 Record *XFormNode = Xforms.back();
1646 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1647 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001648 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001649
1650 Xforms.pop_back();
1651 }
1652}
1653
Chris Lattnerfe718932008-01-06 01:10:31 +00001654void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001655 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1656 while (!AMs.empty()) {
1657 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1658 AMs.pop_back();
1659 }
1660}
1661
1662
1663/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1664/// file, building up the PatternFragments map. After we've collected them all,
1665/// inline fragments together as necessary, so that there are no references left
1666/// inside a pattern fragment to a pattern fragment.
1667///
Chris Lattnerfe718932008-01-06 01:10:31 +00001668void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001669 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1670
Chris Lattnerdc32f982008-01-05 22:43:57 +00001671 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001672 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1673 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1674 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1675 PatternFragments[Fragments[i]] = P;
1676
Chris Lattnerdc32f982008-01-05 22:43:57 +00001677 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001678 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001679 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001680
Chris Lattnerdc32f982008-01-05 22:43:57 +00001681 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001682 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1683
1684 // Parse the operands list.
1685 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1686 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1687 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001688 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001689 if (!OpsOp ||
1690 (OpsOp->getDef()->getName() != "ops" &&
1691 OpsOp->getDef()->getName() != "outs" &&
1692 OpsOp->getDef()->getName() != "ins"))
1693 P->error("Operands list should start with '(ops ... '!");
1694
1695 // Copy over the arguments.
1696 Args.clear();
1697 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1698 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1699 static_cast<DefInit*>(OpsList->getArg(j))->
1700 getDef()->getName() != "node")
1701 P->error("Operands list should all be 'node' values.");
1702 if (OpsList->getArgName(j).empty())
1703 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001704 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001705 P->error("'" + OpsList->getArgName(j) +
1706 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001707 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001708 Args.push_back(OpsList->getArgName(j));
1709 }
1710
Chris Lattnerdc32f982008-01-05 22:43:57 +00001711 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001712 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001713 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001714
Chris Lattnerdc32f982008-01-05 22:43:57 +00001715 // If there is a code init for this fragment, keep track of the fact that
1716 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001717 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001718 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001719 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001720
1721 // If there is a node transformation corresponding to this, keep track of
1722 // it.
1723 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1724 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1725 P->getOnlyTree()->setTransformFn(Transform);
1726 }
1727
Chris Lattner6cefb772008-01-05 22:25:12 +00001728 // Now that we've parsed all of the tree fragments, do a closure on them so
1729 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001730 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1731 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001732 ThePat->InlinePatternFragments();
1733
1734 // Infer as many types as possible. Don't worry about it if we don't infer
1735 // all of them, some may depend on the inputs of the pattern.
1736 try {
1737 ThePat->InferAllTypes();
1738 } catch (...) {
1739 // If this pattern fragment is not supported by this target (no types can
1740 // satisfy its constraints), just ignore it. If the bogus pattern is
1741 // actually used by instructions, the type consistency error will be
1742 // reported there.
1743 }
1744
1745 // If debugging, print out the pattern fragment result.
1746 DEBUG(ThePat->dump());
1747 }
1748}
1749
Chris Lattnerfe718932008-01-06 01:10:31 +00001750void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001751 std::vector<Record*> DefaultOps[2];
1752 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1753 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1754
1755 // Find some SDNode.
1756 assert(!SDNodes.empty() && "No SDNodes parsed?");
1757 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1758
1759 for (unsigned iter = 0; iter != 2; ++iter) {
1760 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1761 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1762
1763 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1764 // SomeSDnode so that we can parse this.
1765 std::vector<std::pair<Init*, std::string> > Ops;
1766 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1767 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1768 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001769 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001770
1771 // Create a TreePattern to parse this.
1772 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1773 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1774
1775 // Copy the operands over into a DAGDefaultOperand.
1776 DAGDefaultOperand DefaultOpInfo;
1777
1778 TreePatternNode *T = P.getTree(0);
1779 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1780 TreePatternNode *TPN = T->getChild(op);
1781 while (TPN->ApplyTypeConstraints(P, false))
1782 /* Resolve all types */;
1783
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001784 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001785 if (iter == 0)
1786 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001787 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00001788 else
1789 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001790 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001791 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001792 DefaultOpInfo.DefaultOps.push_back(TPN);
1793 }
1794
1795 // Insert it into the DefaultOperands map so we can find it later.
1796 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1797 }
1798 }
1799}
1800
1801/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1802/// instruction input. Return true if this is a real use.
1803static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1804 std::map<std::string, TreePatternNode*> &InstInputs,
1805 std::vector<Record*> &InstImpInputs) {
1806 // No name -> not interesting.
1807 if (Pat->getName().empty()) {
1808 if (Pat->isLeaf()) {
1809 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1810 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1811 I->error("Input " + DI->getDef()->getName() + " must be named!");
1812 else if (DI && DI->getDef()->isSubClassOf("Register"))
1813 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001814 }
1815 return false;
1816 }
1817
1818 Record *Rec;
1819 if (Pat->isLeaf()) {
1820 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1821 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1822 Rec = DI->getDef();
1823 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001824 Rec = Pat->getOperator();
1825 }
1826
1827 // SRCVALUE nodes are ignored.
1828 if (Rec->getName() == "srcvalue")
1829 return false;
1830
1831 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1832 if (!Slot) {
1833 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00001834 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00001835 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00001836 Record *SlotRec;
1837 if (Slot->isLeaf()) {
1838 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1839 } else {
1840 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1841 SlotRec = Slot->getOperator();
1842 }
1843
1844 // Ensure that the inputs agree if we've already seen this input.
1845 if (Rec != SlotRec)
1846 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner2cacec52010-03-15 06:00:16 +00001847 if (Slot->getExtType() != Pat->getExtType())
Chris Lattner53d09bd2010-02-23 05:59:10 +00001848 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00001849 return true;
1850}
1851
1852/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1853/// part of "I", the instruction), computing the set of inputs and outputs of
1854/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001855void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001856FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1857 std::map<std::string, TreePatternNode*> &InstInputs,
1858 std::map<std::string, TreePatternNode*>&InstResults,
1859 std::vector<Record*> &InstImpInputs,
1860 std::vector<Record*> &InstImpResults) {
1861 if (Pat->isLeaf()) {
1862 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1863 if (!isUse && Pat->getTransformFn())
1864 I->error("Cannot specify a transform function for a non-input value!");
1865 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001866 }
1867
1868 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001869 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1870 TreePatternNode *Dest = Pat->getChild(i);
1871 if (!Dest->isLeaf())
1872 I->error("implicitly defined value should be a register!");
1873
1874 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1875 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1876 I->error("implicitly defined value should be a register!");
1877 InstImpResults.push_back(Val->getDef());
1878 }
1879 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001880 }
1881
1882 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001883 // If this is not a set, verify that the children nodes are not void typed,
1884 // and recurse.
1885 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001886 if (Pat->getChild(i)->getType() == MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00001887 I->error("Cannot have void nodes inside of patterns!");
1888 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1889 InstImpInputs, InstImpResults);
1890 }
1891
1892 // If this is a non-leaf node with no children, treat it basically as if
1893 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00001894 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00001895
1896 if (!isUse && Pat->getTransformFn())
1897 I->error("Cannot specify a transform function for a non-input value!");
1898 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001899 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001900
1901 // Otherwise, this is a set, validate and collect instruction results.
1902 if (Pat->getNumChildren() == 0)
1903 I->error("set requires operands!");
1904
1905 if (Pat->getTransformFn())
1906 I->error("Cannot specify a transform function on a set node!");
1907
1908 // Check the set destinations.
1909 unsigned NumDests = Pat->getNumChildren()-1;
1910 for (unsigned i = 0; i != NumDests; ++i) {
1911 TreePatternNode *Dest = Pat->getChild(i);
1912 if (!Dest->isLeaf())
1913 I->error("set destination should be a register!");
1914
1915 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1916 if (!Val)
1917 I->error("set destination should be a register!");
1918
1919 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00001920 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001921 if (Dest->getName().empty())
1922 I->error("set destination must have a name!");
1923 if (InstResults.count(Dest->getName()))
1924 I->error("cannot set '" + Dest->getName() +"' multiple times");
1925 InstResults[Dest->getName()] = Dest;
1926 } else if (Val->getDef()->isSubClassOf("Register")) {
1927 InstImpResults.push_back(Val->getDef());
1928 } else {
1929 I->error("set destination should be a register!");
1930 }
1931 }
1932
1933 // Verify and collect info from the computation.
1934 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1935 InstInputs, InstResults,
1936 InstImpInputs, InstImpResults);
1937}
1938
Dan Gohmanee4fa192008-04-03 00:02:49 +00001939//===----------------------------------------------------------------------===//
1940// Instruction Analysis
1941//===----------------------------------------------------------------------===//
1942
1943class InstAnalyzer {
1944 const CodeGenDAGPatterns &CDP;
1945 bool &mayStore;
1946 bool &mayLoad;
1947 bool &HasSideEffects;
1948public:
1949 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1950 bool &maystore, bool &mayload, bool &hse)
1951 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1952 }
1953
1954 /// Analyze - Analyze the specified instruction, returning true if the
1955 /// instruction had a pattern.
1956 bool Analyze(Record *InstRecord) {
1957 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1958 if (Pattern == 0) {
1959 HasSideEffects = 1;
1960 return false; // No pattern.
1961 }
1962
1963 // FIXME: Assume only the first tree is the pattern. The others are clobber
1964 // nodes.
1965 AnalyzeNode(Pattern->getTree(0));
1966 return true;
1967 }
1968
1969private:
1970 void AnalyzeNode(const TreePatternNode *N) {
1971 if (N->isLeaf()) {
1972 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1973 Record *LeafRec = DI->getDef();
1974 // Handle ComplexPattern leaves.
1975 if (LeafRec->isSubClassOf("ComplexPattern")) {
1976 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1977 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1978 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1979 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1980 }
1981 }
1982 return;
1983 }
1984
1985 // Analyze children.
1986 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1987 AnalyzeNode(N->getChild(i));
1988
1989 // Ignore set nodes, which are not SDNodes.
1990 if (N->getOperator()->getName() == "set")
1991 return;
1992
1993 // Get information about the SDNode for the operator.
1994 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1995
1996 // Notice properties of the node.
1997 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1998 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1999 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2000
2001 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2002 // If this is an intrinsic, analyze it.
2003 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2004 mayLoad = true;// These may load memory.
2005
2006 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2007 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2008
2009 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2010 // WriteMem intrinsics can have other strange effects.
2011 HasSideEffects = true;
2012 }
2013 }
2014
2015};
2016
2017static void InferFromPattern(const CodeGenInstruction &Inst,
2018 bool &MayStore, bool &MayLoad,
2019 bool &HasSideEffects,
2020 const CodeGenDAGPatterns &CDP) {
2021 MayStore = MayLoad = HasSideEffects = false;
2022
2023 bool HadPattern =
2024 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
2025
2026 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2027 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2028 // If we decided that this is a store from the pattern, then the .td file
2029 // entry is redundant.
2030 if (MayStore)
2031 fprintf(stderr,
2032 "Warning: mayStore flag explicitly set on instruction '%s'"
2033 " but flag already inferred from pattern.\n",
2034 Inst.TheDef->getName().c_str());
2035 MayStore = true;
2036 }
2037
2038 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2039 // If we decided that this is a load from the pattern, then the .td file
2040 // entry is redundant.
2041 if (MayLoad)
2042 fprintf(stderr,
2043 "Warning: mayLoad flag explicitly set on instruction '%s'"
2044 " but flag already inferred from pattern.\n",
2045 Inst.TheDef->getName().c_str());
2046 MayLoad = true;
2047 }
2048
2049 if (Inst.neverHasSideEffects) {
2050 if (HadPattern)
2051 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2052 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2053 HasSideEffects = false;
2054 }
2055
2056 if (Inst.hasSideEffects) {
2057 if (HasSideEffects)
2058 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2059 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2060 HasSideEffects = true;
2061 }
2062}
2063
Chris Lattner6cefb772008-01-05 22:25:12 +00002064/// ParseInstructions - Parse all of the instructions, inlining and resolving
2065/// any fragments involved. This populates the Instructions list with fully
2066/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002067void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002068 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2069
2070 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2071 ListInit *LI = 0;
2072
2073 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2074 LI = Instrs[i]->getValueAsListInit("Pattern");
2075
2076 // If there is no pattern, only collect minimal information about the
2077 // instruction for its operand list. We have to assume that there is one
2078 // result, as we have no detailed info.
2079 if (!LI || LI->getSize() == 0) {
2080 std::vector<Record*> Results;
2081 std::vector<Record*> Operands;
2082
Chris Lattnerf30187a2010-03-19 00:07:20 +00002083 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002084
2085 if (InstInfo.OperandList.size() != 0) {
2086 if (InstInfo.NumDefs == 0) {
2087 // These produce no results
2088 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2089 Operands.push_back(InstInfo.OperandList[j].Rec);
2090 } else {
2091 // Assume the first operand is the result.
2092 Results.push_back(InstInfo.OperandList[0].Rec);
2093
2094 // The rest are inputs.
2095 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2096 Operands.push_back(InstInfo.OperandList[j].Rec);
2097 }
2098 }
2099
2100 // Create and insert the instruction.
2101 std::vector<Record*> ImpResults;
2102 std::vector<Record*> ImpOperands;
2103 Instructions.insert(std::make_pair(Instrs[i],
2104 DAGInstruction(0, Results, Operands, ImpResults,
2105 ImpOperands)));
2106 continue; // no pattern.
2107 }
2108
2109 // Parse the instruction.
2110 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2111 // Inline pattern fragments into it.
2112 I->InlinePatternFragments();
2113
2114 // Infer as many types as possible. If we cannot infer all of them, we can
2115 // never do anything with this instruction pattern: report it to the user.
2116 if (!I->InferAllTypes())
2117 I->error("Could not infer all types in pattern!");
2118
2119 // InstInputs - Keep track of all of the inputs of the instruction, along
2120 // with the record they are declared as.
2121 std::map<std::string, TreePatternNode*> InstInputs;
2122
2123 // InstResults - Keep track of all the virtual registers that are 'set'
2124 // in the instruction, including what reg class they are.
2125 std::map<std::string, TreePatternNode*> InstResults;
2126
2127 std::vector<Record*> InstImpInputs;
2128 std::vector<Record*> InstImpResults;
2129
2130 // Verify that the top-level forms in the instruction are of void type, and
2131 // fill in the InstResults map.
2132 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2133 TreePatternNode *Pat = I->getTree(j);
Chris Lattner2cacec52010-03-15 06:00:16 +00002134 if (!Pat->hasTypeSet() || Pat->getType() != MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00002135 I->error("Top-level forms in instruction pattern should have"
2136 " void types");
2137
2138 // Find inputs and outputs, and verify the structure of the uses/defs.
2139 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2140 InstImpInputs, InstImpResults);
2141 }
2142
2143 // Now that we have inputs and outputs of the pattern, inspect the operands
2144 // list for the instruction. This determines the order that operands are
2145 // added to the machine instruction the node corresponds to.
2146 unsigned NumResults = InstResults.size();
2147
2148 // Parse the operands list from the (ops) list, validating it.
2149 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002150 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002151
2152 // Check that all of the results occur first in the list.
2153 std::vector<Record*> Results;
2154 TreePatternNode *Res0Node = NULL;
2155 for (unsigned i = 0; i != NumResults; ++i) {
2156 if (i == CGI.OperandList.size())
2157 I->error("'" + InstResults.begin()->first +
2158 "' set but does not appear in operand list!");
2159 const std::string &OpName = CGI.OperandList[i].Name;
2160
2161 // Check that it exists in InstResults.
2162 TreePatternNode *RNode = InstResults[OpName];
2163 if (RNode == 0)
2164 I->error("Operand $" + OpName + " does not exist in operand list!");
2165
2166 if (i == 0)
2167 Res0Node = RNode;
2168 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2169 if (R == 0)
2170 I->error("Operand $" + OpName + " should be a set destination: all "
2171 "outputs must occur before inputs in operand list!");
2172
2173 if (CGI.OperandList[i].Rec != R)
2174 I->error("Operand $" + OpName + " class mismatch!");
2175
2176 // Remember the return type.
2177 Results.push_back(CGI.OperandList[i].Rec);
2178
2179 // Okay, this one checks out.
2180 InstResults.erase(OpName);
2181 }
2182
2183 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2184 // the copy while we're checking the inputs.
2185 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2186
2187 std::vector<TreePatternNode*> ResultNodeOperands;
2188 std::vector<Record*> Operands;
2189 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2190 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2191 const std::string &OpName = Op.Name;
2192 if (OpName.empty())
2193 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2194
2195 if (!InstInputsCheck.count(OpName)) {
2196 // If this is an predicate operand or optional def operand with an
2197 // DefaultOps set filled in, we can ignore this. When we codegen it,
2198 // we will do so as always executed.
2199 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2200 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2201 // Does it have a non-empty DefaultOps field? If so, ignore this
2202 // operand.
2203 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2204 continue;
2205 }
2206 I->error("Operand $" + OpName +
2207 " does not appear in the instruction pattern");
2208 }
2209 TreePatternNode *InVal = InstInputsCheck[OpName];
2210 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2211
2212 if (InVal->isLeaf() &&
2213 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2214 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2215 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2216 I->error("Operand $" + OpName + "'s register class disagrees"
2217 " between the operand and pattern");
2218 }
2219 Operands.push_back(Op.Rec);
2220
2221 // Construct the result for the dest-pattern operand list.
2222 TreePatternNode *OpNode = InVal->clone();
2223
2224 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002225 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00002226
2227 // Promote the xform function to be an explicit node if set.
2228 if (Record *Xform = OpNode->getTransformFn()) {
2229 OpNode->setTransformFn(0);
2230 std::vector<TreePatternNode*> Children;
2231 Children.push_back(OpNode);
2232 OpNode = new TreePatternNode(Xform, Children);
2233 }
2234
2235 ResultNodeOperands.push_back(OpNode);
2236 }
2237
2238 if (!InstInputsCheck.empty())
2239 I->error("Input operand $" + InstInputsCheck.begin()->first +
2240 " occurs in pattern but not in operands list!");
2241
2242 TreePatternNode *ResultPattern =
2243 new TreePatternNode(I->getRecord(), ResultNodeOperands);
2244 // Copy fully inferred output node type to instruction result pattern.
2245 if (NumResults > 0)
Chris Lattner2cacec52010-03-15 06:00:16 +00002246 ResultPattern->setType(Res0Node->getExtType());
Chris Lattner6cefb772008-01-05 22:25:12 +00002247
2248 // Create and insert the instruction.
2249 // FIXME: InstImpResults and InstImpInputs should not be part of
2250 // DAGInstruction.
2251 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2252 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2253
2254 // Use a temporary tree pattern to infer all types and make sure that the
2255 // constructed result is correct. This depends on the instruction already
2256 // being inserted into the Instructions map.
2257 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002258 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002259
2260 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2261 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2262
2263 DEBUG(I->dump());
2264 }
2265
2266 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002267 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2268 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002269 E = Instructions.end(); II != E; ++II) {
2270 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002271 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002272 if (I == 0) continue; // No pattern.
2273
2274 // FIXME: Assume only the first tree is the pattern. The others are clobber
2275 // nodes.
2276 TreePatternNode *Pattern = I->getTree(0);
2277 TreePatternNode *SrcPattern;
2278 if (Pattern->getOperator()->getName() == "set") {
2279 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2280 } else{
2281 // Not a set (store or something?)
2282 SrcPattern = Pattern;
2283 }
2284
Chris Lattner6cefb772008-01-05 22:25:12 +00002285 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002286 AddPatternToMatch(I,
2287 PatternToMatch(Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002288 SrcPattern,
2289 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002290 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002291 Instr->getValueAsInt("AddedComplexity"),
2292 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002293 }
2294}
2295
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002296
2297typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2298
Chris Lattner967d54a2010-02-23 06:35:45 +00002299static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002300 std::map<std::string, NameRecord> &Names,
2301 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002302 if (!P->getName().empty()) {
2303 NameRecord &Rec = Names[P->getName()];
2304 // If this is the first instance of the name, remember the node.
2305 if (Rec.second++ == 0)
2306 Rec.first = P;
Chris Lattner2cacec52010-03-15 06:00:16 +00002307 else if (Rec.first->getType() != P->getType())
Chris Lattnera27234e2010-02-23 07:22:28 +00002308 PatternTop->error("repetition of value: $" + P->getName() +
2309 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002310 }
Chris Lattner967d54a2010-02-23 06:35:45 +00002311
2312 if (!P->isLeaf()) {
2313 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002314 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002315 }
2316}
2317
Chris Lattner25b6f912010-02-23 06:16:51 +00002318void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2319 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002320 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002321 std::string Reason;
2322 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002323 Pattern->error("Pattern can never match: " + Reason);
Chris Lattner25b6f912010-02-23 06:16:51 +00002324
Chris Lattner405f1252010-03-01 22:29:19 +00002325 // If the source pattern's root is a complex pattern, that complex pattern
2326 // must specify the nodes it can potentially match.
2327 if (const ComplexPattern *CP =
2328 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2329 if (CP->getRootNodes().empty())
2330 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2331 " could match");
2332
2333
Chris Lattner967d54a2010-02-23 06:35:45 +00002334 // Find all of the named values in the input and output, ensure they have the
2335 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002336 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002337 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2338 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002339
2340 // Scan all of the named values in the destination pattern, rejecting them if
2341 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002342 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002343 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002344 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002345 Pattern->error("Pattern has input without matching name in output: $" +
2346 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002347 }
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002348
2349 // Scan all of the named values in the source pattern, rejecting them if the
2350 // name isn't used in the dest, and isn't used to tie two values together.
2351 for (std::map<std::string, NameRecord>::iterator
2352 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2353 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2354 Pattern->error("Pattern has dead named input: $" + I->first);
2355
Chris Lattner25b6f912010-02-23 06:16:51 +00002356 PatternsToMatch.push_back(PTM);
2357}
2358
2359
Dan Gohmanee4fa192008-04-03 00:02:49 +00002360
2361void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002362 const std::vector<const CodeGenInstruction*> &Instructions =
2363 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002364 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2365 CodeGenInstruction &InstInfo =
2366 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002367 // Determine properties of the instruction from its pattern.
2368 bool MayStore, MayLoad, HasSideEffects;
2369 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2370 InstInfo.mayStore = MayStore;
2371 InstInfo.mayLoad = MayLoad;
2372 InstInfo.hasSideEffects = HasSideEffects;
2373 }
2374}
2375
Chris Lattner2cacec52010-03-15 06:00:16 +00002376/// Given a pattern result with an unresolved type, see if we can find one
2377/// instruction with an unresolved result type. Force this result type to an
2378/// arbitrary element if it's possible types to converge results.
2379static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2380 if (N->isLeaf())
2381 return false;
2382
2383 // Analyze children.
2384 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2385 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2386 return true;
2387
2388 if (!N->getOperator()->isSubClassOf("Instruction"))
2389 return false;
2390
2391 // If this type is already concrete or completely unknown we can't do
2392 // anything.
2393 if (N->getExtType().isCompletelyUnknown() || N->getExtType().isConcrete())
2394 return false;
2395
2396 // Otherwise, force its type to the first possibility (an arbitrary choice).
2397 return N->getExtType().MergeInTypeInfo(N->getExtType().getTypeList()[0], TP);
2398}
2399
Chris Lattnerfe718932008-01-06 01:10:31 +00002400void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002401 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2402
2403 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2404 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2405 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2406 Record *Operator = OpDef->getDef();
2407 TreePattern *Pattern;
2408 if (Operator->getName() != "parallel")
2409 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2410 else {
2411 std::vector<Init*> Values;
David Greenee1b46912009-06-08 20:23:18 +00002412 RecTy *ListTy = 0;
2413 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002414 Values.push_back(Tree->getArg(j));
David Greenee1b46912009-06-08 20:23:18 +00002415 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2416 if (TArg == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002417 errs() << "In dag: " << Tree->getAsString();
2418 errs() << " -- Untyped argument in pattern\n";
David Greenee1b46912009-06-08 20:23:18 +00002419 assert(0 && "Untyped argument in pattern");
2420 }
2421 if (ListTy != 0) {
2422 ListTy = resolveTypes(ListTy, TArg->getType());
2423 if (ListTy == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002424 errs() << "In dag: " << Tree->getAsString();
2425 errs() << " -- Incompatible types in pattern arguments\n";
David Greenee1b46912009-06-08 20:23:18 +00002426 assert(0 && "Incompatible types in pattern arguments");
2427 }
2428 }
2429 else {
Bill Wendlingee1f6b02009-06-09 18:49:42 +00002430 ListTy = TArg->getType();
David Greenee1b46912009-06-08 20:23:18 +00002431 }
2432 }
2433 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
Chris Lattner6cefb772008-01-05 22:25:12 +00002434 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2435 }
2436
2437 // Inline pattern fragments into it.
2438 Pattern->InlinePatternFragments();
2439
2440 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2441 if (LI->getSize() == 0) continue; // no pattern.
2442
2443 // Parse the instruction.
2444 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2445
2446 // Inline pattern fragments into it.
2447 Result->InlinePatternFragments();
2448
2449 if (Result->getNumTrees() != 1)
2450 Result->error("Cannot handle instructions producing instructions "
2451 "with temporaries yet!");
2452
2453 bool IterateInference;
2454 bool InferredAllPatternTypes, InferredAllResultTypes;
2455 do {
2456 // Infer as many types as possible. If we cannot infer all of them, we
2457 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002458 InferredAllPatternTypes =
2459 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002460
2461 // Infer as many types as possible. If we cannot infer all of them, we
2462 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002463 InferredAllResultTypes =
2464 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002465
Chris Lattner6c6ba362010-03-18 23:15:10 +00002466 IterateInference = false;
2467
Chris Lattner6cefb772008-01-05 22:25:12 +00002468 // Apply the type of the result to the source pattern. This helps us
2469 // resolve cases where the input type is known to be a pointer type (which
2470 // is considered resolved), but the result knows it needs to be 32- or
2471 // 64-bits. Infer the other way for good measure.
Chris Lattner6c6ba362010-03-18 23:15:10 +00002472 if (!Result->getTree(0)->getExtType().isVoid() &&
2473 !Pattern->getTree(0)->getExtType().isVoid()) {
2474 IterateInference = Pattern->getTree(0)->
2475 UpdateNodeType(Result->getTree(0)->getExtType(), *Result);
2476 IterateInference |= Result->getTree(0)->
2477 UpdateNodeType(Pattern->getTree(0)->getExtType(), *Result);
2478 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002479
2480 // If our iteration has converged and the input pattern's types are fully
2481 // resolved but the result pattern is not fully resolved, we may have a
2482 // situation where we have two instructions in the result pattern and
2483 // the instructions require a common register class, but don't care about
2484 // what actual MVT is used. This is actually a bug in our modelling:
2485 // output patterns should have register classes, not MVTs.
2486 //
2487 // In any case, to handle this, we just go through and disambiguate some
2488 // arbitrary types to the result pattern's nodes.
2489 if (!IterateInference && InferredAllPatternTypes &&
2490 !InferredAllResultTypes)
2491 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2492 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002493 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002494
Chris Lattner6cefb772008-01-05 22:25:12 +00002495 // Verify that we inferred enough types that we can do something with the
2496 // pattern and result. If these fire the user has to add type casts.
2497 if (!InferredAllPatternTypes)
2498 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002499 if (!InferredAllResultTypes) {
2500 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002501 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002502 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002503
2504 // Validate that the input pattern is correct.
2505 std::map<std::string, TreePatternNode*> InstInputs;
2506 std::map<std::string, TreePatternNode*> InstResults;
2507 std::vector<Record*> InstImpInputs;
2508 std::vector<Record*> InstImpResults;
2509 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2510 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2511 InstInputs, InstResults,
2512 InstImpInputs, InstImpResults);
2513
2514 // Promote the xform function to be an explicit node if set.
2515 TreePatternNode *DstPattern = Result->getOnlyTree();
2516 std::vector<TreePatternNode*> ResultNodeOperands;
2517 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2518 TreePatternNode *OpNode = DstPattern->getChild(ii);
2519 if (Record *Xform = OpNode->getTransformFn()) {
2520 OpNode->setTransformFn(0);
2521 std::vector<TreePatternNode*> Children;
2522 Children.push_back(OpNode);
2523 OpNode = new TreePatternNode(Xform, Children);
2524 }
2525 ResultNodeOperands.push_back(OpNode);
2526 }
2527 DstPattern = Result->getOnlyTree();
2528 if (!DstPattern->isLeaf())
2529 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2530 ResultNodeOperands);
Chris Lattner2cacec52010-03-15 06:00:16 +00002531 DstPattern->setType(Result->getOnlyTree()->getExtType());
Chris Lattner6cefb772008-01-05 22:25:12 +00002532 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2533 Temp.InferAllTypes();
2534
Chris Lattner6cefb772008-01-05 22:25:12 +00002535
Chris Lattner25b6f912010-02-23 06:16:51 +00002536 AddPatternToMatch(Pattern,
2537 PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2538 Pattern->getTree(0),
2539 Temp.getOnlyTree(), InstImpResults,
Chris Lattner117ccb72010-03-01 22:09:11 +00002540 Patterns[i]->getValueAsInt("AddedComplexity"),
2541 Patterns[i]->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002542 }
2543}
2544
2545/// CombineChildVariants - Given a bunch of permutations of each child of the
2546/// 'operator' node, put them together in all possible ways.
2547static void CombineChildVariants(TreePatternNode *Orig,
2548 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2549 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002550 CodeGenDAGPatterns &CDP,
2551 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002552 // Make sure that each operand has at least one variant to choose from.
2553 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2554 if (ChildVariants[i].empty())
2555 return;
2556
2557 // The end result is an all-pairs construction of the resultant pattern.
2558 std::vector<unsigned> Idxs;
2559 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002560 bool NotDone;
2561 do {
2562#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002563 DEBUG(if (!Idxs.empty()) {
2564 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2565 for (unsigned i = 0; i < Idxs.size(); ++i) {
2566 errs() << Idxs[i] << " ";
2567 }
2568 errs() << "]\n";
2569 });
Scott Michel327d0652008-03-05 17:49:05 +00002570#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002571 // Create the variant and add it to the output list.
2572 std::vector<TreePatternNode*> NewChildren;
2573 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2574 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2575 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2576
2577 // Copy over properties.
2578 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002579 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002580 R->setTransformFn(Orig->getTransformFn());
Chris Lattner2cacec52010-03-15 06:00:16 +00002581 R->setType(Orig->getExtType());
Chris Lattner6cefb772008-01-05 22:25:12 +00002582
Scott Michel327d0652008-03-05 17:49:05 +00002583 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002584 std::string ErrString;
2585 if (!R->canPatternMatch(ErrString, CDP)) {
2586 delete R;
2587 } else {
2588 bool AlreadyExists = false;
2589
2590 // Scan to see if this pattern has already been emitted. We can get
2591 // duplication due to things like commuting:
2592 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2593 // which are the same pattern. Ignore the dups.
2594 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002595 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002596 AlreadyExists = true;
2597 break;
2598 }
2599
2600 if (AlreadyExists)
2601 delete R;
2602 else
2603 OutVariants.push_back(R);
2604 }
2605
Scott Michel327d0652008-03-05 17:49:05 +00002606 // Increment indices to the next permutation by incrementing the
2607 // indicies from last index backward, e.g., generate the sequence
2608 // [0, 0], [0, 1], [1, 0], [1, 1].
2609 int IdxsIdx;
2610 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2611 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2612 Idxs[IdxsIdx] = 0;
2613 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002614 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002615 }
Scott Michel327d0652008-03-05 17:49:05 +00002616 NotDone = (IdxsIdx >= 0);
2617 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002618}
2619
2620/// CombineChildVariants - A helper function for binary operators.
2621///
2622static void CombineChildVariants(TreePatternNode *Orig,
2623 const std::vector<TreePatternNode*> &LHS,
2624 const std::vector<TreePatternNode*> &RHS,
2625 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002626 CodeGenDAGPatterns &CDP,
2627 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002628 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2629 ChildVariants.push_back(LHS);
2630 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002631 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002632}
2633
2634
2635static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2636 std::vector<TreePatternNode *> &Children) {
2637 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2638 Record *Operator = N->getOperator();
2639
2640 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002641 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002642 N->getTransformFn()) {
2643 Children.push_back(N);
2644 return;
2645 }
2646
2647 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2648 Children.push_back(N->getChild(0));
2649 else
2650 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2651
2652 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2653 Children.push_back(N->getChild(1));
2654 else
2655 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2656}
2657
2658/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2659/// the (potentially recursive) pattern by using algebraic laws.
2660///
2661static void GenerateVariantsOf(TreePatternNode *N,
2662 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002663 CodeGenDAGPatterns &CDP,
2664 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002665 // We cannot permute leaves.
2666 if (N->isLeaf()) {
2667 OutVariants.push_back(N);
2668 return;
2669 }
2670
2671 // Look up interesting info about the node.
2672 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2673
Jim Grosbachda4231f2009-03-26 16:17:51 +00002674 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002675 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002676 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002677 std::vector<TreePatternNode*> MaximalChildren;
2678 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2679
2680 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2681 // permutations.
2682 if (MaximalChildren.size() == 3) {
2683 // Find the variants of all of our maximal children.
2684 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002685 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2686 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2687 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002688
2689 // There are only two ways we can permute the tree:
2690 // (A op B) op C and A op (B op C)
2691 // Within these forms, we can also permute A/B/C.
2692
2693 // Generate legal pair permutations of A/B/C.
2694 std::vector<TreePatternNode*> ABVariants;
2695 std::vector<TreePatternNode*> BAVariants;
2696 std::vector<TreePatternNode*> ACVariants;
2697 std::vector<TreePatternNode*> CAVariants;
2698 std::vector<TreePatternNode*> BCVariants;
2699 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002700 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2701 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2702 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2703 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2704 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2705 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002706
2707 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002708 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2709 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2710 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2711 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2712 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2713 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002714
2715 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002716 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2717 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2718 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2719 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2720 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2721 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002722 return;
2723 }
2724 }
2725
2726 // Compute permutations of all children.
2727 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2728 ChildVariants.resize(N->getNumChildren());
2729 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002730 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002731
2732 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002733 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002734
2735 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002736 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2737 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2738 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2739 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002740 // Don't count children which are actually register references.
2741 unsigned NC = 0;
2742 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2743 TreePatternNode *Child = N->getChild(i);
2744 if (Child->isLeaf())
2745 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2746 Record *RR = DI->getDef();
2747 if (RR->isSubClassOf("Register"))
2748 continue;
2749 }
2750 NC++;
2751 }
2752 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002753 if (isCommIntrinsic) {
2754 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2755 // operands are the commutative operands, and there might be more operands
2756 // after those.
2757 assert(NC >= 3 &&
2758 "Commutative intrinsic should have at least 3 childrean!");
2759 std::vector<std::vector<TreePatternNode*> > Variants;
2760 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2761 Variants.push_back(ChildVariants[2]);
2762 Variants.push_back(ChildVariants[1]);
2763 for (unsigned i = 3; i != NC; ++i)
2764 Variants.push_back(ChildVariants[i]);
2765 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2766 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002767 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002768 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002769 }
2770}
2771
2772
2773// GenerateVariants - Generate variants. For example, commutative patterns can
2774// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002775void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00002776 DEBUG(errs() << "Generating instruction variants.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002777
2778 // Loop over all of the patterns we've collected, checking to see if we can
2779 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002780 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002781 // the .td file having to contain tons of variants of instructions.
2782 //
2783 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2784 // intentionally do not reconsider these. Any variants of added patterns have
2785 // already been added.
2786 //
2787 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002788 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002789 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002790 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00002791 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00002792 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00002793 DEBUG(errs() << "\n");
Scott Michel327d0652008-03-05 17:49:05 +00002794 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002795
2796 assert(!Variants.empty() && "Must create at least original variant!");
2797 Variants.erase(Variants.begin()); // Remove the original pattern.
2798
2799 if (Variants.empty()) // No variants for this pattern.
2800 continue;
2801
Chris Lattner569f1212009-08-23 04:44:11 +00002802 DEBUG(errs() << "FOUND VARIANTS OF: ";
2803 PatternsToMatch[i].getSrcPattern()->dump();
2804 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002805
2806 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2807 TreePatternNode *Variant = Variants[v];
2808
Chris Lattner569f1212009-08-23 04:44:11 +00002809 DEBUG(errs() << " VAR#" << v << ": ";
2810 Variant->dump();
2811 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002812
2813 // Scan to see if an instruction or explicit pattern already matches this.
2814 bool AlreadyExists = false;
2815 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00002816 // Skip if the top level predicates do not match.
2817 if (PatternsToMatch[i].getPredicates() !=
2818 PatternsToMatch[p].getPredicates())
2819 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00002820 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002821 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00002822 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002823 AlreadyExists = true;
2824 break;
2825 }
2826 }
2827 // If we already have it, ignore the variant.
2828 if (AlreadyExists) continue;
2829
2830 // Otherwise, add it to the list of patterns we have.
2831 PatternsToMatch.
2832 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2833 Variant, PatternsToMatch[i].getDstPattern(),
2834 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002835 PatternsToMatch[i].getAddedComplexity(),
2836 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002837 }
2838
Chris Lattner569f1212009-08-23 04:44:11 +00002839 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002840 }
2841}
2842