blob: fafcd8c30ef9fafcaf3cbe4c021ef40b45b3958d [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
Chris Lattner2cacec52010-03-15 06:00:16 +000028// FIXME: Remove EEVT::isUnknown!
Chris Lattner6cefb772008-01-05 22:25:12 +000029
Owen Anderson825b72b2009-08-11 20:47:22 +000030static inline bool isInteger(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000031 return EVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000032}
33
Owen Anderson825b72b2009-08-11 20:47:22 +000034static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000035 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000036}
37
Owen Anderson825b72b2009-08-11 20:47:22 +000038static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000039 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000040}
41
Chris Lattner2cacec52010-03-15 06:00:16 +000042EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
43 if (VT == MVT::iAny)
44 EnforceInteger(TP);
45 else if (VT == MVT::fAny)
46 EnforceFloatingPoint(TP);
47 else if (VT == MVT::vAny)
48 EnforceVector(TP);
49 else {
50 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
51 VT == MVT::iPTRAny) && "Not a concrete type!");
52 TypeVec.push_back(VT);
53 }
Chris Lattner6cefb772008-01-05 22:25:12 +000054}
55
Chris Lattner2cacec52010-03-15 06:00:16 +000056
57EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
58 assert(!VTList.empty() && "empty list?");
59 TypeVec.append(VTList.begin(), VTList.end());
60
61 if (!VTList.empty())
62 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
63 VTList[0] != MVT::fAny);
64
65 // Remove duplicates.
66 array_pod_sort(TypeVec.begin(), TypeVec.end());
67 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Chris Lattner6cefb772008-01-05 22:25:12 +000068}
69
Chris Lattner2cacec52010-03-15 06:00:16 +000070
71/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
72/// integer value type.
73bool EEVT::TypeSet::hasIntegerTypes() const {
74 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
75 if (isInteger(TypeVec[i]))
76 return true;
77 return false;
78}
79
80/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
81/// a floating point value type.
82bool EEVT::TypeSet::hasFloatingPointTypes() const {
83 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
84 if (isFloatingPoint(TypeVec[i]))
85 return true;
86 return false;
87}
88
89/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
90/// value type.
91bool EEVT::TypeSet::hasVectorTypes() const {
92 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
93 if (isVector(TypeVec[i]))
94 return true;
95 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +000096}
Bob Wilson61fc4cf2009-08-11 01:14:02 +000097
Chris Lattner2cacec52010-03-15 06:00:16 +000098
99std::string EEVT::TypeSet::getName() const {
100 if (TypeVec.empty()) return "isUnknown";
101
102 std::string Result;
103
104 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
105 std::string VTName = llvm::getEnumName(TypeVec[i]);
106 // Strip off MVT:: prefix if present.
107 if (VTName.substr(0,5) == "MVT::")
108 VTName = VTName.substr(5);
109 if (i) Result += ':';
110 Result += VTName;
111 }
112
113 if (TypeVec.size() == 1)
114 return Result;
115 return "{" + Result + "}";
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000116}
Chris Lattner2cacec52010-03-15 06:00:16 +0000117
118/// MergeInTypeInfo - This merges in type information from the specified
119/// argument. If 'this' changes, it returns true. If the two types are
120/// contradictory (e.g. merge f32 into i32) then this throws an exception.
121bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
122 if (InVT.isCompletelyUnknown() || *this == InVT)
123 return false;
124
125 if (isCompletelyUnknown()) {
126 *this = InVT;
127 return true;
128 }
129
130 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
131
132 // Handle the abstract cases, seeing if we can resolve them better.
133 switch (TypeVec[0]) {
134 default: break;
135 case MVT::iPTR:
136 case MVT::iPTRAny:
137 if (InVT.hasIntegerTypes()) {
138 EEVT::TypeSet InCopy(InVT);
139 InCopy.EnforceInteger(TP);
140 InCopy.EnforceScalar(TP);
141
142 if (InCopy.isConcrete()) {
143 // If the RHS has one integer type, upgrade iPTR to i32.
144 TypeVec[0] = InVT.TypeVec[0];
145 return true;
146 }
147
148 // If the input has multiple scalar integers, this doesn't add any info.
149 if (!InCopy.isCompletelyUnknown())
150 return false;
151 }
152 break;
153 }
154
155 // If the input constraint is iAny/iPTR and this is an integer type list,
156 // remove non-integer types from the list.
157 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
158 hasIntegerTypes()) {
159 bool MadeChange = EnforceInteger(TP);
160
161 // If we're merging in iPTR/iPTRAny and the node currently has a list of
162 // multiple different integer types, replace them with a single iPTR.
163 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
164 TypeVec.size() != 1) {
165 TypeVec.resize(1);
166 TypeVec[0] = InVT.TypeVec[0];
167 MadeChange = true;
168 }
169
170 return MadeChange;
171 }
172
173 // If this is a type list and the RHS is a typelist as well, eliminate entries
174 // from this list that aren't in the other one.
175 bool MadeChange = false;
176 TypeSet InputSet(*this);
177
178 for (unsigned i = 0; i != TypeVec.size(); ++i) {
179 bool InInVT = false;
180 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
181 if (TypeVec[i] == InVT.TypeVec[j]) {
182 InInVT = true;
183 break;
184 }
185
186 if (InInVT) continue;
187 TypeVec.erase(TypeVec.begin()+i--);
188 MadeChange = true;
189 }
190
191 // If we removed all of our types, we have a type contradiction.
192 if (!TypeVec.empty())
193 return MadeChange;
194
195 // FIXME: Really want an SMLoc here!
196 TP.error("Type inference contradiction found, merging '" +
197 InVT.getName() + "' into '" + InputSet.getName() + "'");
198 return true; // unreachable
199}
200
201/// EnforceInteger - Remove all non-integer types from this set.
202bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
203 TypeSet InputSet(*this);
204 bool MadeChange = false;
205
206 // If we know nothing, then get the full set.
207 if (TypeVec.empty()) {
208 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
209 MadeChange = true;
210 }
211
212 if (!hasFloatingPointTypes())
213 return MadeChange;
214
215 // Filter out all the fp types.
216 for (unsigned i = 0; i != TypeVec.size(); ++i)
217 if (isFloatingPoint(TypeVec[i]))
218 TypeVec.erase(TypeVec.begin()+i--);
219
220 if (TypeVec.empty())
221 TP.error("Type inference contradiction found, '" +
222 InputSet.getName() + "' needs to be integer");
223 return MadeChange;
224}
225
226/// EnforceFloatingPoint - Remove all integer types from this set.
227bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
228 TypeSet InputSet(*this);
229 bool MadeChange = false;
230
231 // If we know nothing, then get the full set.
232 if (TypeVec.empty()) {
233 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
234 MadeChange = true;
235 }
236
237 if (!hasIntegerTypes())
238 return MadeChange;
239
240 // Filter out all the fp types.
241 for (unsigned i = 0; i != TypeVec.size(); ++i)
242 if (isInteger(TypeVec[i]))
243 TypeVec.erase(TypeVec.begin()+i--);
244
245 if (TypeVec.empty())
246 TP.error("Type inference contradiction found, '" +
247 InputSet.getName() + "' needs to be floating point");
248 return MadeChange;
249}
250
251/// EnforceScalar - Remove all vector types from this.
252bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
253 TypeSet InputSet(*this);
254 bool MadeChange = false;
255
256 // If we know nothing, then get the full set.
257 if (TypeVec.empty()) {
258 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
259 MadeChange = true;
260 }
261
262 if (!hasVectorTypes())
263 return MadeChange;
264
265 // Filter out all the vector types.
266 for (unsigned i = 0; i != TypeVec.size(); ++i)
267 if (isVector(TypeVec[i]))
268 TypeVec.erase(TypeVec.begin()+i--);
269
270 if (TypeVec.empty())
271 TP.error("Type inference contradiction found, '" +
272 InputSet.getName() + "' needs to be scalar");
273 return MadeChange;
274}
275
276/// EnforceVector - Remove all vector types from this.
277bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
278 TypeSet InputSet(*this);
279 bool MadeChange = false;
280
281 // If we know nothing, then get the full set.
282 if (TypeVec.empty()) {
283 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
284 MadeChange = true;
285 }
286
287 // Filter out all the scalar types.
288 for (unsigned i = 0; i != TypeVec.size(); ++i)
289 if (!isVector(TypeVec[i]))
290 TypeVec.erase(TypeVec.begin()+i--);
291
292 if (TypeVec.empty())
293 TP.error("Type inference contradiction found, '" +
294 InputSet.getName() + "' needs to be a vector");
295 return MadeChange;
296}
297
298
299/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
300/// this an other based on this information.
301bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
302 // Both operands must be integer or FP, but we don't care which.
303 bool MadeChange = false;
304
305 // This code does not currently handle nodes which have multiple types,
306 // where some types are integer, and some are fp. Assert that this is not
307 // the case.
308 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
309 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
310 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
311 // If one side is known to be integer or known to be FP but the other side has
312 // no information, get at least the type integrality info in there.
313 if (hasIntegerTypes())
314 MadeChange |= Other.EnforceInteger(TP);
315 else if (hasFloatingPointTypes())
316 MadeChange |= Other.EnforceFloatingPoint(TP);
317 if (Other.hasIntegerTypes())
318 MadeChange |= EnforceInteger(TP);
319 else if (Other.hasFloatingPointTypes())
320 MadeChange |= EnforceFloatingPoint(TP);
321
322 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
323 "Should have a type list now");
324
325 // If one contains vectors but the other doesn't pull vectors out.
326 if (!hasVectorTypes() && Other.hasVectorTypes())
327 MadeChange |= Other.EnforceScalar(TP);
328 if (hasVectorTypes() && !Other.hasVectorTypes())
329 MadeChange |= EnforceScalar(TP);
330
331 // FIXME: This is a bone-headed way to do this.
332
333 // Get the set of legal VTs and filter it based on the known integrality.
334 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
335 TypeSet LegalVTs = CGT.getLegalValueTypes();
336
337 // TODO: If one or the other side is known to be a specific VT, we could prune
338 // LegalVTs.
339 if (hasIntegerTypes())
340 LegalVTs.EnforceInteger(TP);
341 else if (hasFloatingPointTypes())
342 LegalVTs.EnforceFloatingPoint(TP);
343 else
344 return MadeChange;
345
346 switch (LegalVTs.TypeVec.size()) {
347 case 0: assert(0 && "No legal VTs?");
348 default: // Too many VT's to pick from.
349 // TODO: If the biggest type in LegalVTs is in this set, we could remove it.
350 // If one or the other side is known to be a specific VT, we could prune
351 // LegalVTs.
352 return MadeChange;
353 case 1:
354 // Only one VT of this flavor. Cannot ever satisfy the constraints.
355 return MergeInTypeInfo(MVT::Other, TP); // throw
356 case 2:
357 // If we have exactly two possible types, the little operand must be the
358 // small one, the big operand should be the big one. This is common with
359 // float/double for example.
360 assert(LegalVTs.TypeVec[0] < LegalVTs.TypeVec[1] && "Should be sorted!");
361 MadeChange |= MergeInTypeInfo(LegalVTs.TypeVec[0], TP);
362 MadeChange |= Other.MergeInTypeInfo(LegalVTs.TypeVec[1], TP);
363 return MadeChange;
364 }
365}
366
367/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
368/// whose element is VT.
369bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
370 TreePattern &TP) {
371 TypeSet InputSet(*this);
372 bool MadeChange = false;
373
374 // If we know nothing, then get the full set.
375 if (TypeVec.empty()) {
376 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
377 MadeChange = true;
378 }
379
380 // Filter out all the non-vector types and types which don't have the right
381 // element type.
382 for (unsigned i = 0; i != TypeVec.size(); ++i)
383 if (!isVector(TypeVec[i]) ||
384 EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
385 TypeVec.erase(TypeVec.begin()+i--);
386 MadeChange = true;
387 }
388
389 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
390 TP.error("Type inference contradiction found, forcing '" +
391 InputSet.getName() + "' to have a vector element");
392 return MadeChange;
393}
394
395//===----------------------------------------------------------------------===//
396// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000397
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000398bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
399 return LHS->getID() < RHS->getID();
400}
Scott Michel327d0652008-03-05 17:49:05 +0000401
402/// Dependent variable map for CodeGenDAGPattern variant generation
403typedef std::map<std::string, int> DepVarMap;
404
405/// Const iterator shorthand for DepVarMap
406typedef DepVarMap::const_iterator DepVarMap_citer;
407
408namespace {
409void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
410 if (N->isLeaf()) {
411 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
412 DepMap[N->getName()]++;
413 }
414 } else {
415 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
416 FindDepVarsOf(N->getChild(i), DepMap);
417 }
418}
419
420//! Find dependent variables within child patterns
421/*!
422 */
423void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
424 DepVarMap depcounts;
425 FindDepVarsOf(N, depcounts);
426 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
427 if (i->second > 1) { // std::pair<std::string, int>
428 DepVars.insert(i->first);
429 }
430 }
431}
432
433//! Dump the dependent variable set:
434void DumpDepVars(MultipleUseVarSet &DepVars) {
435 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000436 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000437 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000438 DEBUG(errs() << "[ ");
Scott Michel327d0652008-03-05 17:49:05 +0000439 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
440 i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000441 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000442 }
Chris Lattner569f1212009-08-23 04:44:11 +0000443 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000444 }
445}
446}
447
Chris Lattner6cefb772008-01-05 22:25:12 +0000448//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000449// PatternToMatch implementation
450//
451
452/// getPredicateCheck - Return a single string containing all of this
453/// pattern's predicates concatenated with "&&" operators.
454///
455std::string PatternToMatch::getPredicateCheck() const {
456 std::string PredicateCheck;
457 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
458 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
459 Record *Def = Pred->getDef();
460 if (!Def->isSubClassOf("Predicate")) {
461#ifndef NDEBUG
462 Def->dump();
463#endif
464 assert(0 && "Unknown predicate type!");
465 }
466 if (!PredicateCheck.empty())
467 PredicateCheck += " && ";
468 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
469 }
470 }
471
472 return PredicateCheck;
473}
474
475//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000476// SDTypeConstraint implementation
477//
478
479SDTypeConstraint::SDTypeConstraint(Record *R) {
480 OperandNo = R->getValueAsInt("OperandNum");
481
482 if (R->isSubClassOf("SDTCisVT")) {
483 ConstraintType = SDTCisVT;
484 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
485 } else if (R->isSubClassOf("SDTCisPtrTy")) {
486 ConstraintType = SDTCisPtrTy;
487 } else if (R->isSubClassOf("SDTCisInt")) {
488 ConstraintType = SDTCisInt;
489 } else if (R->isSubClassOf("SDTCisFP")) {
490 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000491 } else if (R->isSubClassOf("SDTCisVec")) {
492 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000493 } else if (R->isSubClassOf("SDTCisSameAs")) {
494 ConstraintType = SDTCisSameAs;
495 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
496 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
497 ConstraintType = SDTCisVTSmallerThanOp;
498 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
499 R->getValueAsInt("OtherOperandNum");
500 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
501 ConstraintType = SDTCisOpSmallerThanOp;
502 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
503 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000504 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
505 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000506 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000507 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000508 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000509 exit(1);
510 }
511}
512
513/// getOperandNum - Return the node corresponding to operand #OpNo in tree
514/// N, which has NumResults results.
515TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
516 TreePatternNode *N,
517 unsigned NumResults) const {
518 assert(NumResults <= 1 &&
519 "We only work with nodes with zero or one result so far!");
520
521 if (OpNo >= (NumResults + N->getNumChildren())) {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000522 errs() << "Invalid operand number " << OpNo << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000523 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000524 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000525 exit(1);
526 }
527
528 if (OpNo < NumResults)
529 return N; // FIXME: need value #
530 else
531 return N->getChild(OpNo-NumResults);
532}
533
534/// ApplyTypeConstraint - Given a node in a pattern, apply this type
535/// constraint to the nodes operands. This returns true if it makes a
536/// change, false otherwise. If a type contradiction is found, throw an
537/// exception.
538bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
539 const SDNodeInfo &NodeInfo,
540 TreePattern &TP) const {
541 unsigned NumResults = NodeInfo.getNumResults();
542 assert(NumResults <= 1 &&
543 "We only work with nodes with zero or one result so far!");
544
545 // Check that the number of operands is sane. Negative operands -> varargs.
546 if (NodeInfo.getNumOperands() >= 0) {
547 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
548 TP.error(N->getOperator()->getName() + " node requires exactly " +
549 itostr(NodeInfo.getNumOperands()) + " operands!");
550 }
551
Chris Lattner6cefb772008-01-05 22:25:12 +0000552 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
553
554 switch (ConstraintType) {
555 default: assert(0 && "Unknown constraint type!");
556 case SDTCisVT:
557 // Operand must be a particular type.
558 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000559 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000560 // Operand must be same as target pointer type.
Owen Anderson825b72b2009-08-11 20:47:22 +0000561 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000562 case SDTCisInt:
563 // Require it to be one of the legal integer VTs.
564 return NodeToApply->getExtType().EnforceInteger(TP);
565 case SDTCisFP:
566 // Require it to be one of the legal fp VTs.
567 return NodeToApply->getExtType().EnforceFloatingPoint(TP);
568 case SDTCisVec:
569 // Require it to be one of the legal vector VTs.
570 return NodeToApply->getExtType().EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000571 case SDTCisSameAs: {
572 TreePatternNode *OtherNode =
573 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Chris Lattner2cacec52010-03-15 06:00:16 +0000574 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
575 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000576 }
577 case SDTCisVTSmallerThanOp: {
578 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
579 // have an integer type that is smaller than the VT.
580 if (!NodeToApply->isLeaf() ||
581 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
582 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
583 ->isSubClassOf("ValueType"))
584 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000585 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000586 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Duncan Sands83ec4b62008-06-06 12:08:01 +0000587 if (!isInteger(VT))
Chris Lattner6cefb772008-01-05 22:25:12 +0000588 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
589
590 TreePatternNode *OtherNode =
591 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
592
593 // It must be integer.
Chris Lattner2cacec52010-03-15 06:00:16 +0000594 bool MadeChange = OtherNode->getExtType().EnforceInteger(TP);
595
596 // This doesn't try to enforce any information on the OtherNode, it just
597 // validates it when information is determined.
598 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
Owen Anderson825b72b2009-08-11 20:47:22 +0000599 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
Bill Wendling7529ece2009-12-25 13:35:40 +0000600 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +0000601 }
602 case SDTCisOpSmallerThanOp: {
603 TreePatternNode *BigOperand =
604 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
Chris Lattner2cacec52010-03-15 06:00:16 +0000605 return NodeToApply->getExtType().
606 EnforceSmallerThan(BigOperand->getExtType(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000607 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000608 case SDTCisEltOfVec: {
Chris Lattner2cacec52010-03-15 06:00:16 +0000609 TreePatternNode *VecOperand =
610 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NumResults);
611 if (VecOperand->hasTypeSet()) {
612 if (!isVector(VecOperand->getType()))
Nate Begemanb5af3342008-02-09 01:37:05 +0000613 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Chris Lattner2cacec52010-03-15 06:00:16 +0000614 EVT IVT = VecOperand->getType();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000615 IVT = IVT.getVectorElementType();
Owen Anderson825b72b2009-08-11 20:47:22 +0000616 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000617 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000618
619 if (NodeToApply->hasTypeSet() && VecOperand->getExtType().hasVectorTypes()){
620 // Filter vector types out of VecOperand that don't have the right element
621 // type.
622 return VecOperand->getExtType().
623 EnforceVectorEltTypeIs(NodeToApply->getType(), TP);
624 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000625 return false;
626 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000627 }
628 return false;
629}
630
631//===----------------------------------------------------------------------===//
632// SDNodeInfo implementation
633//
634SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
635 EnumName = R->getValueAsString("Opcode");
636 SDClassName = R->getValueAsString("SDClass");
637 Record *TypeProfile = R->getValueAsDef("TypeProfile");
638 NumResults = TypeProfile->getValueAsInt("NumResults");
639 NumOperands = TypeProfile->getValueAsInt("NumOperands");
640
641 // Parse the properties.
642 Properties = 0;
643 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
644 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
645 if (PropList[i]->getName() == "SDNPCommutative") {
646 Properties |= 1 << SDNPCommutative;
647 } else if (PropList[i]->getName() == "SDNPAssociative") {
648 Properties |= 1 << SDNPAssociative;
649 } else if (PropList[i]->getName() == "SDNPHasChain") {
650 Properties |= 1 << SDNPHasChain;
651 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen874ae252009-06-02 03:12:52 +0000652 Properties |= 1 << SDNPOutFlag;
Chris Lattner6cefb772008-01-05 22:25:12 +0000653 } else if (PropList[i]->getName() == "SDNPInFlag") {
654 Properties |= 1 << SDNPInFlag;
655 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
656 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000657 } else if (PropList[i]->getName() == "SDNPMayStore") {
658 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000659 } else if (PropList[i]->getName() == "SDNPMayLoad") {
660 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000661 } else if (PropList[i]->getName() == "SDNPSideEffect") {
662 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000663 } else if (PropList[i]->getName() == "SDNPMemOperand") {
664 Properties |= 1 << SDNPMemOperand;
Chris Lattner6cefb772008-01-05 22:25:12 +0000665 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000666 errs() << "Unknown SD Node property '" << PropList[i]->getName()
667 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000668 exit(1);
669 }
670 }
671
672
673 // Parse the type constraints.
674 std::vector<Record*> ConstraintList =
675 TypeProfile->getValueAsListOfDefs("Constraints");
676 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
677}
678
Chris Lattner22579812010-02-28 00:22:30 +0000679/// getKnownType - If the type constraints on this node imply a fixed type
680/// (e.g. all stores return void, etc), then return it as an
681/// MVT::SimpleValueType. Otherwise, return EEVT::isUnknown.
682unsigned SDNodeInfo::getKnownType() const {
683 unsigned NumResults = getNumResults();
684 assert(NumResults <= 1 &&
685 "We only work with nodes with zero or one result so far!");
686
687 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
688 // Make sure that this applies to the correct node result.
689 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
690 continue;
691
692 switch (TypeConstraints[i].ConstraintType) {
693 default: break;
694 case SDTypeConstraint::SDTCisVT:
695 return TypeConstraints[i].x.SDTCisVT_Info.VT;
696 case SDTypeConstraint::SDTCisPtrTy:
697 return MVT::iPTR;
698 }
699 }
700 return EEVT::isUnknown;
701}
702
Chris Lattner6cefb772008-01-05 22:25:12 +0000703//===----------------------------------------------------------------------===//
704// TreePatternNode implementation
705//
706
707TreePatternNode::~TreePatternNode() {
708#if 0 // FIXME: implement refcounted tree nodes!
709 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
710 delete getChild(i);
711#endif
712}
713
Chris Lattnerba1cff42010-02-23 07:50:58 +0000714
Chris Lattner6cefb772008-01-05 22:25:12 +0000715
Daniel Dunbar1a551802009-07-03 00:10:29 +0000716void TreePatternNode::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000717 if (isLeaf()) {
718 OS << *getLeafValue();
719 } else {
Chris Lattnerba1cff42010-02-23 07:50:58 +0000720 OS << '(' << getOperator()->getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000721 }
722
Chris Lattner2cacec52010-03-15 06:00:16 +0000723 if (!isTypeCompletelyUnknown())
724 OS << ':' << getExtType().getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000725
726 if (!isLeaf()) {
727 if (getNumChildren() != 0) {
728 OS << " ";
729 getChild(0)->print(OS);
730 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
731 OS << ", ";
732 getChild(i)->print(OS);
733 }
734 }
735 OS << ")";
736 }
737
Dan Gohman0540e172008-10-15 06:17:21 +0000738 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
739 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000740 if (TransformFn)
741 OS << "<<X:" << TransformFn->getName() << ">>";
742 if (!getName().empty())
743 OS << ":$" << getName();
744
745}
746void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000747 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000748}
749
Scott Michel327d0652008-03-05 17:49:05 +0000750/// isIsomorphicTo - Return true if this node is recursively
751/// isomorphic to the specified node. For this comparison, the node's
752/// entire state is considered. The assigned name is ignored, since
753/// nodes with differing names are considered isomorphic. However, if
754/// the assigned name is present in the dependent variable set, then
755/// the assigned name is considered significant and the node is
756/// isomorphic if the names match.
757bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
758 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000759 if (N == this) return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000760 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000761 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000762 getTransformFn() != N->getTransformFn())
763 return false;
764
765 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000766 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
767 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000768 return ((DI->getDef() == NDI->getDef())
769 && (DepVars.find(getName()) == DepVars.end()
770 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000771 }
772 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000773 return getLeafValue() == N->getLeafValue();
774 }
775
776 if (N->getOperator() != getOperator() ||
777 N->getNumChildren() != getNumChildren()) return false;
778 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000779 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000780 return false;
781 return true;
782}
783
784/// clone - Make a copy of this tree and all of its children.
785///
786TreePatternNode *TreePatternNode::clone() const {
787 TreePatternNode *New;
788 if (isLeaf()) {
789 New = new TreePatternNode(getLeafValue());
790 } else {
791 std::vector<TreePatternNode*> CChildren;
792 CChildren.reserve(Children.size());
793 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
794 CChildren.push_back(getChild(i)->clone());
795 New = new TreePatternNode(getOperator(), CChildren);
796 }
797 New->setName(getName());
Chris Lattner2cacec52010-03-15 06:00:16 +0000798 New->setType(getExtType());
Dan Gohman0540e172008-10-15 06:17:21 +0000799 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000800 New->setTransformFn(getTransformFn());
801 return New;
802}
803
Chris Lattner47661322010-02-14 22:22:58 +0000804/// RemoveAllTypes - Recursively strip all the types of this tree.
805void TreePatternNode::RemoveAllTypes() {
Chris Lattner2cacec52010-03-15 06:00:16 +0000806 setType(EEVT::TypeSet()); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +0000807 if (isLeaf()) return;
808 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
809 getChild(i)->RemoveAllTypes();
810}
811
812
Chris Lattner6cefb772008-01-05 22:25:12 +0000813/// SubstituteFormalArguments - Replace the formal arguments in this tree
814/// with actual values specified by ArgMap.
815void TreePatternNode::
816SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
817 if (isLeaf()) return;
818
819 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
820 TreePatternNode *Child = getChild(i);
821 if (Child->isLeaf()) {
822 Init *Val = Child->getLeafValue();
823 if (dynamic_cast<DefInit*>(Val) &&
824 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
825 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000826 TreePatternNode *NewChild = ArgMap[Child->getName()];
827 assert(NewChild && "Couldn't find formal argument!");
828 assert((Child->getPredicateFns().empty() ||
829 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
830 "Non-empty child predicate clobbered!");
831 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000832 }
833 } else {
834 getChild(i)->SubstituteFormalArguments(ArgMap);
835 }
836 }
837}
838
839
840/// InlinePatternFragments - If this pattern refers to any pattern
841/// fragments, inline them into place, giving us a pattern without any
842/// PatFrag references.
843TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
844 if (isLeaf()) return this; // nothing to do.
845 Record *Op = getOperator();
846
847 if (!Op->isSubClassOf("PatFrag")) {
848 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000849 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
850 TreePatternNode *Child = getChild(i);
851 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
852
853 assert((Child->getPredicateFns().empty() ||
854 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
855 "Non-empty child predicate clobbered!");
856
857 setChild(i, NewChild);
858 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000859 return this;
860 }
861
862 // Otherwise, we found a reference to a fragment. First, look up its
863 // TreePattern record.
864 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
865
866 // Verify that we are passing the right number of operands.
867 if (Frag->getNumArgs() != Children.size())
868 TP.error("'" + Op->getName() + "' fragment requires " +
869 utostr(Frag->getNumArgs()) + " operands!");
870
871 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
872
Dan Gohman0540e172008-10-15 06:17:21 +0000873 std::string Code = Op->getValueAsCode("Predicate");
874 if (!Code.empty())
875 FragTree->addPredicateFn("Predicate_"+Op->getName());
876
Chris Lattner6cefb772008-01-05 22:25:12 +0000877 // Resolve formal arguments to their actual value.
878 if (Frag->getNumArgs()) {
879 // Compute the map of formal to actual arguments.
880 std::map<std::string, TreePatternNode*> ArgMap;
881 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
882 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
883
884 FragTree->SubstituteFormalArguments(ArgMap);
885 }
886
887 FragTree->setName(getName());
Chris Lattner2cacec52010-03-15 06:00:16 +0000888 FragTree->UpdateNodeType(getExtType(), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000889
890 // Transfer in the old predicates.
891 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
892 FragTree->addPredicateFn(getPredicateFns()[i]);
893
Chris Lattner6cefb772008-01-05 22:25:12 +0000894 // Get a new copy of this fragment to stitch into here.
895 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000896
897 // The fragment we inlined could have recursive inlining that is needed. See
898 // if there are any pattern fragments in it and inline them as needed.
899 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000900}
901
902/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000903/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +0000904/// references from the register file information, for example.
905///
Chris Lattner2cacec52010-03-15 06:00:16 +0000906static EEVT::TypeSet getImplicitType(Record *R, bool NotRegisters,
907 TreePattern &TP) {
908 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +0000909 if (R->isSubClassOf("RegisterClass")) {
910 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000911 return EEVT::TypeSet(); // Unknown.
912 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
913 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000914 } else if (R->isSubClassOf("PatFrag")) {
915 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +0000916 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +0000917 } else if (R->isSubClassOf("Register")) {
918 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000919 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +0000920 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +0000921 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6cefb772008-01-05 22:25:12 +0000922 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
923 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +0000924 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000925 } else if (R->isSubClassOf("ComplexPattern")) {
926 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000927 return EEVT::TypeSet(); // Unknown.
928 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
929 TP);
Chris Lattnera938ac62009-07-29 20:43:05 +0000930 } else if (R->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000931 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000932 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
933 R->getName() == "zero_reg") {
934 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +0000935 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +0000936 }
937
938 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +0000939 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000940}
941
Chris Lattnere67bde52008-01-06 05:36:50 +0000942
943/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
944/// CodeGenIntrinsic information for it, otherwise return a null pointer.
945const CodeGenIntrinsic *TreePatternNode::
946getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
947 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
948 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
949 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
950 return 0;
951
952 unsigned IID =
953 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
954 return &CDP.getIntrinsicInfo(IID);
955}
956
Chris Lattner47661322010-02-14 22:22:58 +0000957/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
958/// return the ComplexPattern information, otherwise return null.
959const ComplexPattern *
960TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
961 if (!isLeaf()) return 0;
962
963 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
964 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
965 return &CGP.getComplexPattern(DI->getDef());
966 return 0;
967}
968
969/// NodeHasProperty - Return true if this node has the specified property.
970bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +0000971 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +0000972 if (isLeaf()) {
973 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
974 return CP->hasProperty(Property);
975 return false;
976 }
977
978 Record *Operator = getOperator();
979 if (!Operator->isSubClassOf("SDNode")) return false;
980
981 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
982}
983
984
985
986
987/// TreeHasProperty - Return true if any node in this tree has the specified
988/// property.
989bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +0000990 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +0000991 if (NodeHasProperty(Property, CGP))
992 return true;
993 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
994 if (getChild(i)->TreeHasProperty(Property, CGP))
995 return true;
996 return false;
997}
998
Evan Cheng6bd95672008-06-16 20:29:38 +0000999/// isCommutativeIntrinsic - Return true if the node corresponds to a
1000/// commutative intrinsic.
1001bool
1002TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1003 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1004 return Int->isCommutative;
1005 return false;
1006}
1007
Chris Lattnere67bde52008-01-06 05:36:50 +00001008
Bob Wilson6c01ca92009-01-05 17:23:09 +00001009/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001010/// this node and its children in the tree. This returns true if it makes a
1011/// change, false otherwise. If a type contradiction is found, throw an
1012/// exception.
1013bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001014 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001015 if (isLeaf()) {
1016 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1017 // If it's a regclass or something else known, include the type.
1018 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner523f6a52010-02-14 21:10:15 +00001019 }
1020
1021 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001022 // Int inits are always integers. :)
Chris Lattner2cacec52010-03-15 06:00:16 +00001023 bool MadeChange = Type.EnforceInteger(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001024
Chris Lattner2cacec52010-03-15 06:00:16 +00001025 if (!hasTypeSet())
1026 return MadeChange;
1027
1028 MVT::SimpleValueType VT = getType();
1029 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1030 return MadeChange;
1031
1032 unsigned Size = EVT(VT).getSizeInBits();
1033 // Make sure that the value is representable for this type.
1034 if (Size >= 32) return MadeChange;
1035
1036 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1037 if (Val == II->getValue()) return MadeChange;
1038
1039 // If sign-extended doesn't fit, does it fit as unsigned?
1040 unsigned ValueMask;
1041 unsigned UnsignedVal;
1042 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1043 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001044
Chris Lattner2cacec52010-03-15 06:00:16 +00001045 if ((ValueMask & UnsignedVal) == UnsignedVal)
1046 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001047
Chris Lattner2cacec52010-03-15 06:00:16 +00001048 TP.error("Integer value '" + itostr(II->getValue())+
1049 "' is out of range for type '" + getEnumName(getType()) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001050 return MadeChange;
1051 }
1052 return false;
1053 }
1054
1055 // special handling for set, which isn't really an SDNode.
1056 if (getOperator()->getName() == "set") {
1057 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
1058 unsigned NC = getNumChildren();
1059 bool MadeChange = false;
1060 for (unsigned i = 0; i < NC-1; ++i) {
1061 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1062 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
1063
1064 // Types of operands must match.
Chris Lattner2cacec52010-03-15 06:00:16 +00001065 MadeChange |=getChild(i)->UpdateNodeType(getChild(NC-1)->getExtType(),TP);
1066 MadeChange |=getChild(NC-1)->UpdateNodeType(getChild(i)->getExtType(),TP);
1067 MadeChange |=UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001068 }
1069 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001070 }
1071
1072 if (getOperator()->getName() == "implicit" ||
1073 getOperator()->getName() == "parallel") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001074 bool MadeChange = false;
1075 for (unsigned i = 0; i < getNumChildren(); ++i)
1076 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Owen Anderson825b72b2009-08-11 20:47:22 +00001077 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001078 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001079 }
1080
1081 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001082 bool MadeChange = false;
1083 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1084 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner2cacec52010-03-15 06:00:16 +00001085
1086 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1087 // what type it gets, so if it didn't get a concrete type just give it the
1088 // first viable type from the reg class.
1089 if (!getChild(1)->hasTypeSet() &&
1090 !getChild(1)->getExtType().isCompletelyUnknown()) {
1091 MVT::SimpleValueType RCVT = getChild(1)->getExtType().getTypeList()[0];
1092 MadeChange |= getChild(1)->UpdateNodeType(RCVT, TP);
1093 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001094 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001095 }
1096
1097 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001098 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001099
Chris Lattner6cefb772008-01-05 22:25:12 +00001100 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001101 unsigned NumRetVTs = Int->IS.RetVTs.size();
1102 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001103
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001104 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1105 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
1106
1107 if (getNumChildren() != NumParamVTs + NumRetVTs)
Chris Lattnere67bde52008-01-06 05:36:50 +00001108 TP.error("Intrinsic '" + Int->Name + "' expects " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001109 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
1110 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001111
1112 // Apply type info to the intrinsic ID.
Owen Anderson825b72b2009-08-11 20:47:22 +00001113 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001114
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001115 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001116 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
Chris Lattner6cefb772008-01-05 22:25:12 +00001117 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
1118 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1119 }
1120 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001121 }
1122
1123 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001124 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1125
1126 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1127 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1128 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1129 // Branch, etc. do not produce results and top-level forms in instr pattern
1130 // must have void types.
1131 if (NI.getNumResults() == 0)
Owen Anderson825b72b2009-08-11 20:47:22 +00001132 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001133
Chris Lattner6cefb772008-01-05 22:25:12 +00001134 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001135 }
1136
1137 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001138 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001139 unsigned NumResults = Inst.getNumResults();
Chris Lattner6cefb772008-01-05 22:25:12 +00001140 assert(NumResults <= 1 &&
1141 "Only supports zero or one result instrs!");
1142
1143 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001144 CDP.getTargetInfo().getInstruction(getOperator());
Chris Lattner6c6ba362010-03-18 23:15:10 +00001145
1146 EEVT::TypeSet ResultType;
1147
Chris Lattner6cefb772008-01-05 22:25:12 +00001148 // Apply the result type to the node
Chris Lattner6c6ba362010-03-18 23:15:10 +00001149 if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
Chris Lattner6cefb772008-01-05 22:25:12 +00001150 Record *ResultNode = Inst.getResult(0);
1151
Chris Lattnera938ac62009-07-29 20:43:05 +00001152 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00001153 ResultType = EEVT::TypeSet(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001154 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001155 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001156 } else {
1157 assert(ResultNode->isSubClassOf("RegisterClass") &&
1158 "Operands should be register classes!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001159 const CodeGenRegisterClass &RC =
1160 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner6c6ba362010-03-18 23:15:10 +00001161 ResultType = RC.getValueTypes();
Chris Lattner6cefb772008-01-05 22:25:12 +00001162 }
Chris Lattner6c6ba362010-03-18 23:15:10 +00001163 } else if (!InstInfo.ImplicitDefs.empty()) {
1164 // If the instruction has implicit defs, the first one defines the result
1165 // type.
Chris Lattner6c6ba362010-03-18 23:15:10 +00001166 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
Chris Lattner92879532010-03-18 23:57:40 +00001167 assert(FirstImplicitDef->isSubClassOf("Register"));
Chris Lattner6c6ba362010-03-18 23:15:10 +00001168 const std::vector<MVT::SimpleValueType> &RegVTs =
1169 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
Chris Lattner92879532010-03-18 23:57:40 +00001170 if (RegVTs.size() == 1)
Chris Lattner6c6ba362010-03-18 23:15:10 +00001171 ResultType = EEVT::TypeSet(RegVTs);
Chris Lattner92879532010-03-18 23:57:40 +00001172 else
1173 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
Chris Lattner6c6ba362010-03-18 23:15:10 +00001174 } else {
1175 // Otherwise, the instruction produces no value result.
1176 // FIXME: Model "no result" different than "one result that is void"
1177 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001178 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001179
Chris Lattner6c6ba362010-03-18 23:15:10 +00001180 bool MadeChange = UpdateNodeType(ResultType, TP);
1181
Chris Lattner2cacec52010-03-15 06:00:16 +00001182 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1183 // be the same.
1184 if (getOperator()->getName() == "INSERT_SUBREG") {
1185 MadeChange |= UpdateNodeType(getChild(0)->getExtType(), TP);
1186 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1187 }
1188
Chris Lattner6cefb772008-01-05 22:25:12 +00001189
1190 unsigned ChildNo = 0;
1191 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1192 Record *OperandNode = Inst.getOperand(i);
1193
1194 // If the instruction expects a predicate or optional def operand, we
1195 // codegen this by setting the operand to it's default value if it has a
1196 // non-empty DefaultOps field.
1197 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1198 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1199 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1200 continue;
1201
1202 // Verify that we didn't run out of provided operands.
1203 if (ChildNo >= getNumChildren())
1204 TP.error("Instruction '" + getOperator()->getName() +
1205 "' expects more operands than were provided.");
1206
Owen Anderson825b72b2009-08-11 20:47:22 +00001207 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001208 TreePatternNode *Child = getChild(ChildNo++);
1209 if (OperandNode->isSubClassOf("RegisterClass")) {
1210 const CodeGenRegisterClass &RC =
1211 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner2cacec52010-03-15 06:00:16 +00001212 MadeChange |= Child->UpdateNodeType(RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001213 } else if (OperandNode->isSubClassOf("Operand")) {
1214 VT = getValueType(OperandNode->getValueAsDef("Type"));
1215 MadeChange |= Child->UpdateNodeType(VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001216 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001217 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001218 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001219 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001220 } else {
1221 assert(0 && "Unknown operand type!");
1222 abort();
1223 }
1224 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1225 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001226
Christopher Lamb02f69372008-03-10 04:16:09 +00001227 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001228 TP.error("Instruction '" + getOperator()->getName() +
1229 "' was provided too many operands!");
1230
1231 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001232 }
Chris Lattner6eb30122010-02-23 05:51:07 +00001233
1234 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1235
1236 // Node transforms always take one operand.
1237 if (getNumChildren() != 1)
1238 TP.error("Node transform '" + getOperator()->getName() +
1239 "' requires one operand!");
1240
Chris Lattner2cacec52010-03-15 06:00:16 +00001241 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1242
1243
Chris Lattner6eb30122010-02-23 05:51:07 +00001244 // If either the output or input of the xform does not have exact
1245 // type info. We assume they must be the same. Otherwise, it is perfectly
1246 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001247#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001248 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001249 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1250 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001251 return MadeChange;
1252 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001253#endif
1254 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001255}
1256
1257/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1258/// RHS of a commutative operation, not the on LHS.
1259static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1260 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1261 return true;
1262 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1263 return true;
1264 return false;
1265}
1266
1267
1268/// canPatternMatch - If it is impossible for this pattern to match on this
1269/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001270/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001271/// that can never possibly work), and to prevent the pattern permuter from
1272/// generating stuff that is useless.
1273bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001274 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001275 if (isLeaf()) return true;
1276
1277 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1278 if (!getChild(i)->canPatternMatch(Reason, CDP))
1279 return false;
1280
1281 // If this is an intrinsic, handle cases that would make it not match. For
1282 // example, if an operand is required to be an immediate.
1283 if (getOperator()->isSubClassOf("Intrinsic")) {
1284 // TODO:
1285 return true;
1286 }
1287
1288 // If this node is a commutative operator, check that the LHS isn't an
1289 // immediate.
1290 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001291 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1292 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001293 // Scan all of the operands of the node and make sure that only the last one
1294 // is a constant node, unless the RHS also is.
1295 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001296 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1297 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001298 if (OnlyOnRHSOfCommutative(getChild(i))) {
1299 Reason="Immediate value must be on the RHS of commutative operators!";
1300 return false;
1301 }
1302 }
1303 }
1304
1305 return true;
1306}
1307
1308//===----------------------------------------------------------------------===//
1309// TreePattern implementation
1310//
1311
1312TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001313 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001314 isInputPattern = isInput;
1315 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1316 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001317}
1318
1319TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001320 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001321 isInputPattern = isInput;
1322 Trees.push_back(ParseTreePattern(Pat));
1323}
1324
1325TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001326 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001327 isInputPattern = isInput;
1328 Trees.push_back(Pat);
1329}
1330
Chris Lattner6cefb772008-01-05 22:25:12 +00001331void TreePattern::error(const std::string &Msg) const {
1332 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001333 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001334}
1335
Chris Lattner2cacec52010-03-15 06:00:16 +00001336void TreePattern::ComputeNamedNodes() {
1337 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1338 ComputeNamedNodes(Trees[i]);
1339}
1340
1341void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1342 if (!N->getName().empty())
1343 NamedNodes[N->getName()].push_back(N);
1344
1345 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1346 ComputeNamedNodes(N->getChild(i));
1347}
1348
Chris Lattner6cefb772008-01-05 22:25:12 +00001349TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1350 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1351 if (!OpDef) error("Pattern has unexpected operator type!");
1352 Record *Operator = OpDef->getDef();
1353
1354 if (Operator->isSubClassOf("ValueType")) {
1355 // If the operator is a ValueType, then this must be "type cast" of a leaf
1356 // node.
1357 if (Dag->getNumArgs() != 1)
1358 error("Type cast only takes one operand!");
1359
1360 Init *Arg = Dag->getArg(0);
1361 TreePatternNode *New;
1362 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1363 Record *R = DI->getDef();
1364 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001365 Dag->setArg(0, new DagInit(DI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001366 std::vector<std::pair<Init*, std::string> >()));
1367 return ParseTreePattern(Dag);
1368 }
Chris Lattner43e47542010-03-08 18:36:19 +00001369
1370 // Input argument?
1371 if (R->getName() == "node") {
1372 if (Dag->getArgName(0).empty())
1373 error("'node' argument requires a name to match with operand list");
1374 Args.push_back(Dag->getArgName(0));
1375 }
1376
Chris Lattner6cefb772008-01-05 22:25:12 +00001377 New = new TreePatternNode(DI);
1378 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1379 New = ParseTreePattern(DI);
1380 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1381 New = new TreePatternNode(II);
1382 if (!Dag->getArgName(0).empty())
1383 error("Constant int argument should not have a name!");
1384 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1385 // Turn this into an IntInit.
1386 Init *II = BI->convertInitializerTo(new IntRecTy());
1387 if (II == 0 || !dynamic_cast<IntInit*>(II))
1388 error("Bits value must be constants!");
1389
1390 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1391 if (!Dag->getArgName(0).empty())
1392 error("Constant int argument should not have a name!");
1393 } else {
1394 Arg->dump();
1395 error("Unknown leaf value for tree pattern!");
1396 return 0;
1397 }
1398
1399 // Apply the type cast.
1400 New->UpdateNodeType(getValueType(Operator), *this);
Nate Begeman7cee8172009-03-19 05:21:56 +00001401 if (New->getNumChildren() == 0)
1402 New->setName(Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001403 return New;
1404 }
1405
1406 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001407 if (!Operator->isSubClassOf("PatFrag") &&
1408 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001409 !Operator->isSubClassOf("Instruction") &&
1410 !Operator->isSubClassOf("SDNodeXForm") &&
1411 !Operator->isSubClassOf("Intrinsic") &&
1412 Operator->getName() != "set" &&
1413 Operator->getName() != "implicit" &&
1414 Operator->getName() != "parallel")
1415 error("Unrecognized node '" + Operator->getName() + "'!");
1416
1417 // Check to see if this is something that is illegal in an input pattern.
1418 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1419 Operator->isSubClassOf("SDNodeXForm")))
1420 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1421
1422 std::vector<TreePatternNode*> Children;
1423
1424 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1425 Init *Arg = Dag->getArg(i);
1426 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1427 Children.push_back(ParseTreePattern(DI));
1428 if (Children.back()->getName().empty())
1429 Children.back()->setName(Dag->getArgName(i));
1430 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1431 Record *R = DefI->getDef();
1432 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1433 // TreePatternNode if its own.
1434 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001435 Dag->setArg(i, new DagInit(DefI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001436 std::vector<std::pair<Init*, std::string> >()));
1437 --i; // Revisit this node...
1438 } else {
1439 TreePatternNode *Node = new TreePatternNode(DefI);
1440 Node->setName(Dag->getArgName(i));
1441 Children.push_back(Node);
1442
1443 // Input argument?
1444 if (R->getName() == "node") {
1445 if (Dag->getArgName(i).empty())
1446 error("'node' argument requires a name to match with operand list");
1447 Args.push_back(Dag->getArgName(i));
1448 }
1449 }
1450 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1451 TreePatternNode *Node = new TreePatternNode(II);
1452 if (!Dag->getArgName(i).empty())
1453 error("Constant int argument should not have a name!");
1454 Children.push_back(Node);
1455 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1456 // Turn this into an IntInit.
1457 Init *II = BI->convertInitializerTo(new IntRecTy());
1458 if (II == 0 || !dynamic_cast<IntInit*>(II))
1459 error("Bits value must be constants!");
1460
1461 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1462 if (!Dag->getArgName(i).empty())
1463 error("Constant int argument should not have a name!");
1464 Children.push_back(Node);
1465 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001466 errs() << '"';
Chris Lattner6cefb772008-01-05 22:25:12 +00001467 Arg->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001468 errs() << "\": ";
Chris Lattner6cefb772008-01-05 22:25:12 +00001469 error("Unknown leaf value for tree pattern!");
1470 }
1471 }
1472
1473 // If the operator is an intrinsic, then this is just syntactic sugar for for
1474 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1475 // convert the intrinsic name to a number.
1476 if (Operator->isSubClassOf("Intrinsic")) {
1477 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1478 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1479
1480 // If this intrinsic returns void, it must have side-effects and thus a
1481 // chain.
Owen Anderson825b72b2009-08-11 20:47:22 +00001482 if (Int.IS.RetVTs[0] == MVT::isVoid) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001483 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1484 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1485 // Has side-effects, requires chain.
1486 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1487 } else {
1488 // Otherwise, no chain.
1489 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1490 }
1491
1492 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1493 Children.insert(Children.begin(), IIDNode);
1494 }
1495
Nate Begeman7cee8172009-03-19 05:21:56 +00001496 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1497 Result->setName(Dag->getName());
1498 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001499}
1500
1501/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001502/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001503/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001504bool TreePattern::
1505InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1506 if (NamedNodes.empty())
1507 ComputeNamedNodes();
1508
Chris Lattner6cefb772008-01-05 22:25:12 +00001509 bool MadeChange = true;
1510 while (MadeChange) {
1511 MadeChange = false;
1512 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1513 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner2cacec52010-03-15 06:00:16 +00001514
1515 // If there are constraints on our named nodes, apply them.
1516 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1517 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1518 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1519
1520 // If we have input named node types, propagate their types to the named
1521 // values here.
1522 if (InNamedTypes) {
1523 // FIXME: Should be error?
1524 assert(InNamedTypes->count(I->getKey()) &&
1525 "Named node in output pattern but not input pattern?");
1526
1527 const SmallVectorImpl<TreePatternNode*> &InNodes =
1528 InNamedTypes->find(I->getKey())->second;
1529
1530 // The input types should be fully resolved by now.
1531 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1532 // If this node is a register class, and it is the root of the pattern
1533 // then we're mapping something onto an input register. We allow
1534 // changing the type of the input register in this case. This allows
1535 // us to match things like:
1536 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1537 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1538 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1539 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1540 continue;
1541 }
1542
1543 MadeChange |=Nodes[i]->UpdateNodeType(InNodes[0]->getExtType(),*this);
1544 }
1545 }
1546
1547 // If there are multiple nodes with the same name, they must all have the
1548 // same type.
1549 if (I->second.size() > 1) {
1550 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1551 MadeChange |=Nodes[i]->UpdateNodeType(Nodes[i+1]->getExtType(),*this);
1552 MadeChange |=Nodes[i+1]->UpdateNodeType(Nodes[i]->getExtType(),*this);
1553 }
1554 }
1555 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001556 }
1557
1558 bool HasUnresolvedTypes = false;
1559 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1560 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1561 return !HasUnresolvedTypes;
1562}
1563
Daniel Dunbar1a551802009-07-03 00:10:29 +00001564void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001565 OS << getRecord()->getName();
1566 if (!Args.empty()) {
1567 OS << "(" << Args[0];
1568 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1569 OS << ", " << Args[i];
1570 OS << ")";
1571 }
1572 OS << ": ";
1573
1574 if (Trees.size() > 1)
1575 OS << "[\n";
1576 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1577 OS << "\t";
1578 Trees[i]->print(OS);
1579 OS << "\n";
1580 }
1581
1582 if (Trees.size() > 1)
1583 OS << "]\n";
1584}
1585
Daniel Dunbar1a551802009-07-03 00:10:29 +00001586void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001587
1588//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001589// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001590//
1591
Chris Lattnerfe718932008-01-06 01:10:31 +00001592CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001593 Intrinsics = LoadIntrinsics(Records, false);
1594 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001595 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001596 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001597 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001598 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001599 ParseDefaultOperands();
1600 ParseInstructions();
1601 ParsePatterns();
1602
1603 // Generate variants. For example, commutative patterns can match
1604 // multiple ways. Add them to PatternsToMatch as well.
1605 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001606
1607 // Infer instruction flags. For example, we can detect loads,
1608 // stores, and side effects in many cases by examining an
1609 // instruction's pattern.
1610 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001611}
1612
Chris Lattnerfe718932008-01-06 01:10:31 +00001613CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001614 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001615 E = PatternFragments.end(); I != E; ++I)
1616 delete I->second;
1617}
1618
1619
Chris Lattnerfe718932008-01-06 01:10:31 +00001620Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001621 Record *N = Records.getDef(Name);
1622 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001623 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001624 exit(1);
1625 }
1626 return N;
1627}
1628
1629// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001630void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001631 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1632 while (!Nodes.empty()) {
1633 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1634 Nodes.pop_back();
1635 }
1636
Jim Grosbachda4231f2009-03-26 16:17:51 +00001637 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001638 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1639 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1640 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1641}
1642
1643/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1644/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001645void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001646 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1647 while (!Xforms.empty()) {
1648 Record *XFormNode = Xforms.back();
1649 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1650 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001651 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001652
1653 Xforms.pop_back();
1654 }
1655}
1656
Chris Lattnerfe718932008-01-06 01:10:31 +00001657void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001658 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1659 while (!AMs.empty()) {
1660 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1661 AMs.pop_back();
1662 }
1663}
1664
1665
1666/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1667/// file, building up the PatternFragments map. After we've collected them all,
1668/// inline fragments together as necessary, so that there are no references left
1669/// inside a pattern fragment to a pattern fragment.
1670///
Chris Lattnerfe718932008-01-06 01:10:31 +00001671void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001672 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1673
Chris Lattnerdc32f982008-01-05 22:43:57 +00001674 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001675 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1676 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1677 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1678 PatternFragments[Fragments[i]] = P;
1679
Chris Lattnerdc32f982008-01-05 22:43:57 +00001680 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001681 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001682 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001683
Chris Lattnerdc32f982008-01-05 22:43:57 +00001684 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001685 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1686
1687 // Parse the operands list.
1688 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1689 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1690 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001691 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001692 if (!OpsOp ||
1693 (OpsOp->getDef()->getName() != "ops" &&
1694 OpsOp->getDef()->getName() != "outs" &&
1695 OpsOp->getDef()->getName() != "ins"))
1696 P->error("Operands list should start with '(ops ... '!");
1697
1698 // Copy over the arguments.
1699 Args.clear();
1700 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1701 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1702 static_cast<DefInit*>(OpsList->getArg(j))->
1703 getDef()->getName() != "node")
1704 P->error("Operands list should all be 'node' values.");
1705 if (OpsList->getArgName(j).empty())
1706 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001707 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001708 P->error("'" + OpsList->getArgName(j) +
1709 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001710 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001711 Args.push_back(OpsList->getArgName(j));
1712 }
1713
Chris Lattnerdc32f982008-01-05 22:43:57 +00001714 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001715 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001716 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001717
Chris Lattnerdc32f982008-01-05 22:43:57 +00001718 // If there is a code init for this fragment, keep track of the fact that
1719 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001720 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001721 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001722 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001723
1724 // If there is a node transformation corresponding to this, keep track of
1725 // it.
1726 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1727 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1728 P->getOnlyTree()->setTransformFn(Transform);
1729 }
1730
Chris Lattner6cefb772008-01-05 22:25:12 +00001731 // Now that we've parsed all of the tree fragments, do a closure on them so
1732 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001733 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1734 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001735 ThePat->InlinePatternFragments();
1736
1737 // Infer as many types as possible. Don't worry about it if we don't infer
1738 // all of them, some may depend on the inputs of the pattern.
1739 try {
1740 ThePat->InferAllTypes();
1741 } catch (...) {
1742 // If this pattern fragment is not supported by this target (no types can
1743 // satisfy its constraints), just ignore it. If the bogus pattern is
1744 // actually used by instructions, the type consistency error will be
1745 // reported there.
1746 }
1747
1748 // If debugging, print out the pattern fragment result.
1749 DEBUG(ThePat->dump());
1750 }
1751}
1752
Chris Lattnerfe718932008-01-06 01:10:31 +00001753void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001754 std::vector<Record*> DefaultOps[2];
1755 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1756 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1757
1758 // Find some SDNode.
1759 assert(!SDNodes.empty() && "No SDNodes parsed?");
1760 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1761
1762 for (unsigned iter = 0; iter != 2; ++iter) {
1763 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1764 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1765
1766 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1767 // SomeSDnode so that we can parse this.
1768 std::vector<std::pair<Init*, std::string> > Ops;
1769 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1770 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1771 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001772 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001773
1774 // Create a TreePattern to parse this.
1775 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1776 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1777
1778 // Copy the operands over into a DAGDefaultOperand.
1779 DAGDefaultOperand DefaultOpInfo;
1780
1781 TreePatternNode *T = P.getTree(0);
1782 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1783 TreePatternNode *TPN = T->getChild(op);
1784 while (TPN->ApplyTypeConstraints(P, false))
1785 /* Resolve all types */;
1786
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001787 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001788 if (iter == 0)
1789 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001790 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00001791 else
1792 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001793 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001794 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001795 DefaultOpInfo.DefaultOps.push_back(TPN);
1796 }
1797
1798 // Insert it into the DefaultOperands map so we can find it later.
1799 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1800 }
1801 }
1802}
1803
1804/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1805/// instruction input. Return true if this is a real use.
1806static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1807 std::map<std::string, TreePatternNode*> &InstInputs,
1808 std::vector<Record*> &InstImpInputs) {
1809 // No name -> not interesting.
1810 if (Pat->getName().empty()) {
1811 if (Pat->isLeaf()) {
1812 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1813 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1814 I->error("Input " + DI->getDef()->getName() + " must be named!");
1815 else if (DI && DI->getDef()->isSubClassOf("Register"))
1816 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001817 }
1818 return false;
1819 }
1820
1821 Record *Rec;
1822 if (Pat->isLeaf()) {
1823 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1824 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1825 Rec = DI->getDef();
1826 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001827 Rec = Pat->getOperator();
1828 }
1829
1830 // SRCVALUE nodes are ignored.
1831 if (Rec->getName() == "srcvalue")
1832 return false;
1833
1834 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1835 if (!Slot) {
1836 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00001837 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00001838 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00001839 Record *SlotRec;
1840 if (Slot->isLeaf()) {
1841 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1842 } else {
1843 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1844 SlotRec = Slot->getOperator();
1845 }
1846
1847 // Ensure that the inputs agree if we've already seen this input.
1848 if (Rec != SlotRec)
1849 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner2cacec52010-03-15 06:00:16 +00001850 if (Slot->getExtType() != Pat->getExtType())
Chris Lattner53d09bd2010-02-23 05:59:10 +00001851 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00001852 return true;
1853}
1854
1855/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1856/// part of "I", the instruction), computing the set of inputs and outputs of
1857/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001858void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001859FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1860 std::map<std::string, TreePatternNode*> &InstInputs,
1861 std::map<std::string, TreePatternNode*>&InstResults,
1862 std::vector<Record*> &InstImpInputs,
1863 std::vector<Record*> &InstImpResults) {
1864 if (Pat->isLeaf()) {
1865 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1866 if (!isUse && Pat->getTransformFn())
1867 I->error("Cannot specify a transform function for a non-input value!");
1868 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001869 }
1870
1871 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001872 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1873 TreePatternNode *Dest = Pat->getChild(i);
1874 if (!Dest->isLeaf())
1875 I->error("implicitly defined value should be a register!");
1876
1877 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1878 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1879 I->error("implicitly defined value should be a register!");
1880 InstImpResults.push_back(Val->getDef());
1881 }
1882 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001883 }
1884
1885 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001886 // If this is not a set, verify that the children nodes are not void typed,
1887 // and recurse.
1888 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001889 if (Pat->getChild(i)->getType() == MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00001890 I->error("Cannot have void nodes inside of patterns!");
1891 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1892 InstImpInputs, InstImpResults);
1893 }
1894
1895 // If this is a non-leaf node with no children, treat it basically as if
1896 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00001897 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00001898
1899 if (!isUse && Pat->getTransformFn())
1900 I->error("Cannot specify a transform function for a non-input value!");
1901 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001902 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001903
1904 // Otherwise, this is a set, validate and collect instruction results.
1905 if (Pat->getNumChildren() == 0)
1906 I->error("set requires operands!");
1907
1908 if (Pat->getTransformFn())
1909 I->error("Cannot specify a transform function on a set node!");
1910
1911 // Check the set destinations.
1912 unsigned NumDests = Pat->getNumChildren()-1;
1913 for (unsigned i = 0; i != NumDests; ++i) {
1914 TreePatternNode *Dest = Pat->getChild(i);
1915 if (!Dest->isLeaf())
1916 I->error("set destination should be a register!");
1917
1918 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1919 if (!Val)
1920 I->error("set destination should be a register!");
1921
1922 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00001923 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001924 if (Dest->getName().empty())
1925 I->error("set destination must have a name!");
1926 if (InstResults.count(Dest->getName()))
1927 I->error("cannot set '" + Dest->getName() +"' multiple times");
1928 InstResults[Dest->getName()] = Dest;
1929 } else if (Val->getDef()->isSubClassOf("Register")) {
1930 InstImpResults.push_back(Val->getDef());
1931 } else {
1932 I->error("set destination should be a register!");
1933 }
1934 }
1935
1936 // Verify and collect info from the computation.
1937 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1938 InstInputs, InstResults,
1939 InstImpInputs, InstImpResults);
1940}
1941
Dan Gohmanee4fa192008-04-03 00:02:49 +00001942//===----------------------------------------------------------------------===//
1943// Instruction Analysis
1944//===----------------------------------------------------------------------===//
1945
1946class InstAnalyzer {
1947 const CodeGenDAGPatterns &CDP;
1948 bool &mayStore;
1949 bool &mayLoad;
1950 bool &HasSideEffects;
1951public:
1952 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1953 bool &maystore, bool &mayload, bool &hse)
1954 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1955 }
1956
1957 /// Analyze - Analyze the specified instruction, returning true if the
1958 /// instruction had a pattern.
1959 bool Analyze(Record *InstRecord) {
1960 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1961 if (Pattern == 0) {
1962 HasSideEffects = 1;
1963 return false; // No pattern.
1964 }
1965
1966 // FIXME: Assume only the first tree is the pattern. The others are clobber
1967 // nodes.
1968 AnalyzeNode(Pattern->getTree(0));
1969 return true;
1970 }
1971
1972private:
1973 void AnalyzeNode(const TreePatternNode *N) {
1974 if (N->isLeaf()) {
1975 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1976 Record *LeafRec = DI->getDef();
1977 // Handle ComplexPattern leaves.
1978 if (LeafRec->isSubClassOf("ComplexPattern")) {
1979 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1980 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1981 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1982 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1983 }
1984 }
1985 return;
1986 }
1987
1988 // Analyze children.
1989 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1990 AnalyzeNode(N->getChild(i));
1991
1992 // Ignore set nodes, which are not SDNodes.
1993 if (N->getOperator()->getName() == "set")
1994 return;
1995
1996 // Get information about the SDNode for the operator.
1997 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1998
1999 // Notice properties of the node.
2000 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2001 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2002 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2003
2004 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2005 // If this is an intrinsic, analyze it.
2006 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2007 mayLoad = true;// These may load memory.
2008
2009 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2010 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2011
2012 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2013 // WriteMem intrinsics can have other strange effects.
2014 HasSideEffects = true;
2015 }
2016 }
2017
2018};
2019
2020static void InferFromPattern(const CodeGenInstruction &Inst,
2021 bool &MayStore, bool &MayLoad,
2022 bool &HasSideEffects,
2023 const CodeGenDAGPatterns &CDP) {
2024 MayStore = MayLoad = HasSideEffects = false;
2025
2026 bool HadPattern =
2027 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
2028
2029 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2030 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2031 // If we decided that this is a store from the pattern, then the .td file
2032 // entry is redundant.
2033 if (MayStore)
2034 fprintf(stderr,
2035 "Warning: mayStore flag explicitly set on instruction '%s'"
2036 " but flag already inferred from pattern.\n",
2037 Inst.TheDef->getName().c_str());
2038 MayStore = true;
2039 }
2040
2041 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2042 // If we decided that this is a load from the pattern, then the .td file
2043 // entry is redundant.
2044 if (MayLoad)
2045 fprintf(stderr,
2046 "Warning: mayLoad flag explicitly set on instruction '%s'"
2047 " but flag already inferred from pattern.\n",
2048 Inst.TheDef->getName().c_str());
2049 MayLoad = true;
2050 }
2051
2052 if (Inst.neverHasSideEffects) {
2053 if (HadPattern)
2054 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2055 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2056 HasSideEffects = false;
2057 }
2058
2059 if (Inst.hasSideEffects) {
2060 if (HasSideEffects)
2061 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2062 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2063 HasSideEffects = true;
2064 }
2065}
2066
Chris Lattner6cefb772008-01-05 22:25:12 +00002067/// ParseInstructions - Parse all of the instructions, inlining and resolving
2068/// any fragments involved. This populates the Instructions list with fully
2069/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002070void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002071 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2072
2073 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2074 ListInit *LI = 0;
2075
2076 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2077 LI = Instrs[i]->getValueAsListInit("Pattern");
2078
2079 // If there is no pattern, only collect minimal information about the
2080 // instruction for its operand list. We have to assume that there is one
2081 // result, as we have no detailed info.
2082 if (!LI || LI->getSize() == 0) {
2083 std::vector<Record*> Results;
2084 std::vector<Record*> Operands;
2085
Chris Lattnerf30187a2010-03-19 00:07:20 +00002086 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002087
2088 if (InstInfo.OperandList.size() != 0) {
2089 if (InstInfo.NumDefs == 0) {
2090 // These produce no results
2091 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2092 Operands.push_back(InstInfo.OperandList[j].Rec);
2093 } else {
2094 // Assume the first operand is the result.
2095 Results.push_back(InstInfo.OperandList[0].Rec);
2096
2097 // The rest are inputs.
2098 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2099 Operands.push_back(InstInfo.OperandList[j].Rec);
2100 }
2101 }
2102
2103 // Create and insert the instruction.
2104 std::vector<Record*> ImpResults;
2105 std::vector<Record*> ImpOperands;
2106 Instructions.insert(std::make_pair(Instrs[i],
2107 DAGInstruction(0, Results, Operands, ImpResults,
2108 ImpOperands)));
2109 continue; // no pattern.
2110 }
2111
2112 // Parse the instruction.
2113 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2114 // Inline pattern fragments into it.
2115 I->InlinePatternFragments();
2116
2117 // Infer as many types as possible. If we cannot infer all of them, we can
2118 // never do anything with this instruction pattern: report it to the user.
2119 if (!I->InferAllTypes())
2120 I->error("Could not infer all types in pattern!");
2121
2122 // InstInputs - Keep track of all of the inputs of the instruction, along
2123 // with the record they are declared as.
2124 std::map<std::string, TreePatternNode*> InstInputs;
2125
2126 // InstResults - Keep track of all the virtual registers that are 'set'
2127 // in the instruction, including what reg class they are.
2128 std::map<std::string, TreePatternNode*> InstResults;
2129
2130 std::vector<Record*> InstImpInputs;
2131 std::vector<Record*> InstImpResults;
2132
2133 // Verify that the top-level forms in the instruction are of void type, and
2134 // fill in the InstResults map.
2135 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2136 TreePatternNode *Pat = I->getTree(j);
Chris Lattner2cacec52010-03-15 06:00:16 +00002137 if (!Pat->hasTypeSet() || Pat->getType() != MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00002138 I->error("Top-level forms in instruction pattern should have"
2139 " void types");
2140
2141 // Find inputs and outputs, and verify the structure of the uses/defs.
2142 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2143 InstImpInputs, InstImpResults);
2144 }
2145
2146 // Now that we have inputs and outputs of the pattern, inspect the operands
2147 // list for the instruction. This determines the order that operands are
2148 // added to the machine instruction the node corresponds to.
2149 unsigned NumResults = InstResults.size();
2150
2151 // Parse the operands list from the (ops) list, validating it.
2152 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002153 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002154
2155 // Check that all of the results occur first in the list.
2156 std::vector<Record*> Results;
2157 TreePatternNode *Res0Node = NULL;
2158 for (unsigned i = 0; i != NumResults; ++i) {
2159 if (i == CGI.OperandList.size())
2160 I->error("'" + InstResults.begin()->first +
2161 "' set but does not appear in operand list!");
2162 const std::string &OpName = CGI.OperandList[i].Name;
2163
2164 // Check that it exists in InstResults.
2165 TreePatternNode *RNode = InstResults[OpName];
2166 if (RNode == 0)
2167 I->error("Operand $" + OpName + " does not exist in operand list!");
2168
2169 if (i == 0)
2170 Res0Node = RNode;
2171 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2172 if (R == 0)
2173 I->error("Operand $" + OpName + " should be a set destination: all "
2174 "outputs must occur before inputs in operand list!");
2175
2176 if (CGI.OperandList[i].Rec != R)
2177 I->error("Operand $" + OpName + " class mismatch!");
2178
2179 // Remember the return type.
2180 Results.push_back(CGI.OperandList[i].Rec);
2181
2182 // Okay, this one checks out.
2183 InstResults.erase(OpName);
2184 }
2185
2186 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2187 // the copy while we're checking the inputs.
2188 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2189
2190 std::vector<TreePatternNode*> ResultNodeOperands;
2191 std::vector<Record*> Operands;
2192 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2193 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2194 const std::string &OpName = Op.Name;
2195 if (OpName.empty())
2196 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2197
2198 if (!InstInputsCheck.count(OpName)) {
2199 // If this is an predicate operand or optional def operand with an
2200 // DefaultOps set filled in, we can ignore this. When we codegen it,
2201 // we will do so as always executed.
2202 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2203 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2204 // Does it have a non-empty DefaultOps field? If so, ignore this
2205 // operand.
2206 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2207 continue;
2208 }
2209 I->error("Operand $" + OpName +
2210 " does not appear in the instruction pattern");
2211 }
2212 TreePatternNode *InVal = InstInputsCheck[OpName];
2213 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2214
2215 if (InVal->isLeaf() &&
2216 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2217 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2218 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2219 I->error("Operand $" + OpName + "'s register class disagrees"
2220 " between the operand and pattern");
2221 }
2222 Operands.push_back(Op.Rec);
2223
2224 // Construct the result for the dest-pattern operand list.
2225 TreePatternNode *OpNode = InVal->clone();
2226
2227 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002228 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00002229
2230 // Promote the xform function to be an explicit node if set.
2231 if (Record *Xform = OpNode->getTransformFn()) {
2232 OpNode->setTransformFn(0);
2233 std::vector<TreePatternNode*> Children;
2234 Children.push_back(OpNode);
2235 OpNode = new TreePatternNode(Xform, Children);
2236 }
2237
2238 ResultNodeOperands.push_back(OpNode);
2239 }
2240
2241 if (!InstInputsCheck.empty())
2242 I->error("Input operand $" + InstInputsCheck.begin()->first +
2243 " occurs in pattern but not in operands list!");
2244
2245 TreePatternNode *ResultPattern =
2246 new TreePatternNode(I->getRecord(), ResultNodeOperands);
2247 // Copy fully inferred output node type to instruction result pattern.
2248 if (NumResults > 0)
Chris Lattner2cacec52010-03-15 06:00:16 +00002249 ResultPattern->setType(Res0Node->getExtType());
Chris Lattner6cefb772008-01-05 22:25:12 +00002250
2251 // Create and insert the instruction.
2252 // FIXME: InstImpResults and InstImpInputs should not be part of
2253 // DAGInstruction.
2254 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2255 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2256
2257 // Use a temporary tree pattern to infer all types and make sure that the
2258 // constructed result is correct. This depends on the instruction already
2259 // being inserted into the Instructions map.
2260 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002261 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002262
2263 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2264 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2265
2266 DEBUG(I->dump());
2267 }
2268
2269 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002270 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2271 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002272 E = Instructions.end(); II != E; ++II) {
2273 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002274 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002275 if (I == 0) continue; // No pattern.
2276
2277 // FIXME: Assume only the first tree is the pattern. The others are clobber
2278 // nodes.
2279 TreePatternNode *Pattern = I->getTree(0);
2280 TreePatternNode *SrcPattern;
2281 if (Pattern->getOperator()->getName() == "set") {
2282 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2283 } else{
2284 // Not a set (store or something?)
2285 SrcPattern = Pattern;
2286 }
2287
Chris Lattner6cefb772008-01-05 22:25:12 +00002288 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002289 AddPatternToMatch(I,
2290 PatternToMatch(Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002291 SrcPattern,
2292 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002293 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002294 Instr->getValueAsInt("AddedComplexity"),
2295 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002296 }
2297}
2298
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002299
2300typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2301
Chris Lattner967d54a2010-02-23 06:35:45 +00002302static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002303 std::map<std::string, NameRecord> &Names,
2304 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002305 if (!P->getName().empty()) {
2306 NameRecord &Rec = Names[P->getName()];
2307 // If this is the first instance of the name, remember the node.
2308 if (Rec.second++ == 0)
2309 Rec.first = P;
Chris Lattner2cacec52010-03-15 06:00:16 +00002310 else if (Rec.first->getType() != P->getType())
Chris Lattnera27234e2010-02-23 07:22:28 +00002311 PatternTop->error("repetition of value: $" + P->getName() +
2312 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002313 }
Chris Lattner967d54a2010-02-23 06:35:45 +00002314
2315 if (!P->isLeaf()) {
2316 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002317 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002318 }
2319}
2320
Chris Lattner25b6f912010-02-23 06:16:51 +00002321void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2322 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002323 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002324 std::string Reason;
2325 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002326 Pattern->error("Pattern can never match: " + Reason);
Chris Lattner25b6f912010-02-23 06:16:51 +00002327
Chris Lattner405f1252010-03-01 22:29:19 +00002328 // If the source pattern's root is a complex pattern, that complex pattern
2329 // must specify the nodes it can potentially match.
2330 if (const ComplexPattern *CP =
2331 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2332 if (CP->getRootNodes().empty())
2333 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2334 " could match");
2335
2336
Chris Lattner967d54a2010-02-23 06:35:45 +00002337 // Find all of the named values in the input and output, ensure they have the
2338 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002339 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002340 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2341 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002342
2343 // Scan all of the named values in the destination pattern, rejecting them if
2344 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002345 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002346 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002347 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002348 Pattern->error("Pattern has input without matching name in output: $" +
2349 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002350 }
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002351
2352 // Scan all of the named values in the source pattern, rejecting them if the
2353 // name isn't used in the dest, and isn't used to tie two values together.
2354 for (std::map<std::string, NameRecord>::iterator
2355 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2356 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2357 Pattern->error("Pattern has dead named input: $" + I->first);
2358
Chris Lattner25b6f912010-02-23 06:16:51 +00002359 PatternsToMatch.push_back(PTM);
2360}
2361
2362
Dan Gohmanee4fa192008-04-03 00:02:49 +00002363
2364void CodeGenDAGPatterns::InferInstructionFlags() {
2365 std::map<std::string, CodeGenInstruction> &InstrDescs =
2366 Target.getInstructions();
2367 for (std::map<std::string, CodeGenInstruction>::iterator
2368 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2369 CodeGenInstruction &InstInfo = II->second;
2370 // Determine properties of the instruction from its pattern.
2371 bool MayStore, MayLoad, HasSideEffects;
2372 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2373 InstInfo.mayStore = MayStore;
2374 InstInfo.mayLoad = MayLoad;
2375 InstInfo.hasSideEffects = HasSideEffects;
2376 }
2377}
2378
Chris Lattner2cacec52010-03-15 06:00:16 +00002379/// Given a pattern result with an unresolved type, see if we can find one
2380/// instruction with an unresolved result type. Force this result type to an
2381/// arbitrary element if it's possible types to converge results.
2382static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2383 if (N->isLeaf())
2384 return false;
2385
2386 // Analyze children.
2387 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2388 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2389 return true;
2390
2391 if (!N->getOperator()->isSubClassOf("Instruction"))
2392 return false;
2393
2394 // If this type is already concrete or completely unknown we can't do
2395 // anything.
2396 if (N->getExtType().isCompletelyUnknown() || N->getExtType().isConcrete())
2397 return false;
2398
2399 // Otherwise, force its type to the first possibility (an arbitrary choice).
2400 return N->getExtType().MergeInTypeInfo(N->getExtType().getTypeList()[0], TP);
2401}
2402
Chris Lattnerfe718932008-01-06 01:10:31 +00002403void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002404 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2405
2406 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2407 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2408 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2409 Record *Operator = OpDef->getDef();
2410 TreePattern *Pattern;
2411 if (Operator->getName() != "parallel")
2412 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2413 else {
2414 std::vector<Init*> Values;
David Greenee1b46912009-06-08 20:23:18 +00002415 RecTy *ListTy = 0;
2416 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002417 Values.push_back(Tree->getArg(j));
David Greenee1b46912009-06-08 20:23:18 +00002418 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2419 if (TArg == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002420 errs() << "In dag: " << Tree->getAsString();
2421 errs() << " -- Untyped argument in pattern\n";
David Greenee1b46912009-06-08 20:23:18 +00002422 assert(0 && "Untyped argument in pattern");
2423 }
2424 if (ListTy != 0) {
2425 ListTy = resolveTypes(ListTy, TArg->getType());
2426 if (ListTy == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002427 errs() << "In dag: " << Tree->getAsString();
2428 errs() << " -- Incompatible types in pattern arguments\n";
David Greenee1b46912009-06-08 20:23:18 +00002429 assert(0 && "Incompatible types in pattern arguments");
2430 }
2431 }
2432 else {
Bill Wendlingee1f6b02009-06-09 18:49:42 +00002433 ListTy = TArg->getType();
David Greenee1b46912009-06-08 20:23:18 +00002434 }
2435 }
2436 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
Chris Lattner6cefb772008-01-05 22:25:12 +00002437 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2438 }
2439
2440 // Inline pattern fragments into it.
2441 Pattern->InlinePatternFragments();
2442
2443 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2444 if (LI->getSize() == 0) continue; // no pattern.
2445
2446 // Parse the instruction.
2447 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2448
2449 // Inline pattern fragments into it.
2450 Result->InlinePatternFragments();
2451
2452 if (Result->getNumTrees() != 1)
2453 Result->error("Cannot handle instructions producing instructions "
2454 "with temporaries yet!");
2455
2456 bool IterateInference;
2457 bool InferredAllPatternTypes, InferredAllResultTypes;
2458 do {
2459 // Infer as many types as possible. If we cannot infer all of them, we
2460 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002461 InferredAllPatternTypes =
2462 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002463
2464 // Infer as many types as possible. If we cannot infer all of them, we
2465 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002466 InferredAllResultTypes =
2467 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002468
Chris Lattner6c6ba362010-03-18 23:15:10 +00002469 IterateInference = false;
2470
Chris Lattner6cefb772008-01-05 22:25:12 +00002471 // Apply the type of the result to the source pattern. This helps us
2472 // resolve cases where the input type is known to be a pointer type (which
2473 // is considered resolved), but the result knows it needs to be 32- or
2474 // 64-bits. Infer the other way for good measure.
Chris Lattner6c6ba362010-03-18 23:15:10 +00002475 if (!Result->getTree(0)->getExtType().isVoid() &&
2476 !Pattern->getTree(0)->getExtType().isVoid()) {
2477 IterateInference = Pattern->getTree(0)->
2478 UpdateNodeType(Result->getTree(0)->getExtType(), *Result);
2479 IterateInference |= Result->getTree(0)->
2480 UpdateNodeType(Pattern->getTree(0)->getExtType(), *Result);
2481 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002482
2483 // If our iteration has converged and the input pattern's types are fully
2484 // resolved but the result pattern is not fully resolved, we may have a
2485 // situation where we have two instructions in the result pattern and
2486 // the instructions require a common register class, but don't care about
2487 // what actual MVT is used. This is actually a bug in our modelling:
2488 // output patterns should have register classes, not MVTs.
2489 //
2490 // In any case, to handle this, we just go through and disambiguate some
2491 // arbitrary types to the result pattern's nodes.
2492 if (!IterateInference && InferredAllPatternTypes &&
2493 !InferredAllResultTypes)
2494 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2495 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002496 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002497
Chris Lattner6cefb772008-01-05 22:25:12 +00002498 // Verify that we inferred enough types that we can do something with the
2499 // pattern and result. If these fire the user has to add type casts.
2500 if (!InferredAllPatternTypes)
2501 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002502 if (!InferredAllResultTypes) {
2503 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002504 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002505 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002506
2507 // Validate that the input pattern is correct.
2508 std::map<std::string, TreePatternNode*> InstInputs;
2509 std::map<std::string, TreePatternNode*> InstResults;
2510 std::vector<Record*> InstImpInputs;
2511 std::vector<Record*> InstImpResults;
2512 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2513 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2514 InstInputs, InstResults,
2515 InstImpInputs, InstImpResults);
2516
2517 // Promote the xform function to be an explicit node if set.
2518 TreePatternNode *DstPattern = Result->getOnlyTree();
2519 std::vector<TreePatternNode*> ResultNodeOperands;
2520 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2521 TreePatternNode *OpNode = DstPattern->getChild(ii);
2522 if (Record *Xform = OpNode->getTransformFn()) {
2523 OpNode->setTransformFn(0);
2524 std::vector<TreePatternNode*> Children;
2525 Children.push_back(OpNode);
2526 OpNode = new TreePatternNode(Xform, Children);
2527 }
2528 ResultNodeOperands.push_back(OpNode);
2529 }
2530 DstPattern = Result->getOnlyTree();
2531 if (!DstPattern->isLeaf())
2532 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2533 ResultNodeOperands);
Chris Lattner2cacec52010-03-15 06:00:16 +00002534 DstPattern->setType(Result->getOnlyTree()->getExtType());
Chris Lattner6cefb772008-01-05 22:25:12 +00002535 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2536 Temp.InferAllTypes();
2537
Chris Lattner6cefb772008-01-05 22:25:12 +00002538
Chris Lattner25b6f912010-02-23 06:16:51 +00002539 AddPatternToMatch(Pattern,
2540 PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2541 Pattern->getTree(0),
2542 Temp.getOnlyTree(), InstImpResults,
Chris Lattner117ccb72010-03-01 22:09:11 +00002543 Patterns[i]->getValueAsInt("AddedComplexity"),
2544 Patterns[i]->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002545 }
2546}
2547
2548/// CombineChildVariants - Given a bunch of permutations of each child of the
2549/// 'operator' node, put them together in all possible ways.
2550static void CombineChildVariants(TreePatternNode *Orig,
2551 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2552 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002553 CodeGenDAGPatterns &CDP,
2554 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002555 // Make sure that each operand has at least one variant to choose from.
2556 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2557 if (ChildVariants[i].empty())
2558 return;
2559
2560 // The end result is an all-pairs construction of the resultant pattern.
2561 std::vector<unsigned> Idxs;
2562 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002563 bool NotDone;
2564 do {
2565#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002566 DEBUG(if (!Idxs.empty()) {
2567 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2568 for (unsigned i = 0; i < Idxs.size(); ++i) {
2569 errs() << Idxs[i] << " ";
2570 }
2571 errs() << "]\n";
2572 });
Scott Michel327d0652008-03-05 17:49:05 +00002573#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002574 // Create the variant and add it to the output list.
2575 std::vector<TreePatternNode*> NewChildren;
2576 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2577 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2578 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2579
2580 // Copy over properties.
2581 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002582 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002583 R->setTransformFn(Orig->getTransformFn());
Chris Lattner2cacec52010-03-15 06:00:16 +00002584 R->setType(Orig->getExtType());
Chris Lattner6cefb772008-01-05 22:25:12 +00002585
Scott Michel327d0652008-03-05 17:49:05 +00002586 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002587 std::string ErrString;
2588 if (!R->canPatternMatch(ErrString, CDP)) {
2589 delete R;
2590 } else {
2591 bool AlreadyExists = false;
2592
2593 // Scan to see if this pattern has already been emitted. We can get
2594 // duplication due to things like commuting:
2595 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2596 // which are the same pattern. Ignore the dups.
2597 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002598 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002599 AlreadyExists = true;
2600 break;
2601 }
2602
2603 if (AlreadyExists)
2604 delete R;
2605 else
2606 OutVariants.push_back(R);
2607 }
2608
Scott Michel327d0652008-03-05 17:49:05 +00002609 // Increment indices to the next permutation by incrementing the
2610 // indicies from last index backward, e.g., generate the sequence
2611 // [0, 0], [0, 1], [1, 0], [1, 1].
2612 int IdxsIdx;
2613 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2614 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2615 Idxs[IdxsIdx] = 0;
2616 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002617 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002618 }
Scott Michel327d0652008-03-05 17:49:05 +00002619 NotDone = (IdxsIdx >= 0);
2620 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002621}
2622
2623/// CombineChildVariants - A helper function for binary operators.
2624///
2625static void CombineChildVariants(TreePatternNode *Orig,
2626 const std::vector<TreePatternNode*> &LHS,
2627 const std::vector<TreePatternNode*> &RHS,
2628 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002629 CodeGenDAGPatterns &CDP,
2630 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002631 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2632 ChildVariants.push_back(LHS);
2633 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002634 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002635}
2636
2637
2638static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2639 std::vector<TreePatternNode *> &Children) {
2640 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2641 Record *Operator = N->getOperator();
2642
2643 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002644 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002645 N->getTransformFn()) {
2646 Children.push_back(N);
2647 return;
2648 }
2649
2650 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2651 Children.push_back(N->getChild(0));
2652 else
2653 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2654
2655 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2656 Children.push_back(N->getChild(1));
2657 else
2658 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2659}
2660
2661/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2662/// the (potentially recursive) pattern by using algebraic laws.
2663///
2664static void GenerateVariantsOf(TreePatternNode *N,
2665 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002666 CodeGenDAGPatterns &CDP,
2667 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002668 // We cannot permute leaves.
2669 if (N->isLeaf()) {
2670 OutVariants.push_back(N);
2671 return;
2672 }
2673
2674 // Look up interesting info about the node.
2675 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2676
Jim Grosbachda4231f2009-03-26 16:17:51 +00002677 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002678 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002679 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002680 std::vector<TreePatternNode*> MaximalChildren;
2681 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2682
2683 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2684 // permutations.
2685 if (MaximalChildren.size() == 3) {
2686 // Find the variants of all of our maximal children.
2687 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002688 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2689 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2690 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002691
2692 // There are only two ways we can permute the tree:
2693 // (A op B) op C and A op (B op C)
2694 // Within these forms, we can also permute A/B/C.
2695
2696 // Generate legal pair permutations of A/B/C.
2697 std::vector<TreePatternNode*> ABVariants;
2698 std::vector<TreePatternNode*> BAVariants;
2699 std::vector<TreePatternNode*> ACVariants;
2700 std::vector<TreePatternNode*> CAVariants;
2701 std::vector<TreePatternNode*> BCVariants;
2702 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002703 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2704 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2705 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2706 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2707 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2708 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002709
2710 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002711 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2712 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2713 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2714 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2715 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2716 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002717
2718 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002719 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2720 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2721 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2722 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2723 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2724 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002725 return;
2726 }
2727 }
2728
2729 // Compute permutations of all children.
2730 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2731 ChildVariants.resize(N->getNumChildren());
2732 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002733 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002734
2735 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002736 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002737
2738 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002739 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2740 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2741 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2742 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002743 // Don't count children which are actually register references.
2744 unsigned NC = 0;
2745 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2746 TreePatternNode *Child = N->getChild(i);
2747 if (Child->isLeaf())
2748 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2749 Record *RR = DI->getDef();
2750 if (RR->isSubClassOf("Register"))
2751 continue;
2752 }
2753 NC++;
2754 }
2755 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002756 if (isCommIntrinsic) {
2757 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2758 // operands are the commutative operands, and there might be more operands
2759 // after those.
2760 assert(NC >= 3 &&
2761 "Commutative intrinsic should have at least 3 childrean!");
2762 std::vector<std::vector<TreePatternNode*> > Variants;
2763 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2764 Variants.push_back(ChildVariants[2]);
2765 Variants.push_back(ChildVariants[1]);
2766 for (unsigned i = 3; i != NC; ++i)
2767 Variants.push_back(ChildVariants[i]);
2768 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2769 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002770 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002771 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002772 }
2773}
2774
2775
2776// GenerateVariants - Generate variants. For example, commutative patterns can
2777// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002778void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00002779 DEBUG(errs() << "Generating instruction variants.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002780
2781 // Loop over all of the patterns we've collected, checking to see if we can
2782 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002783 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002784 // the .td file having to contain tons of variants of instructions.
2785 //
2786 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2787 // intentionally do not reconsider these. Any variants of added patterns have
2788 // already been added.
2789 //
2790 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002791 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002792 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002793 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00002794 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00002795 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00002796 DEBUG(errs() << "\n");
Scott Michel327d0652008-03-05 17:49:05 +00002797 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002798
2799 assert(!Variants.empty() && "Must create at least original variant!");
2800 Variants.erase(Variants.begin()); // Remove the original pattern.
2801
2802 if (Variants.empty()) // No variants for this pattern.
2803 continue;
2804
Chris Lattner569f1212009-08-23 04:44:11 +00002805 DEBUG(errs() << "FOUND VARIANTS OF: ";
2806 PatternsToMatch[i].getSrcPattern()->dump();
2807 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002808
2809 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2810 TreePatternNode *Variant = Variants[v];
2811
Chris Lattner569f1212009-08-23 04:44:11 +00002812 DEBUG(errs() << " VAR#" << v << ": ";
2813 Variant->dump();
2814 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002815
2816 // Scan to see if an instruction or explicit pattern already matches this.
2817 bool AlreadyExists = false;
2818 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00002819 // Skip if the top level predicates do not match.
2820 if (PatternsToMatch[i].getPredicates() !=
2821 PatternsToMatch[p].getPredicates())
2822 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00002823 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002824 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00002825 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002826 AlreadyExists = true;
2827 break;
2828 }
2829 }
2830 // If we already have it, ignore the variant.
2831 if (AlreadyExists) continue;
2832
2833 // Otherwise, add it to the list of patterns we have.
2834 PatternsToMatch.
2835 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2836 Variant, PatternsToMatch[i].getDstPattern(),
2837 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002838 PatternsToMatch[i].getAddedComplexity(),
2839 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002840 }
2841
Chris Lattner569f1212009-08-23 04:44:11 +00002842 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002843 }
2844}
2845