blob: a73da717c1f03dd9ae599704724d3df69d1b70d5 [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"
Jim Grosbach0b6a44a2011-06-21 22:55:50 +000016#include "Error.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000017#include "Record.h"
18#include "llvm/ADT/StringExtras.h"
Chris Lattner2cacec52010-03-15 06:00:16 +000019#include "llvm/ADT/STLExtras.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000020#include "llvm/Support/Debug.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000021#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000022#include <algorithm>
Chris Lattner6cefb772008-01-05 22:25:12 +000023using namespace llvm;
24
25//===----------------------------------------------------------------------===//
Chris Lattner2cacec52010-03-15 06:00:16 +000026// EEVT::TypeSet Implementation
27//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +000028
Owen Anderson825b72b2009-08-11 20:47:22 +000029static inline bool isInteger(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000030 return EVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000031}
Owen Anderson825b72b2009-08-11 20:47:22 +000032static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000033 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000034}
Owen Anderson825b72b2009-08-11 20:47:22 +000035static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000036 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000037}
Chris Lattner774ce292010-03-19 17:41:26 +000038static inline bool isScalar(MVT::SimpleValueType VT) {
39 return !EVT(VT).isVector();
40}
Duncan Sands83ec4b62008-06-06 12:08:01 +000041
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());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000060
Chris Lattner2cacec52010-03-15 06:00:16 +000061 if (!VTList.empty())
62 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
63 VTList[0] != MVT::fAny);
Jim Grosbachfbadcd02010-12-21 16:16:00 +000064
Chris Lattner0d7952e2010-03-27 20:32:26 +000065 // Verify no duplicates.
Chris Lattner2cacec52010-03-15 06:00:16 +000066 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner0d7952e2010-03-27 20:32:26 +000067 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner6cefb772008-01-05 22:25:12 +000068}
69
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000070/// FillWithPossibleTypes - Set to all legal types and return true, only valid
71/// on completely unknown type sets.
Chris Lattner774ce292010-03-19 17:41:26 +000072bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
73 bool (*Pred)(MVT::SimpleValueType),
74 const char *PredicateName) {
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000075 assert(isCompletelyUnknown());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000076 const std::vector<MVT::SimpleValueType> &LegalTypes =
Chris Lattner774ce292010-03-19 17:41:26 +000077 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +000078
Chris Lattner774ce292010-03-19 17:41:26 +000079 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
80 if (Pred == 0 || Pred(LegalTypes[i]))
81 TypeVec.push_back(LegalTypes[i]);
82
83 // If we have nothing that matches the predicate, bail out.
84 if (TypeVec.empty())
85 TP.error("Type inference contradiction found, no " +
Jim Grosbachfbadcd02010-12-21 16:16:00 +000086 std::string(PredicateName) + " types found");
Chris Lattner774ce292010-03-19 17:41:26 +000087 // No need to sort with one element.
88 if (TypeVec.size() == 1) return true;
89
90 // Remove duplicates.
91 array_pod_sort(TypeVec.begin(), TypeVec.end());
92 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000093
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000094 return true;
95}
Chris Lattner2cacec52010-03-15 06:00:16 +000096
97/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
98/// integer value type.
99bool EEVT::TypeSet::hasIntegerTypes() const {
100 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
101 if (isInteger(TypeVec[i]))
102 return true;
103 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000104}
Chris Lattner2cacec52010-03-15 06:00:16 +0000105
106/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
107/// a floating point value type.
108bool EEVT::TypeSet::hasFloatingPointTypes() const {
109 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
110 if (isFloatingPoint(TypeVec[i]))
111 return true;
112 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000113}
Chris Lattner2cacec52010-03-15 06:00:16 +0000114
115/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
116/// value type.
117bool EEVT::TypeSet::hasVectorTypes() const {
118 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
119 if (isVector(TypeVec[i]))
120 return true;
121 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +0000122}
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000123
Chris Lattner2cacec52010-03-15 06:00:16 +0000124
125std::string EEVT::TypeSet::getName() const {
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000126 if (TypeVec.empty()) return "<empty>";
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000127
Chris Lattner2cacec52010-03-15 06:00:16 +0000128 std::string Result;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000129
Chris Lattner2cacec52010-03-15 06:00:16 +0000130 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
131 std::string VTName = llvm::getEnumName(TypeVec[i]);
132 // Strip off MVT:: prefix if present.
133 if (VTName.substr(0,5) == "MVT::")
134 VTName = VTName.substr(5);
135 if (i) Result += ':';
136 Result += VTName;
137 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000138
Chris Lattner2cacec52010-03-15 06:00:16 +0000139 if (TypeVec.size() == 1)
140 return Result;
141 return "{" + Result + "}";
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000142}
Chris Lattner2cacec52010-03-15 06:00:16 +0000143
144/// MergeInTypeInfo - This merges in type information from the specified
145/// argument. If 'this' changes, it returns true. If the two types are
146/// contradictory (e.g. merge f32 into i32) then this throws an exception.
147bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
148 if (InVT.isCompletelyUnknown() || *this == InVT)
149 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000150
Chris Lattner2cacec52010-03-15 06:00:16 +0000151 if (isCompletelyUnknown()) {
152 *this = InVT;
153 return true;
154 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000155
Chris Lattner2cacec52010-03-15 06:00:16 +0000156 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000157
Chris Lattner2cacec52010-03-15 06:00:16 +0000158 // Handle the abstract cases, seeing if we can resolve them better.
159 switch (TypeVec[0]) {
160 default: break;
161 case MVT::iPTR:
162 case MVT::iPTRAny:
163 if (InVT.hasIntegerTypes()) {
164 EEVT::TypeSet InCopy(InVT);
165 InCopy.EnforceInteger(TP);
166 InCopy.EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000167
Chris Lattner2cacec52010-03-15 06:00:16 +0000168 if (InCopy.isConcrete()) {
169 // If the RHS has one integer type, upgrade iPTR to i32.
170 TypeVec[0] = InVT.TypeVec[0];
171 return true;
172 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000173
Chris Lattner2cacec52010-03-15 06:00:16 +0000174 // If the input has multiple scalar integers, this doesn't add any info.
175 if (!InCopy.isCompletelyUnknown())
176 return false;
177 }
178 break;
179 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000180
Chris Lattner2cacec52010-03-15 06:00:16 +0000181 // If the input constraint is iAny/iPTR and this is an integer type list,
182 // remove non-integer types from the list.
183 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
184 hasIntegerTypes()) {
185 bool MadeChange = EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000186
Chris Lattner2cacec52010-03-15 06:00:16 +0000187 // If we're merging in iPTR/iPTRAny and the node currently has a list of
188 // multiple different integer types, replace them with a single iPTR.
189 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
190 TypeVec.size() != 1) {
191 TypeVec.resize(1);
192 TypeVec[0] = InVT.TypeVec[0];
193 MadeChange = true;
194 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000195
Chris Lattner2cacec52010-03-15 06:00:16 +0000196 return MadeChange;
197 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000198
Chris Lattner2cacec52010-03-15 06:00:16 +0000199 // If this is a type list and the RHS is a typelist as well, eliminate entries
200 // from this list that aren't in the other one.
201 bool MadeChange = false;
202 TypeSet InputSet(*this);
203
204 for (unsigned i = 0; i != TypeVec.size(); ++i) {
205 bool InInVT = false;
206 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
207 if (TypeVec[i] == InVT.TypeVec[j]) {
208 InInVT = true;
209 break;
210 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000211
Chris Lattner2cacec52010-03-15 06:00:16 +0000212 if (InInVT) continue;
213 TypeVec.erase(TypeVec.begin()+i--);
214 MadeChange = true;
215 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000216
Chris Lattner2cacec52010-03-15 06:00:16 +0000217 // If we removed all of our types, we have a type contradiction.
218 if (!TypeVec.empty())
219 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000220
Chris Lattner2cacec52010-03-15 06:00:16 +0000221 // FIXME: Really want an SMLoc here!
222 TP.error("Type inference contradiction found, merging '" +
223 InVT.getName() + "' into '" + InputSet.getName() + "'");
224 return true; // unreachable
225}
226
227/// EnforceInteger - Remove all non-integer types from this set.
228bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000229 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000230 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000231 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattner2cacec52010-03-15 06:00:16 +0000232 if (!hasFloatingPointTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000233 return false;
234
235 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000236
Chris Lattner2cacec52010-03-15 06:00:16 +0000237 // Filter out all the fp types.
238 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000239 if (!isInteger(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000240 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000241
Chris Lattner2cacec52010-03-15 06:00:16 +0000242 if (TypeVec.empty())
243 TP.error("Type inference contradiction found, '" +
244 InputSet.getName() + "' needs to be integer");
Chris Lattner774ce292010-03-19 17:41:26 +0000245 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000246}
247
248/// EnforceFloatingPoint - Remove all integer types from this set.
249bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000250 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000251 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000252 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
253
Chris Lattner2cacec52010-03-15 06:00:16 +0000254 if (!hasIntegerTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000255 return false;
256
257 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000258
Chris Lattner2cacec52010-03-15 06:00:16 +0000259 // Filter out all the fp types.
260 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000261 if (!isFloatingPoint(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000262 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000263
Chris Lattner2cacec52010-03-15 06:00:16 +0000264 if (TypeVec.empty())
265 TP.error("Type inference contradiction found, '" +
266 InputSet.getName() + "' needs to be floating point");
Chris Lattner774ce292010-03-19 17:41:26 +0000267 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000268}
269
270/// EnforceScalar - Remove all vector types from this.
271bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000272 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000273 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000274 return FillWithPossibleTypes(TP, isScalar, "scalar");
275
Chris Lattner2cacec52010-03-15 06:00:16 +0000276 if (!hasVectorTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000277 return false;
278
279 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000280
Chris Lattner2cacec52010-03-15 06:00:16 +0000281 // Filter out all the vector types.
282 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000283 if (!isScalar(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000284 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000285
Chris Lattner2cacec52010-03-15 06:00:16 +0000286 if (TypeVec.empty())
287 TP.error("Type inference contradiction found, '" +
288 InputSet.getName() + "' needs to be scalar");
Chris Lattner774ce292010-03-19 17:41:26 +0000289 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000290}
291
292/// EnforceVector - Remove all vector types from this.
293bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Chris Lattner774ce292010-03-19 17:41:26 +0000294 // If we know nothing, then get the full set.
295 if (TypeVec.empty())
296 return FillWithPossibleTypes(TP, isVector, "vector");
297
Chris Lattner2cacec52010-03-15 06:00:16 +0000298 TypeSet InputSet(*this);
299 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000300
Chris Lattner2cacec52010-03-15 06:00:16 +0000301 // Filter out all the scalar types.
302 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000303 if (!isVector(TypeVec[i])) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000304 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner774ce292010-03-19 17:41:26 +0000305 MadeChange = true;
306 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000307
Chris Lattner2cacec52010-03-15 06:00:16 +0000308 if (TypeVec.empty())
309 TP.error("Type inference contradiction found, '" +
310 InputSet.getName() + "' needs to be a vector");
311 return MadeChange;
312}
313
314
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000315
Chris Lattner2cacec52010-03-15 06:00:16 +0000316/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
317/// this an other based on this information.
318bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
319 // Both operands must be integer or FP, but we don't care which.
320 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000321
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000322 if (isCompletelyUnknown())
323 MadeChange = FillWithPossibleTypes(TP);
324
325 if (Other.isCompletelyUnknown())
326 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000327
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000328 // If one side is known to be integer or known to be FP but the other side has
329 // no information, get at least the type integrality info in there.
330 if (!hasFloatingPointTypes())
331 MadeChange |= Other.EnforceInteger(TP);
332 else if (!hasIntegerTypes())
333 MadeChange |= Other.EnforceFloatingPoint(TP);
334 if (!Other.hasFloatingPointTypes())
335 MadeChange |= EnforceInteger(TP);
336 else if (!Other.hasIntegerTypes())
337 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000338
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000339 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
340 "Should have a type list now");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000341
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000342 // If one contains vectors but the other doesn't pull vectors out.
343 if (!hasVectorTypes())
344 MadeChange |= Other.EnforceScalar(TP);
345 if (!hasVectorTypes())
346 MadeChange |= EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000347
David Greene9d7f0112011-02-01 19:12:32 +0000348 if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
349 // If we are down to concrete types, this code does not currently
350 // handle nodes which have multiple types, where some types are
351 // integer, and some are fp. Assert that this is not the case.
352 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
353 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
354 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
355
356 // Otherwise, if these are both vector types, either this vector
357 // must have a larger bitsize than the other, or this element type
358 // must be larger than the other.
359 EVT Type(TypeVec[0]);
360 EVT OtherType(Other.TypeVec[0]);
361
362 if (hasVectorTypes() && Other.hasVectorTypes()) {
363 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
364 if (Type.getVectorElementType().getSizeInBits()
365 >= OtherType.getVectorElementType().getSizeInBits())
366 TP.error("Type inference contradiction found, '" +
367 getName() + "' element type not smaller than '" +
368 Other.getName() +"'!");
369 }
370 else
371 // For scalar types, the bitsize of this type must be larger
372 // than that of the other.
373 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
374 TP.error("Type inference contradiction found, '" +
375 getName() + "' is not smaller than '" +
376 Other.getName() +"'!");
377
378 }
379
380
381 // Handle int and fp as disjoint sets. This won't work for patterns
382 // that have mixed fp/int types but those are likely rare and would
383 // not have been accepted by this code previously.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000384
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000385 // Okay, find the smallest type from the current set and remove it from the
386 // largest set.
David Greenec83e2032011-02-04 17:01:53 +0000387 MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
David Greene9d7f0112011-02-01 19:12:32 +0000388 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
389 if (isInteger(TypeVec[i])) {
390 SmallestInt = TypeVec[i];
391 break;
392 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000393 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
David Greene9d7f0112011-02-01 19:12:32 +0000394 if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
395 SmallestInt = TypeVec[i];
396
David Greenec83e2032011-02-04 17:01:53 +0000397 MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
David Greene9d7f0112011-02-01 19:12:32 +0000398 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
399 if (isFloatingPoint(TypeVec[i])) {
400 SmallestFP = TypeVec[i];
401 break;
402 }
403 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
404 if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
405 SmallestFP = TypeVec[i];
406
407 int OtherIntSize = 0;
408 int OtherFPSize = 0;
409 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
410 Other.TypeVec.begin();
411 TVI != Other.TypeVec.end();
412 /* NULL */) {
413 if (isInteger(*TVI)) {
414 ++OtherIntSize;
415 if (*TVI == SmallestInt) {
416 TVI = Other.TypeVec.erase(TVI);
417 --OtherIntSize;
418 MadeChange = true;
419 continue;
420 }
421 }
422 else if (isFloatingPoint(*TVI)) {
423 ++OtherFPSize;
424 if (*TVI == SmallestFP) {
425 TVI = Other.TypeVec.erase(TVI);
426 --OtherFPSize;
427 MadeChange = true;
428 continue;
429 }
430 }
431 ++TVI;
432 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000433
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000434 // If this is the only type in the large set, the constraint can never be
435 // satisfied.
David Greene9d7f0112011-02-01 19:12:32 +0000436 if ((Other.hasIntegerTypes() && OtherIntSize == 0)
437 || (Other.hasFloatingPointTypes() && OtherFPSize == 0))
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000438 TP.error("Type inference contradiction found, '" +
439 Other.getName() + "' has nothing larger than '" + getName() +"'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000440
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000441 // Okay, find the largest type in the Other set and remove it from the
442 // current set.
David Greenec83e2032011-02-04 17:01:53 +0000443 MVT::SimpleValueType LargestInt = MVT::Other;
David Greene9d7f0112011-02-01 19:12:32 +0000444 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
445 if (isInteger(Other.TypeVec[i])) {
446 LargestInt = Other.TypeVec[i];
447 break;
448 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000449 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
David Greene9d7f0112011-02-01 19:12:32 +0000450 if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
451 LargestInt = Other.TypeVec[i];
452
David Greenec83e2032011-02-04 17:01:53 +0000453 MVT::SimpleValueType LargestFP = MVT::Other;
David Greene9d7f0112011-02-01 19:12:32 +0000454 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
455 if (isFloatingPoint(Other.TypeVec[i])) {
456 LargestFP = Other.TypeVec[i];
457 break;
458 }
459 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
460 if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
461 LargestFP = Other.TypeVec[i];
462
463 int IntSize = 0;
464 int FPSize = 0;
465 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
466 TypeVec.begin();
467 TVI != TypeVec.end();
468 /* NULL */) {
469 if (isInteger(*TVI)) {
470 ++IntSize;
471 if (*TVI == LargestInt) {
472 TVI = TypeVec.erase(TVI);
473 --IntSize;
474 MadeChange = true;
475 continue;
476 }
477 }
478 else if (isFloatingPoint(*TVI)) {
479 ++FPSize;
480 if (*TVI == LargestFP) {
481 TVI = TypeVec.erase(TVI);
482 --FPSize;
483 MadeChange = true;
484 continue;
485 }
486 }
487 ++TVI;
488 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000489
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000490 // If this is the only type in the small set, the constraint can never be
491 // satisfied.
David Greene9d7f0112011-02-01 19:12:32 +0000492 if ((hasIntegerTypes() && IntSize == 0)
493 || (hasFloatingPointTypes() && FPSize == 0))
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000494 TP.error("Type inference contradiction found, '" +
495 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000496
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000497 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000498}
499
500/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner66fb9d22010-03-24 00:01:16 +0000501/// whose element is specified by VTOperand.
502bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattner2cacec52010-03-15 06:00:16 +0000503 TreePattern &TP) {
Chris Lattner66fb9d22010-03-24 00:01:16 +0000504 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattner2cacec52010-03-15 06:00:16 +0000505 bool MadeChange = false;
Chris Lattner66fb9d22010-03-24 00:01:16 +0000506 MadeChange |= EnforceVector(TP);
507 MadeChange |= VTOperand.EnforceScalar(TP);
508
509 // If we know the vector type, it forces the scalar to agree.
510 if (isConcrete()) {
511 EVT IVT = getConcrete();
512 IVT = IVT.getVectorElementType();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000513 return MadeChange |
Chris Lattner66fb9d22010-03-24 00:01:16 +0000514 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
515 }
516
517 // If the scalar type is known, filter out vector types whose element types
518 // disagree.
519 if (!VTOperand.isConcrete())
520 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000521
Chris Lattner66fb9d22010-03-24 00:01:16 +0000522 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000523
Chris Lattner66fb9d22010-03-24 00:01:16 +0000524 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000525
Chris Lattner66fb9d22010-03-24 00:01:16 +0000526 // Filter out all the types which don't have the right element type.
527 for (unsigned i = 0; i != TypeVec.size(); ++i) {
528 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
529 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000530 TypeVec.erase(TypeVec.begin()+i--);
531 MadeChange = true;
532 }
Chris Lattner66fb9d22010-03-24 00:01:16 +0000533 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000534
Chris Lattner2cacec52010-03-15 06:00:16 +0000535 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
536 TP.error("Type inference contradiction found, forcing '" +
537 InputSet.getName() + "' to have a vector element");
538 return MadeChange;
539}
540
David Greene60322692011-01-24 20:53:18 +0000541/// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
542/// vector type specified by VTOperand.
543bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
544 TreePattern &TP) {
545 // "This" must be a vector and "VTOperand" must be a vector.
546 bool MadeChange = false;
547 MadeChange |= EnforceVector(TP);
548 MadeChange |= VTOperand.EnforceVector(TP);
549
550 // "This" must be larger than "VTOperand."
551 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
552
553 // If we know the vector type, it forces the scalar types to agree.
554 if (isConcrete()) {
555 EVT IVT = getConcrete();
556 IVT = IVT.getVectorElementType();
557
558 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
559 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
560 } else if (VTOperand.isConcrete()) {
561 EVT IVT = VTOperand.getConcrete();
562 IVT = IVT.getVectorElementType();
563
564 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
565 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
566 }
567
568 return MadeChange;
569}
570
Chris Lattner2cacec52010-03-15 06:00:16 +0000571//===----------------------------------------------------------------------===//
572// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000573
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000574bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
575 return LHS->getID() < RHS->getID();
576}
Scott Michel327d0652008-03-05 17:49:05 +0000577
578/// Dependent variable map for CodeGenDAGPattern variant generation
579typedef std::map<std::string, int> DepVarMap;
580
581/// Const iterator shorthand for DepVarMap
582typedef DepVarMap::const_iterator DepVarMap_citer;
583
Chris Lattner54379062011-04-17 21:38:24 +0000584static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel327d0652008-03-05 17:49:05 +0000585 if (N->isLeaf()) {
David Greened4a90662011-07-11 18:25:51 +0000586 if (dynamic_cast<const DefInit*>(N->getLeafValue()) != NULL)
Scott Michel327d0652008-03-05 17:49:05 +0000587 DepMap[N->getName()]++;
Scott Michel327d0652008-03-05 17:49:05 +0000588 } else {
589 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
590 FindDepVarsOf(N->getChild(i), DepMap);
591 }
592}
Chris Lattner54379062011-04-17 21:38:24 +0000593
594/// Find dependent variables within child patterns
595static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000596 DepVarMap depcounts;
597 FindDepVarsOf(N, depcounts);
598 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner54379062011-04-17 21:38:24 +0000599 if (i->second > 1) // std::pair<std::string, int>
Scott Michel327d0652008-03-05 17:49:05 +0000600 DepVars.insert(i->first);
Scott Michel327d0652008-03-05 17:49:05 +0000601 }
602}
603
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000604#ifndef NDEBUG
Chris Lattner54379062011-04-17 21:38:24 +0000605/// Dump the dependent variable set:
606static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000607 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000608 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000609 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000610 DEBUG(errs() << "[ ");
Jim Grosbachbb168242010-10-08 18:13:57 +0000611 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
612 e = DepVars.end(); i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000613 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000614 }
Chris Lattner569f1212009-08-23 04:44:11 +0000615 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000616 }
617}
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000618#endif
619
Chris Lattner54379062011-04-17 21:38:24 +0000620
621//===----------------------------------------------------------------------===//
622// TreePredicateFn Implementation
623//===----------------------------------------------------------------------===//
624
Chris Lattner7ed13912011-04-17 22:05:17 +0000625/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
626TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
627 assert((getPredCode().empty() || getImmCode().empty()) &&
628 ".td file corrupt: can't have a node predicate *and* an imm predicate");
629}
630
Chris Lattner54379062011-04-17 21:38:24 +0000631std::string TreePredicateFn::getPredCode() const {
632 return PatFragRec->getRecord()->getValueAsCode("PredicateCode");
633}
634
Chris Lattner7ed13912011-04-17 22:05:17 +0000635std::string TreePredicateFn::getImmCode() const {
636 return PatFragRec->getRecord()->getValueAsCode("ImmediateCode");
637}
638
Chris Lattner54379062011-04-17 21:38:24 +0000639
640/// isAlwaysTrue - Return true if this is a noop predicate.
641bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000642 return getPredCode().empty() && getImmCode().empty();
Chris Lattner54379062011-04-17 21:38:24 +0000643}
644
645/// Return the name to use in the generated code to reference this, this is
646/// "Predicate_foo" if from a pattern fragment "foo".
647std::string TreePredicateFn::getFnName() const {
648 return "Predicate_" + PatFragRec->getRecord()->getName();
649}
650
651/// getCodeToRunOnSDNode - Return the code for the function body that
652/// evaluates this predicate. The argument is expected to be in "Node",
653/// not N. This handles casting and conversion to a concrete node type as
654/// appropriate.
655std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000656 // Handle immediate predicates first.
657 std::string ImmCode = getImmCode();
658 if (!ImmCode.empty()) {
659 std::string Result =
660 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner7ed13912011-04-17 22:05:17 +0000661 return Result + ImmCode;
662 }
663
664 // Handle arbitrary node predicates.
665 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner54379062011-04-17 21:38:24 +0000666 std::string ClassName;
667 if (PatFragRec->getOnlyTree()->isLeaf())
668 ClassName = "SDNode";
669 else {
670 Record *Op = PatFragRec->getOnlyTree()->getOperator();
671 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
672 }
673 std::string Result;
674 if (ClassName == "SDNode")
675 Result = " SDNode *N = Node;\n";
676 else
677 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
678
679 return Result + getPredCode();
Scott Michel327d0652008-03-05 17:49:05 +0000680}
681
Chris Lattner6cefb772008-01-05 22:25:12 +0000682//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000683// PatternToMatch implementation
684//
685
Chris Lattner48e86db2010-03-29 01:40:38 +0000686
687/// getPatternSize - Return the 'size' of this pattern. We want to match large
688/// patterns before small ones. This is used to determine the size of a
689/// pattern.
690static unsigned getPatternSize(const TreePatternNode *P,
691 const CodeGenDAGPatterns &CGP) {
692 unsigned Size = 3; // The node itself.
693 // If the root node is a ConstantSDNode, increases its size.
694 // e.g. (set R32:$dst, 0).
David Greened4a90662011-07-11 18:25:51 +0000695 if (P->isLeaf() && dynamic_cast<const IntInit*>(P->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000696 Size += 2;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000697
Chris Lattner48e86db2010-03-29 01:40:38 +0000698 // FIXME: This is a hack to statically increase the priority of patterns
699 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
700 // Later we can allow complexity / cost for each pattern to be (optionally)
701 // specified. To get best possible pattern match we'll need to dynamically
702 // calculate the complexity of all patterns a dag can potentially map to.
703 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
704 if (AM)
705 Size += AM->getNumOperands() * 3;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000706
Chris Lattner48e86db2010-03-29 01:40:38 +0000707 // If this node has some predicate function that must match, it adds to the
708 // complexity of this node.
709 if (!P->getPredicateFns().empty())
710 ++Size;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000711
Chris Lattner48e86db2010-03-29 01:40:38 +0000712 // Count children in the count if they are also nodes.
713 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
714 TreePatternNode *Child = P->getChild(i);
715 if (!Child->isLeaf() && Child->getNumTypes() &&
716 Child->getType(0) != MVT::Other)
717 Size += getPatternSize(Child, CGP);
718 else if (Child->isLeaf()) {
David Greened4a90662011-07-11 18:25:51 +0000719 if (dynamic_cast<const IntInit*>(Child->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000720 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
721 else if (Child->getComplexPatternInfo(CGP))
722 Size += getPatternSize(Child, CGP);
723 else if (!Child->getPredicateFns().empty())
724 ++Size;
725 }
726 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000727
Chris Lattner48e86db2010-03-29 01:40:38 +0000728 return Size;
729}
730
731/// Compute the complexity metric for the input pattern. This roughly
732/// corresponds to the number of nodes that are covered.
733unsigned PatternToMatch::
734getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
735 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
736}
737
738
Dan Gohman22bb3112008-08-22 00:20:26 +0000739/// getPredicateCheck - Return a single string containing all of this
740/// pattern's predicates concatenated with "&&" operators.
741///
742std::string PatternToMatch::getPredicateCheck() const {
743 std::string PredicateCheck;
744 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
David Greened4a90662011-07-11 18:25:51 +0000745 if (const DefInit *Pred =
746 dynamic_cast<const DefInit*>(Predicates->getElement(i))) {
Dan Gohman22bb3112008-08-22 00:20:26 +0000747 Record *Def = Pred->getDef();
748 if (!Def->isSubClassOf("Predicate")) {
749#ifndef NDEBUG
750 Def->dump();
751#endif
752 assert(0 && "Unknown predicate type!");
753 }
754 if (!PredicateCheck.empty())
755 PredicateCheck += " && ";
756 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
757 }
758 }
759
760 return PredicateCheck;
761}
762
763//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000764// SDTypeConstraint implementation
765//
766
767SDTypeConstraint::SDTypeConstraint(Record *R) {
768 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000769
Chris Lattner6cefb772008-01-05 22:25:12 +0000770 if (R->isSubClassOf("SDTCisVT")) {
771 ConstraintType = SDTCisVT;
772 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerc8122612010-03-28 06:04:39 +0000773 if (x.SDTCisVT_Info.VT == MVT::isVoid)
774 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000775
Chris Lattner6cefb772008-01-05 22:25:12 +0000776 } else if (R->isSubClassOf("SDTCisPtrTy")) {
777 ConstraintType = SDTCisPtrTy;
778 } else if (R->isSubClassOf("SDTCisInt")) {
779 ConstraintType = SDTCisInt;
780 } else if (R->isSubClassOf("SDTCisFP")) {
781 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000782 } else if (R->isSubClassOf("SDTCisVec")) {
783 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000784 } else if (R->isSubClassOf("SDTCisSameAs")) {
785 ConstraintType = SDTCisSameAs;
786 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
787 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
788 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000789 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000790 R->getValueAsInt("OtherOperandNum");
791 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
792 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000793 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000794 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000795 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
796 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000797 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene60322692011-01-24 20:53:18 +0000798 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
799 ConstraintType = SDTCisSubVecOfVec;
800 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
801 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000802 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000803 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000804 exit(1);
805 }
806}
807
808/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000809/// N, and the result number in ResNo.
810static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
811 const SDNodeInfo &NodeInfo,
812 unsigned &ResNo) {
813 unsigned NumResults = NodeInfo.getNumResults();
814 if (OpNo < NumResults) {
815 ResNo = OpNo;
816 return N;
817 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000818
Chris Lattner2e68a022010-03-19 21:56:21 +0000819 OpNo -= NumResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000820
Chris Lattner2e68a022010-03-19 21:56:21 +0000821 if (OpNo >= N->getNumChildren()) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000822 errs() << "Invalid operand number in type constraint "
Chris Lattner2e68a022010-03-19 21:56:21 +0000823 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000824 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000825 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000826 exit(1);
827 }
828
Chris Lattner2e68a022010-03-19 21:56:21 +0000829 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000830}
831
832/// ApplyTypeConstraint - Given a node in a pattern, apply this type
833/// constraint to the nodes operands. This returns true if it makes a
834/// change, false otherwise. If a type contradiction is found, throw an
835/// exception.
836bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
837 const SDNodeInfo &NodeInfo,
838 TreePattern &TP) const {
Chris Lattner2e68a022010-03-19 21:56:21 +0000839 unsigned ResNo = 0; // The result number being referenced.
840 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000841
Chris Lattner6cefb772008-01-05 22:25:12 +0000842 switch (ConstraintType) {
843 default: assert(0 && "Unknown constraint type!");
844 case SDTCisVT:
845 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000846 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000847 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000848 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000849 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000850 case SDTCisInt:
851 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000852 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000853 case SDTCisFP:
854 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000855 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000856 case SDTCisVec:
857 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000858 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000859 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000860 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000861 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000862 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000863 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
864 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000865 }
866 case SDTCisVTSmallerThanOp: {
867 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
868 // have an integer type that is smaller than the VT.
869 if (!NodeToApply->isLeaf() ||
David Greened4a90662011-07-11 18:25:51 +0000870 !dynamic_cast<const DefInit*>(NodeToApply->getLeafValue()) ||
871 !static_cast<const DefInit*>(NodeToApply->getLeafValue())->getDef()
Chris Lattner6cefb772008-01-05 22:25:12 +0000872 ->isSubClassOf("ValueType"))
873 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000874 MVT::SimpleValueType VT =
David Greened4a90662011-07-11 18:25:51 +0000875 getValueType(static_cast<const DefInit*>(NodeToApply->getLeafValue())
876 ->getDef());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000877
Chris Lattnercc878302010-03-24 00:06:46 +0000878 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000879
Chris Lattner2e68a022010-03-19 21:56:21 +0000880 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000881 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000882 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
883 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000884
Chris Lattnercc878302010-03-24 00:06:46 +0000885 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000886 }
887 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000888 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000889 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000890 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
891 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000892 return NodeToApply->getExtType(ResNo).
893 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000894 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000895 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000896 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000897 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000898 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
899 VResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000900
Chris Lattner66fb9d22010-03-24 00:01:16 +0000901 // Filter vector types out of VecOperand that don't have the right element
902 // type.
903 return VecOperand->getExtType(VResNo).
904 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000905 }
David Greene60322692011-01-24 20:53:18 +0000906 case SDTCisSubVecOfVec: {
907 unsigned VResNo = 0;
908 TreePatternNode *BigVecOperand =
909 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
910 VResNo);
911
912 // Filter vector types out of BigVecOperand that don't have the
913 // right subvector type.
914 return BigVecOperand->getExtType(VResNo).
915 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
916 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000917 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000918 return false;
919}
920
921//===----------------------------------------------------------------------===//
922// SDNodeInfo implementation
923//
924SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
925 EnumName = R->getValueAsString("Opcode");
926 SDClassName = R->getValueAsString("SDClass");
927 Record *TypeProfile = R->getValueAsDef("TypeProfile");
928 NumResults = TypeProfile->getValueAsInt("NumResults");
929 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000930
Chris Lattner6cefb772008-01-05 22:25:12 +0000931 // Parse the properties.
932 Properties = 0;
933 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
934 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
935 if (PropList[i]->getName() == "SDNPCommutative") {
936 Properties |= 1 << SDNPCommutative;
937 } else if (PropList[i]->getName() == "SDNPAssociative") {
938 Properties |= 1 << SDNPAssociative;
939 } else if (PropList[i]->getName() == "SDNPHasChain") {
940 Properties |= 1 << SDNPHasChain;
Chris Lattner036609b2010-12-23 18:28:41 +0000941 } else if (PropList[i]->getName() == "SDNPOutGlue") {
942 Properties |= 1 << SDNPOutGlue;
943 } else if (PropList[i]->getName() == "SDNPInGlue") {
944 Properties |= 1 << SDNPInGlue;
945 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
946 Properties |= 1 << SDNPOptInGlue;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000947 } else if (PropList[i]->getName() == "SDNPMayStore") {
948 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000949 } else if (PropList[i]->getName() == "SDNPMayLoad") {
950 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000951 } else if (PropList[i]->getName() == "SDNPSideEffect") {
952 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000953 } else if (PropList[i]->getName() == "SDNPMemOperand") {
954 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000955 } else if (PropList[i]->getName() == "SDNPVariadic") {
956 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000957 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000958 errs() << "Unknown SD Node property '" << PropList[i]->getName()
959 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000960 exit(1);
961 }
962 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000963
964
Chris Lattner6cefb772008-01-05 22:25:12 +0000965 // Parse the type constraints.
966 std::vector<Record*> ConstraintList =
967 TypeProfile->getValueAsListOfDefs("Constraints");
968 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
969}
970
Chris Lattner22579812010-02-28 00:22:30 +0000971/// getKnownType - If the type constraints on this node imply a fixed type
972/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000973/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +0000974MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +0000975 unsigned NumResults = getNumResults();
976 assert(NumResults <= 1 &&
977 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +0000978 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000979
Chris Lattner22579812010-02-28 00:22:30 +0000980 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
981 // Make sure that this applies to the correct node result.
982 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
983 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000984
Chris Lattner22579812010-02-28 00:22:30 +0000985 switch (TypeConstraints[i].ConstraintType) {
986 default: break;
987 case SDTypeConstraint::SDTCisVT:
988 return TypeConstraints[i].x.SDTCisVT_Info.VT;
989 case SDTypeConstraint::SDTCisPtrTy:
990 return MVT::iPTR;
991 }
992 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000993 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000994}
995
Chris Lattner6cefb772008-01-05 22:25:12 +0000996//===----------------------------------------------------------------------===//
997// TreePatternNode implementation
998//
999
1000TreePatternNode::~TreePatternNode() {
1001#if 0 // FIXME: implement refcounted tree nodes!
1002 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1003 delete getChild(i);
1004#endif
1005}
1006
Chris Lattnerd7349192010-03-19 21:37:09 +00001007static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1008 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +00001009 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +00001010 return 0; // All return nothing.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001011
Chris Lattner93dc92e2010-03-22 20:56:36 +00001012 if (Operator->isSubClassOf("Intrinsic"))
1013 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001014
Chris Lattnerd7349192010-03-19 21:37:09 +00001015 if (Operator->isSubClassOf("SDNode"))
1016 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001017
Chris Lattnerd7349192010-03-19 21:37:09 +00001018 if (Operator->isSubClassOf("PatFrag")) {
1019 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1020 // the forward reference case where one pattern fragment references another
1021 // before it is processed.
1022 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1023 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001024
Chris Lattnerd7349192010-03-19 21:37:09 +00001025 // Get the result tree.
David Greened4a90662011-07-11 18:25:51 +00001026 const DagInit *Tree = Operator->getValueAsDag("Fragment");
Chris Lattnerd7349192010-03-19 21:37:09 +00001027 Record *Op = 0;
David Greened4a90662011-07-11 18:25:51 +00001028 if (Tree && dynamic_cast<const DefInit*>(Tree->getOperator()))
1029 Op = dynamic_cast<const DefInit*>(Tree->getOperator())->getDef();
Chris Lattnerd7349192010-03-19 21:37:09 +00001030 assert(Op && "Invalid Fragment");
1031 return GetNumNodeResults(Op, CDP);
1032 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001033
Chris Lattnerd7349192010-03-19 21:37:09 +00001034 if (Operator->isSubClassOf("Instruction")) {
1035 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001036
1037 // FIXME: Should allow access to all the results here.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001038 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001039
Chris Lattner9414ae52010-03-27 20:09:24 +00001040 // Add on one implicit def if it has a resolvable type.
1041 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1042 ++NumDefsToAdd;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001043 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +00001044 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001045
Chris Lattnerd7349192010-03-19 21:37:09 +00001046 if (Operator->isSubClassOf("SDNodeXForm"))
1047 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001048
Chris Lattnerd7349192010-03-19 21:37:09 +00001049 Operator->dump();
1050 errs() << "Unhandled node in GetNumNodeResults\n";
1051 exit(1);
1052}
1053
1054void TreePatternNode::print(raw_ostream &OS) const {
1055 if (isLeaf())
1056 OS << *getLeafValue();
1057 else
1058 OS << '(' << getOperator()->getName();
1059
1060 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1061 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +00001062
1063 if (!isLeaf()) {
1064 if (getNumChildren() != 0) {
1065 OS << " ";
1066 getChild(0)->print(OS);
1067 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1068 OS << ", ";
1069 getChild(i)->print(OS);
1070 }
1071 }
1072 OS << ")";
1073 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001074
Dan Gohman0540e172008-10-15 06:17:21 +00001075 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner54379062011-04-17 21:38:24 +00001076 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +00001077 if (TransformFn)
1078 OS << "<<X:" << TransformFn->getName() << ">>";
1079 if (!getName().empty())
1080 OS << ":$" << getName();
1081
1082}
1083void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001084 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +00001085}
1086
Scott Michel327d0652008-03-05 17:49:05 +00001087/// isIsomorphicTo - Return true if this node is recursively
1088/// isomorphic to the specified node. For this comparison, the node's
1089/// entire state is considered. The assigned name is ignored, since
1090/// nodes with differing names are considered isomorphic. However, if
1091/// the assigned name is present in the dependent variable set, then
1092/// the assigned name is considered significant and the node is
1093/// isomorphic if the names match.
1094bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1095 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001096 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +00001097 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +00001098 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00001099 getTransformFn() != N->getTransformFn())
1100 return false;
1101
1102 if (isLeaf()) {
David Greened4a90662011-07-11 18:25:51 +00001103 if (const DefInit *DI = dynamic_cast<const DefInit*>(getLeafValue())) {
1104 if (const DefInit *NDI = dynamic_cast<const DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +00001105 return ((DI->getDef() == NDI->getDef())
1106 && (DepVars.find(getName()) == DepVars.end()
1107 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +00001108 }
1109 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001110 return getLeafValue() == N->getLeafValue();
1111 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001112
Chris Lattner6cefb772008-01-05 22:25:12 +00001113 if (N->getOperator() != getOperator() ||
1114 N->getNumChildren() != getNumChildren()) return false;
1115 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00001116 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +00001117 return false;
1118 return true;
1119}
1120
1121/// clone - Make a copy of this tree and all of its children.
1122///
1123TreePatternNode *TreePatternNode::clone() const {
1124 TreePatternNode *New;
1125 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001126 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001127 } else {
1128 std::vector<TreePatternNode*> CChildren;
1129 CChildren.reserve(Children.size());
1130 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1131 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +00001132 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001133 }
1134 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001135 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +00001136 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00001137 New->setTransformFn(getTransformFn());
1138 return New;
1139}
1140
Chris Lattner47661322010-02-14 22:22:58 +00001141/// RemoveAllTypes - Recursively strip all the types of this tree.
1142void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +00001143 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1144 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +00001145 if (isLeaf()) return;
1146 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1147 getChild(i)->RemoveAllTypes();
1148}
1149
1150
Chris Lattner6cefb772008-01-05 22:25:12 +00001151/// SubstituteFormalArguments - Replace the formal arguments in this tree
1152/// with actual values specified by ArgMap.
1153void TreePatternNode::
1154SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1155 if (isLeaf()) return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001156
Chris Lattner6cefb772008-01-05 22:25:12 +00001157 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1158 TreePatternNode *Child = getChild(i);
1159 if (Child->isLeaf()) {
David Greened4a90662011-07-11 18:25:51 +00001160 const Init *Val = Child->getLeafValue();
1161 if (dynamic_cast<const DefInit*>(Val) &&
1162 static_cast<const DefInit*>(Val)->getDef()->getName() == "node") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001163 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +00001164 TreePatternNode *NewChild = ArgMap[Child->getName()];
1165 assert(NewChild && "Couldn't find formal argument!");
1166 assert((Child->getPredicateFns().empty() ||
1167 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1168 "Non-empty child predicate clobbered!");
1169 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +00001170 }
1171 } else {
1172 getChild(i)->SubstituteFormalArguments(ArgMap);
1173 }
1174 }
1175}
1176
1177
1178/// InlinePatternFragments - If this pattern refers to any pattern
1179/// fragments, inline them into place, giving us a pattern without any
1180/// PatFrag references.
1181TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1182 if (isLeaf()) return this; // nothing to do.
1183 Record *Op = getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001184
Chris Lattner6cefb772008-01-05 22:25:12 +00001185 if (!Op->isSubClassOf("PatFrag")) {
1186 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00001187 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1188 TreePatternNode *Child = getChild(i);
1189 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1190
1191 assert((Child->getPredicateFns().empty() ||
1192 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1193 "Non-empty child predicate clobbered!");
1194
1195 setChild(i, NewChild);
1196 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001197 return this;
1198 }
1199
1200 // Otherwise, we found a reference to a fragment. First, look up its
1201 // TreePattern record.
1202 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001203
Chris Lattner6cefb772008-01-05 22:25:12 +00001204 // Verify that we are passing the right number of operands.
1205 if (Frag->getNumArgs() != Children.size())
1206 TP.error("'" + Op->getName() + "' fragment requires " +
1207 utostr(Frag->getNumArgs()) + " operands!");
1208
1209 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1210
Chris Lattner54379062011-04-17 21:38:24 +00001211 TreePredicateFn PredFn(Frag);
1212 if (!PredFn.isAlwaysTrue())
1213 FragTree->addPredicateFn(PredFn);
Dan Gohman0540e172008-10-15 06:17:21 +00001214
Chris Lattner6cefb772008-01-05 22:25:12 +00001215 // Resolve formal arguments to their actual value.
1216 if (Frag->getNumArgs()) {
1217 // Compute the map of formal to actual arguments.
1218 std::map<std::string, TreePatternNode*> ArgMap;
1219 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1220 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001221
Chris Lattner6cefb772008-01-05 22:25:12 +00001222 FragTree->SubstituteFormalArguments(ArgMap);
1223 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001224
Chris Lattner6cefb772008-01-05 22:25:12 +00001225 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001226 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1227 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +00001228
1229 // Transfer in the old predicates.
1230 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1231 FragTree->addPredicateFn(getPredicateFns()[i]);
1232
Chris Lattner6cefb772008-01-05 22:25:12 +00001233 // Get a new copy of this fragment to stitch into here.
1234 //delete this; // FIXME: implement refcounting!
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001235
Chris Lattner2ca698d2008-06-30 03:02:03 +00001236 // The fragment we inlined could have recursive inlining that is needed. See
1237 // if there are any pattern fragments in it and inline them as needed.
1238 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001239}
1240
1241/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +00001242/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +00001243/// references from the register file information, for example.
1244///
Chris Lattnerd7349192010-03-19 21:37:09 +00001245static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1246 bool NotRegisters, TreePattern &TP) {
Owen Andersonbea6f612011-06-27 21:06:21 +00001247 // Check to see if this is a register operand.
1248 if (R->isSubClassOf("RegisterOperand")) {
1249 assert(ResNo == 0 && "Regoperand ref only has one result!");
1250 if (NotRegisters)
1251 return EEVT::TypeSet(); // Unknown.
1252 Record *RegClass = R->getValueAsDef("RegClass");
1253 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1254 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1255 }
1256
Chris Lattner2cacec52010-03-15 06:00:16 +00001257 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +00001258 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00001259 assert(ResNo == 0 && "Regclass ref only has one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001260 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001261 return EEVT::TypeSet(); // Unknown.
1262 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1263 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001264 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001265
Chris Lattner640a3f52010-03-23 23:50:31 +00001266 if (R->isSubClassOf("PatFrag")) {
1267 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001268 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001269 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001270 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001271
Chris Lattner640a3f52010-03-23 23:50:31 +00001272 if (R->isSubClassOf("Register")) {
1273 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001274 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001275 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001276 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001277 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001278 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +00001279
1280 if (R->isSubClassOf("SubRegIndex")) {
1281 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1282 return EEVT::TypeSet();
1283 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001284
Chris Lattner640a3f52010-03-23 23:50:31 +00001285 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1286 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001287 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001288 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001289 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001290
Chris Lattner640a3f52010-03-23 23:50:31 +00001291 if (R->isSubClassOf("ComplexPattern")) {
1292 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001293 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001294 return EEVT::TypeSet(); // Unknown.
1295 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1296 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001297 }
1298 if (R->isSubClassOf("PointerLikeRegClass")) {
1299 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001300 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001301 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001302
Chris Lattner640a3f52010-03-23 23:50:31 +00001303 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1304 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001305 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001306 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001307 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001308
Chris Lattner6cefb772008-01-05 22:25:12 +00001309 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001310 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001311}
1312
Chris Lattnere67bde52008-01-06 05:36:50 +00001313
1314/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1315/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1316const CodeGenIntrinsic *TreePatternNode::
1317getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1318 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1319 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1320 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1321 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001322
1323 unsigned IID =
David Greened4a90662011-07-11 18:25:51 +00001324 dynamic_cast<const IntInit*>(getChild(0)->getLeafValue())->getValue();
Chris Lattnere67bde52008-01-06 05:36:50 +00001325 return &CDP.getIntrinsicInfo(IID);
1326}
1327
Chris Lattner47661322010-02-14 22:22:58 +00001328/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1329/// return the ComplexPattern information, otherwise return null.
1330const ComplexPattern *
1331TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1332 if (!isLeaf()) return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001333
David Greened4a90662011-07-11 18:25:51 +00001334 const DefInit *DI = dynamic_cast<const DefInit*>(getLeafValue());
Chris Lattner47661322010-02-14 22:22:58 +00001335 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1336 return &CGP.getComplexPattern(DI->getDef());
1337 return 0;
1338}
1339
1340/// NodeHasProperty - Return true if this node has the specified property.
1341bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001342 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001343 if (isLeaf()) {
1344 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1345 return CP->hasProperty(Property);
1346 return false;
1347 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001348
Chris Lattner47661322010-02-14 22:22:58 +00001349 Record *Operator = getOperator();
1350 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001351
Chris Lattner47661322010-02-14 22:22:58 +00001352 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1353}
1354
1355
1356
1357
1358/// TreeHasProperty - Return true if any node in this tree has the specified
1359/// property.
1360bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001361 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001362 if (NodeHasProperty(Property, CGP))
1363 return true;
1364 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1365 if (getChild(i)->TreeHasProperty(Property, CGP))
1366 return true;
1367 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001368}
Chris Lattner47661322010-02-14 22:22:58 +00001369
Evan Cheng6bd95672008-06-16 20:29:38 +00001370/// isCommutativeIntrinsic - Return true if the node corresponds to a
1371/// commutative intrinsic.
1372bool
1373TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1374 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1375 return Int->isCommutative;
1376 return false;
1377}
1378
Chris Lattnere67bde52008-01-06 05:36:50 +00001379
Bob Wilson6c01ca92009-01-05 17:23:09 +00001380/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001381/// this node and its children in the tree. This returns true if it makes a
1382/// change, false otherwise. If a type contradiction is found, throw an
1383/// exception.
1384bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001385 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001386 if (isLeaf()) {
David Greened4a90662011-07-11 18:25:51 +00001387 if (const DefInit *DI = dynamic_cast<const DefInit*>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001388 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001389 bool MadeChange = false;
1390 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1391 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1392 NotRegisters, TP), TP);
1393 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001394 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001395
David Greened4a90662011-07-11 18:25:51 +00001396 if (const IntInit *II = dynamic_cast<const IntInit*>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001397 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001398
Chris Lattnerd7349192010-03-19 21:37:09 +00001399 // Int inits are always integers. :)
1400 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001401
Chris Lattnerd7349192010-03-19 21:37:09 +00001402 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001403 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001404
Chris Lattnerd7349192010-03-19 21:37:09 +00001405 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001406 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1407 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001408
Chris Lattner2cacec52010-03-15 06:00:16 +00001409 unsigned Size = EVT(VT).getSizeInBits();
1410 // Make sure that the value is representable for this type.
1411 if (Size >= 32) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001412
Chris Lattner2cacec52010-03-15 06:00:16 +00001413 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1414 if (Val == II->getValue()) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001415
Chris Lattner2cacec52010-03-15 06:00:16 +00001416 // If sign-extended doesn't fit, does it fit as unsigned?
1417 unsigned ValueMask;
1418 unsigned UnsignedVal;
1419 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1420 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001421
Chris Lattner2cacec52010-03-15 06:00:16 +00001422 if ((ValueMask & UnsignedVal) == UnsignedVal)
1423 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001424
Chris Lattner2cacec52010-03-15 06:00:16 +00001425 TP.error("Integer value '" + itostr(II->getValue())+
Chris Lattnerd7349192010-03-19 21:37:09 +00001426 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001427 return MadeChange;
1428 }
1429 return false;
1430 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001431
Chris Lattner6cefb772008-01-05 22:25:12 +00001432 // special handling for set, which isn't really an SDNode.
1433 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001434 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1435 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001436 unsigned NC = getNumChildren();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001437
Chris Lattnerd7349192010-03-19 21:37:09 +00001438 TreePatternNode *SetVal = getChild(NC-1);
1439 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1440
Chris Lattner6cefb772008-01-05 22:25:12 +00001441 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001442 TreePatternNode *Child = getChild(i);
1443 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001444
Chris Lattner6cefb772008-01-05 22:25:12 +00001445 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001446 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1447 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001448 }
1449 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001450 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001451
Chris Lattner310adf12010-03-27 02:53:27 +00001452 if (getOperator()->getName() == "implicit") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001453 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1454
Chris Lattner6cefb772008-01-05 22:25:12 +00001455 bool MadeChange = false;
1456 for (unsigned i = 0; i < getNumChildren(); ++i)
1457 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001458 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001459 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001460
Chris Lattner6eb30122010-02-23 05:51:07 +00001461 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001462 bool MadeChange = false;
1463 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1464 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001465
Chris Lattnerd7349192010-03-19 21:37:09 +00001466 assert(getChild(0)->getNumTypes() == 1 &&
1467 getChild(1)->getNumTypes() == 1 && "Unhandled case");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001468
Chris Lattner2cacec52010-03-15 06:00:16 +00001469 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1470 // what type it gets, so if it didn't get a concrete type just give it the
1471 // first viable type from the reg class.
Chris Lattnerd7349192010-03-19 21:37:09 +00001472 if (!getChild(1)->hasTypeSet(0) &&
1473 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1474 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1475 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001476 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001477 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001478 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001479
Chris Lattner6eb30122010-02-23 05:51:07 +00001480 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001481 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001482
Chris Lattner6cefb772008-01-05 22:25:12 +00001483 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001484 unsigned NumRetVTs = Int->IS.RetVTs.size();
1485 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001486
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001487 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001488 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001489
Chris Lattnerd7349192010-03-19 21:37:09 +00001490 if (getNumChildren() != NumParamVTs + 1)
Chris Lattnere67bde52008-01-06 05:36:50 +00001491 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001492 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001493 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001494
1495 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001496 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001497
Chris Lattnerd7349192010-03-19 21:37:09 +00001498 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1499 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001500
Chris Lattnerd7349192010-03-19 21:37:09 +00001501 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1502 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1503 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001504 }
1505 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001506 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001507
Chris Lattner6eb30122010-02-23 05:51:07 +00001508 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001509 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001510
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001511 // Check that the number of operands is sane. Negative operands -> varargs.
1512 if (NI.getNumOperands() >= 0 &&
1513 getNumChildren() != (unsigned)NI.getNumOperands())
1514 TP.error(getOperator()->getName() + " node requires exactly " +
1515 itostr(NI.getNumOperands()) + " operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001516
Chris Lattner6cefb772008-01-05 22:25:12 +00001517 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1518 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1519 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001520 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001521 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001522
Chris Lattner6eb30122010-02-23 05:51:07 +00001523 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001524 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001525 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001526 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001527
Chris Lattner0be6fe72010-03-27 19:15:02 +00001528 bool MadeChange = false;
1529
1530 // Apply the result types to the node, these come from the things in the
1531 // (outs) list of the instruction.
1532 // FIXME: Cap at one result so far.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001533 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001534 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1535 Record *ResultNode = Inst.getResult(ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001536
Chris Lattnera938ac62009-07-29 20:43:05 +00001537 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001538 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
Owen Andersonbea6f612011-06-27 21:06:21 +00001539 } else if (ResultNode->isSubClassOf("RegisterOperand")) {
1540 Record *RegClass = ResultNode->getValueAsDef("RegClass");
1541 const CodeGenRegisterClass &RC =
1542 CDP.getTargetInfo().getRegisterClass(RegClass);
1543 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001544 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001545 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001546 } else {
1547 assert(ResultNode->isSubClassOf("RegisterClass") &&
1548 "Operands should be register classes!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001549 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001550 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001551 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001552 }
Chris Lattner0be6fe72010-03-27 19:15:02 +00001553 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001554
Chris Lattner0be6fe72010-03-27 19:15:02 +00001555 // If the instruction has implicit defs, we apply the first one as a result.
1556 // FIXME: This sucks, it should apply all implicit defs.
1557 if (!InstInfo.ImplicitDefs.empty()) {
1558 unsigned ResNo = NumResultsToAdd;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001559
Chris Lattner9414ae52010-03-27 20:09:24 +00001560 // FIXME: Generalize to multiple possible types and multiple possible
1561 // ImplicitDefs.
1562 MVT::SimpleValueType VT =
1563 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001564
Chris Lattner9414ae52010-03-27 20:09:24 +00001565 if (VT != MVT::Other)
1566 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001567 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001568
Chris Lattner2cacec52010-03-15 06:00:16 +00001569 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1570 // be the same.
1571 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001572 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1573 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1574 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001575 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001576
1577 unsigned ChildNo = 0;
1578 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1579 Record *OperandNode = Inst.getOperand(i);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001580
Chris Lattner6cefb772008-01-05 22:25:12 +00001581 // If the instruction expects a predicate or optional def operand, we
1582 // codegen this by setting the operand to it's default value if it has a
1583 // non-empty DefaultOps field.
1584 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1585 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1586 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1587 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001588
Chris Lattner6cefb772008-01-05 22:25:12 +00001589 // Verify that we didn't run out of provided operands.
1590 if (ChildNo >= getNumChildren())
1591 TP.error("Instruction '" + getOperator()->getName() +
1592 "' expects more operands than were provided.");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001593
Owen Anderson825b72b2009-08-11 20:47:22 +00001594 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001595 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001596 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001597
Chris Lattner6cefb772008-01-05 22:25:12 +00001598 if (OperandNode->isSubClassOf("RegisterClass")) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001599 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001600 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001601 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Owen Andersonbea6f612011-06-27 21:06:21 +00001602 } else if (OperandNode->isSubClassOf("RegisterOperand")) {
1603 Record *RegClass = OperandNode->getValueAsDef("RegClass");
1604 const CodeGenRegisterClass &RC =
1605 CDP.getTargetInfo().getRegisterClass(RegClass);
1606 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001607 } else if (OperandNode->isSubClassOf("Operand")) {
1608 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattner0be6fe72010-03-27 19:15:02 +00001609 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001610 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001611 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001612 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001613 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001614 } else {
1615 assert(0 && "Unknown operand type!");
1616 abort();
1617 }
1618 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1619 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001620
Christopher Lamb02f69372008-03-10 04:16:09 +00001621 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001622 TP.error("Instruction '" + getOperator()->getName() +
1623 "' was provided too many operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001624
Chris Lattner6cefb772008-01-05 22:25:12 +00001625 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001626 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001627
Chris Lattner6eb30122010-02-23 05:51:07 +00001628 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001629
Chris Lattner6eb30122010-02-23 05:51:07 +00001630 // Node transforms always take one operand.
1631 if (getNumChildren() != 1)
1632 TP.error("Node transform '" + getOperator()->getName() +
1633 "' requires one operand!");
1634
Chris Lattner2cacec52010-03-15 06:00:16 +00001635 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1636
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001637
Chris Lattner6eb30122010-02-23 05:51:07 +00001638 // If either the output or input of the xform does not have exact
1639 // type info. We assume they must be the same. Otherwise, it is perfectly
1640 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001641#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001642 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001643 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1644 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001645 return MadeChange;
1646 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001647#endif
1648 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001649}
1650
1651/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1652/// RHS of a commutative operation, not the on LHS.
1653static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1654 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1655 return true;
David Greened4a90662011-07-11 18:25:51 +00001656 if (N->isLeaf() && dynamic_cast<const IntInit*>(N->getLeafValue()))
Chris Lattner6cefb772008-01-05 22:25:12 +00001657 return true;
1658 return false;
1659}
1660
1661
1662/// canPatternMatch - If it is impossible for this pattern to match on this
1663/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001664/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001665/// that can never possibly work), and to prevent the pattern permuter from
1666/// generating stuff that is useless.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001667bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001668 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001669 if (isLeaf()) return true;
1670
1671 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1672 if (!getChild(i)->canPatternMatch(Reason, CDP))
1673 return false;
1674
1675 // If this is an intrinsic, handle cases that would make it not match. For
1676 // example, if an operand is required to be an immediate.
1677 if (getOperator()->isSubClassOf("Intrinsic")) {
1678 // TODO:
1679 return true;
1680 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001681
Chris Lattner6cefb772008-01-05 22:25:12 +00001682 // If this node is a commutative operator, check that the LHS isn't an
1683 // immediate.
1684 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001685 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1686 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001687 // Scan all of the operands of the node and make sure that only the last one
1688 // is a constant node, unless the RHS also is.
1689 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001690 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1691 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001692 if (OnlyOnRHSOfCommutative(getChild(i))) {
1693 Reason="Immediate value must be on the RHS of commutative operators!";
1694 return false;
1695 }
1696 }
1697 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001698
Chris Lattner6cefb772008-01-05 22:25:12 +00001699 return true;
1700}
1701
1702//===----------------------------------------------------------------------===//
1703// TreePattern implementation
1704//
1705
David Greened4a90662011-07-11 18:25:51 +00001706TreePattern::TreePattern(Record *TheRec, const ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001707 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001708 isInputPattern = isInput;
1709 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattnerc2173052010-03-28 06:50:34 +00001710 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001711}
1712
David Greened4a90662011-07-11 18:25:51 +00001713TreePattern::TreePattern(Record *TheRec, const DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001714 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001715 isInputPattern = isInput;
Chris Lattnerc2173052010-03-28 06:50:34 +00001716 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001717}
1718
1719TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001720 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001721 isInputPattern = isInput;
1722 Trees.push_back(Pat);
1723}
1724
Chris Lattner6cefb772008-01-05 22:25:12 +00001725void TreePattern::error(const std::string &Msg) const {
1726 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001727 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001728}
1729
Chris Lattner2cacec52010-03-15 06:00:16 +00001730void TreePattern::ComputeNamedNodes() {
1731 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1732 ComputeNamedNodes(Trees[i]);
1733}
1734
1735void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1736 if (!N->getName().empty())
1737 NamedNodes[N->getName()].push_back(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001738
Chris Lattner2cacec52010-03-15 06:00:16 +00001739 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1740 ComputeNamedNodes(N->getChild(i));
1741}
1742
Chris Lattnerd7349192010-03-19 21:37:09 +00001743
David Greened4a90662011-07-11 18:25:51 +00001744TreePatternNode *TreePattern::ParseTreePattern(const Init *TheInit,
1745 StringRef OpName){
1746 if (const DefInit *DI = dynamic_cast<const DefInit*>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001747 Record *R = DI->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001748
Chris Lattnerc2173052010-03-28 06:50:34 +00001749 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbach66c9ee72011-07-06 23:38:13 +00001750 // TreePatternNode of its own. For example:
Chris Lattnerc2173052010-03-28 06:50:34 +00001751 /// (foo GPR, imm) -> (foo GPR, (imm))
1752 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greened4a90662011-07-11 18:25:51 +00001753 return ParseTreePattern(DagInit::Create(DI, "",
1754 std::vector<std::pair<const Init*, std::string> >()),
Chris Lattnerc2173052010-03-28 06:50:34 +00001755 OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001756
Chris Lattnerc2173052010-03-28 06:50:34 +00001757 // Input argument?
1758 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001759 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001760 if (OpName.empty())
1761 error("'node' argument requires a name to match with operand list");
1762 Args.push_back(OpName);
1763 }
1764
1765 Res->setName(OpName);
1766 return Res;
1767 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001768
David Greened4a90662011-07-11 18:25:51 +00001769 if (const IntInit *II = dynamic_cast<const IntInit*>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001770 if (!OpName.empty())
1771 error("Constant int argument should not have a name!");
1772 return new TreePatternNode(II, 1);
1773 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001774
David Greened4a90662011-07-11 18:25:51 +00001775 if (const BitsInit *BI = dynamic_cast<const BitsInit*>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001776 // Turn this into an IntInit.
David Greened4a90662011-07-11 18:25:51 +00001777 const Init *II = BI->convertInitializerTo(new IntRecTy());
1778 if (II == 0 || !dynamic_cast<const IntInit*>(II))
Chris Lattnerc2173052010-03-28 06:50:34 +00001779 error("Bits value must be constants!");
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001780 return ParseTreePattern(II, OpName);
Chris Lattnerc2173052010-03-28 06:50:34 +00001781 }
1782
David Greened4a90662011-07-11 18:25:51 +00001783 const DagInit *Dag = dynamic_cast<const DagInit*>(TheInit);
Chris Lattnerc2173052010-03-28 06:50:34 +00001784 if (!Dag) {
1785 TheInit->dump();
1786 error("Pattern has unexpected init kind!");
1787 }
David Greened4a90662011-07-11 18:25:51 +00001788 const DefInit *OpDef = dynamic_cast<const DefInit*>(Dag->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001789 if (!OpDef) error("Pattern has unexpected operator type!");
1790 Record *Operator = OpDef->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001791
Chris Lattner6cefb772008-01-05 22:25:12 +00001792 if (Operator->isSubClassOf("ValueType")) {
1793 // If the operator is a ValueType, then this must be "type cast" of a leaf
1794 // node.
1795 if (Dag->getNumArgs() != 1)
1796 error("Type cast only takes one operand!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001797
Chris Lattnerc2173052010-03-28 06:50:34 +00001798 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001799
Chris Lattner6cefb772008-01-05 22:25:12 +00001800 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001801 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1802 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001803
Chris Lattnerc2173052010-03-28 06:50:34 +00001804 if (!OpName.empty())
1805 error("ValueType cast should not have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001806 return New;
1807 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001808
Chris Lattner6cefb772008-01-05 22:25:12 +00001809 // Verify that this is something that makes sense for an operator.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001810 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begeman7cee8172009-03-19 05:21:56 +00001811 !Operator->isSubClassOf("SDNode") &&
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001812 !Operator->isSubClassOf("Instruction") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001813 !Operator->isSubClassOf("SDNodeXForm") &&
1814 !Operator->isSubClassOf("Intrinsic") &&
1815 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00001816 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00001817 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001818
Chris Lattner6cefb772008-01-05 22:25:12 +00001819 // Check to see if this is something that is illegal in an input pattern.
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001820 if (isInputPattern) {
1821 if (Operator->isSubClassOf("Instruction") ||
1822 Operator->isSubClassOf("SDNodeXForm"))
1823 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1824 } else {
1825 if (Operator->isSubClassOf("Intrinsic"))
1826 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001827
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001828 if (Operator->isSubClassOf("SDNode") &&
1829 Operator->getName() != "imm" &&
1830 Operator->getName() != "fpimm" &&
1831 Operator->getName() != "tglobaltlsaddr" &&
1832 Operator->getName() != "tconstpool" &&
1833 Operator->getName() != "tjumptable" &&
1834 Operator->getName() != "tframeindex" &&
1835 Operator->getName() != "texternalsym" &&
1836 Operator->getName() != "tblockaddress" &&
1837 Operator->getName() != "tglobaladdr" &&
1838 Operator->getName() != "bb" &&
1839 Operator->getName() != "vt")
1840 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1841 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001842
Chris Lattner6cefb772008-01-05 22:25:12 +00001843 std::vector<TreePatternNode*> Children;
Chris Lattnerc2173052010-03-28 06:50:34 +00001844
1845 // Parse all the operands.
1846 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1847 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001848
Chris Lattner6cefb772008-01-05 22:25:12 +00001849 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001850 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner6cefb772008-01-05 22:25:12 +00001851 // convert the intrinsic name to a number.
1852 if (Operator->isSubClassOf("Intrinsic")) {
1853 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1854 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1855
1856 // If this intrinsic returns void, it must have side-effects and thus a
1857 // chain.
Chris Lattnerc2173052010-03-28 06:50:34 +00001858 if (Int.IS.RetVTs.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001859 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001860 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner6cefb772008-01-05 22:25:12 +00001861 // Has side-effects, requires chain.
1862 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001863 else // Otherwise, no chain.
Chris Lattner6cefb772008-01-05 22:25:12 +00001864 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001865
David Greened4a90662011-07-11 18:25:51 +00001866 TreePatternNode *IIDNode = new TreePatternNode(IntInit::Create(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001867 Children.insert(Children.begin(), IIDNode);
1868 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001869
Chris Lattnerd7349192010-03-19 21:37:09 +00001870 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1871 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattnerc2173052010-03-28 06:50:34 +00001872 Result->setName(OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001873
Chris Lattnerc2173052010-03-28 06:50:34 +00001874 if (!Dag->getName().empty()) {
1875 assert(Result->getName().empty());
1876 Result->setName(Dag->getName());
1877 }
Nate Begeman7cee8172009-03-19 05:21:56 +00001878 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001879}
1880
Chris Lattner7a0eb912010-03-28 08:38:32 +00001881/// SimplifyTree - See if we can simplify this tree to eliminate something that
1882/// will never match in favor of something obvious that will. This is here
1883/// strictly as a convenience to target authors because it allows them to write
1884/// more type generic things and have useless type casts fold away.
1885///
1886/// This returns true if any change is made.
1887static bool SimplifyTree(TreePatternNode *&N) {
1888 if (N->isLeaf())
1889 return false;
1890
1891 // If we have a bitconvert with a resolved type and if the source and
1892 // destination types are the same, then the bitconvert is useless, remove it.
1893 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattner7a0eb912010-03-28 08:38:32 +00001894 N->getExtType(0).isConcrete() &&
1895 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1896 N->getName().empty()) {
1897 N = N->getChild(0);
1898 SimplifyTree(N);
1899 return true;
1900 }
1901
1902 // Walk all children.
1903 bool MadeChange = false;
1904 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1905 TreePatternNode *Child = N->getChild(i);
1906 MadeChange |= SimplifyTree(Child);
1907 N->setChild(i, Child);
1908 }
1909 return MadeChange;
1910}
1911
1912
1913
Chris Lattner6cefb772008-01-05 22:25:12 +00001914/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001915/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001916/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001917bool TreePattern::
1918InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1919 if (NamedNodes.empty())
1920 ComputeNamedNodes();
1921
Chris Lattner6cefb772008-01-05 22:25:12 +00001922 bool MadeChange = true;
1923 while (MadeChange) {
1924 MadeChange = false;
Chris Lattner7a0eb912010-03-28 08:38:32 +00001925 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001926 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner7a0eb912010-03-28 08:38:32 +00001927 MadeChange |= SimplifyTree(Trees[i]);
1928 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001929
1930 // If there are constraints on our named nodes, apply them.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001931 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattner2cacec52010-03-15 06:00:16 +00001932 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1933 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001934
Chris Lattner2cacec52010-03-15 06:00:16 +00001935 // If we have input named node types, propagate their types to the named
1936 // values here.
1937 if (InNamedTypes) {
1938 // FIXME: Should be error?
1939 assert(InNamedTypes->count(I->getKey()) &&
1940 "Named node in output pattern but not input pattern?");
1941
1942 const SmallVectorImpl<TreePatternNode*> &InNodes =
1943 InNamedTypes->find(I->getKey())->second;
1944
1945 // The input types should be fully resolved by now.
1946 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1947 // If this node is a register class, and it is the root of the pattern
1948 // then we're mapping something onto an input register. We allow
1949 // changing the type of the input register in this case. This allows
1950 // us to match things like:
1951 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1952 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
David Greened4a90662011-07-11 18:25:51 +00001953 const DefInit *DI =
1954 dynamic_cast<const DefInit*>(Nodes[i]->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00001955 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
1956 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner2cacec52010-03-15 06:00:16 +00001957 continue;
1958 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001959
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001960 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001961 InNodes[0]->getNumTypes() == 1 &&
1962 "FIXME: cannot name multiple result nodes yet");
1963 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1964 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001965 }
1966 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001967
Chris Lattner2cacec52010-03-15 06:00:16 +00001968 // If there are multiple nodes with the same name, they must all have the
1969 // same type.
1970 if (I->second.size() > 1) {
1971 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001972 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001973 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001974 "FIXME: cannot name multiple result nodes yet");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001975
Chris Lattnerd7349192010-03-19 21:37:09 +00001976 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1977 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001978 }
1979 }
1980 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001981 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001982
Chris Lattner6cefb772008-01-05 22:25:12 +00001983 bool HasUnresolvedTypes = false;
1984 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1985 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1986 return !HasUnresolvedTypes;
1987}
1988
Daniel Dunbar1a551802009-07-03 00:10:29 +00001989void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001990 OS << getRecord()->getName();
1991 if (!Args.empty()) {
1992 OS << "(" << Args[0];
1993 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1994 OS << ", " << Args[i];
1995 OS << ")";
1996 }
1997 OS << ": ";
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001998
Chris Lattner6cefb772008-01-05 22:25:12 +00001999 if (Trees.size() > 1)
2000 OS << "[\n";
2001 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2002 OS << "\t";
2003 Trees[i]->print(OS);
2004 OS << "\n";
2005 }
2006
2007 if (Trees.size() > 1)
2008 OS << "]\n";
2009}
2010
Daniel Dunbar1a551802009-07-03 00:10:29 +00002011void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00002012
2013//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00002014// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00002015//
2016
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002017CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner67db8832010-12-13 00:23:57 +00002018 Records(R), Target(R) {
2019
Dale Johannesen49de9822009-02-05 01:49:45 +00002020 Intrinsics = LoadIntrinsics(Records, false);
2021 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00002022 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00002023 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00002024 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002025 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00002026 ParseDefaultOperands();
2027 ParseInstructions();
2028 ParsePatterns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002029
Chris Lattner6cefb772008-01-05 22:25:12 +00002030 // Generate variants. For example, commutative patterns can match
2031 // multiple ways. Add them to PatternsToMatch as well.
2032 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00002033
2034 // Infer instruction flags. For example, we can detect loads,
2035 // stores, and side effects in many cases by examining an
2036 // instruction's pattern.
2037 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00002038}
2039
Chris Lattnerfe718932008-01-06 01:10:31 +00002040CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002041 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002042 E = PatternFragments.end(); I != E; ++I)
2043 delete I->second;
2044}
2045
2046
Chris Lattnerfe718932008-01-06 01:10:31 +00002047Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00002048 Record *N = Records.getDef(Name);
2049 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002050 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00002051 exit(1);
2052 }
2053 return N;
2054}
2055
2056// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00002057void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002058 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2059 while (!Nodes.empty()) {
2060 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2061 Nodes.pop_back();
2062 }
2063
Jim Grosbachda4231f2009-03-26 16:17:51 +00002064 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00002065 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2066 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2067 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2068}
2069
2070/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2071/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002072void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002073 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2074 while (!Xforms.empty()) {
2075 Record *XFormNode = Xforms.back();
2076 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2077 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00002078 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002079
2080 Xforms.pop_back();
2081 }
2082}
2083
Chris Lattnerfe718932008-01-06 01:10:31 +00002084void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002085 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2086 while (!AMs.empty()) {
2087 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2088 AMs.pop_back();
2089 }
2090}
2091
2092
2093/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2094/// file, building up the PatternFragments map. After we've collected them all,
2095/// inline fragments together as necessary, so that there are no references left
2096/// inside a pattern fragment to a pattern fragment.
2097///
Chris Lattnerfe718932008-01-06 01:10:31 +00002098void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002099 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002100
Chris Lattnerdc32f982008-01-05 22:43:57 +00002101 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002102 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
David Greened4a90662011-07-11 18:25:51 +00002103 const DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattner6cefb772008-01-05 22:25:12 +00002104 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2105 PatternFragments[Fragments[i]] = P;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002106
Chris Lattnerdc32f982008-01-05 22:43:57 +00002107 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00002108 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002109 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002110
Chris Lattnerdc32f982008-01-05 22:43:57 +00002111 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00002112 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002113
Chris Lattner6cefb772008-01-05 22:25:12 +00002114 // Parse the operands list.
David Greened4a90662011-07-11 18:25:51 +00002115 const DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2116 const DefInit *OpsOp = dynamic_cast<const DefInit*>(OpsList->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00002117 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00002118 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00002119 if (!OpsOp ||
2120 (OpsOp->getDef()->getName() != "ops" &&
2121 OpsOp->getDef()->getName() != "outs" &&
2122 OpsOp->getDef()->getName() != "ins"))
2123 P->error("Operands list should start with '(ops ... '!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002124
2125 // Copy over the arguments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002126 Args.clear();
2127 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
David Greened4a90662011-07-11 18:25:51 +00002128 if (!dynamic_cast<const DefInit*>(OpsList->getArg(j)) ||
2129 static_cast<const DefInit*>(OpsList->getArg(j))->
Chris Lattner6cefb772008-01-05 22:25:12 +00002130 getDef()->getName() != "node")
2131 P->error("Operands list should all be 'node' values.");
2132 if (OpsList->getArgName(j).empty())
2133 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002134 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00002135 P->error("'" + OpsList->getArgName(j) +
2136 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002137 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00002138 Args.push_back(OpsList->getArgName(j));
2139 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002140
Chris Lattnerdc32f982008-01-05 22:43:57 +00002141 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00002142 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00002143 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002144
Chris Lattnerdc32f982008-01-05 22:43:57 +00002145 // If there is a code init for this fragment, keep track of the fact that
2146 // this fragment uses it.
Chris Lattner54379062011-04-17 21:38:24 +00002147 TreePredicateFn PredFn(P);
2148 if (!PredFn.isAlwaysTrue())
2149 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002150
Chris Lattner6cefb772008-01-05 22:25:12 +00002151 // If there is a node transformation corresponding to this, keep track of
2152 // it.
2153 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2154 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2155 P->getOnlyTree()->setTransformFn(Transform);
2156 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002157
Chris Lattner6cefb772008-01-05 22:25:12 +00002158 // Now that we've parsed all of the tree fragments, do a closure on them so
2159 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00002160 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2161 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00002162 ThePat->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002163
Chris Lattner6cefb772008-01-05 22:25:12 +00002164 // Infer as many types as possible. Don't worry about it if we don't infer
2165 // all of them, some may depend on the inputs of the pattern.
2166 try {
2167 ThePat->InferAllTypes();
2168 } catch (...) {
2169 // If this pattern fragment is not supported by this target (no types can
2170 // satisfy its constraints), just ignore it. If the bogus pattern is
2171 // actually used by instructions, the type consistency error will be
2172 // reported there.
2173 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002174
Chris Lattner6cefb772008-01-05 22:25:12 +00002175 // If debugging, print out the pattern fragment result.
2176 DEBUG(ThePat->dump());
2177 }
2178}
2179
Chris Lattnerfe718932008-01-06 01:10:31 +00002180void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002181 std::vector<Record*> DefaultOps[2];
2182 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
2183 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
2184
2185 // Find some SDNode.
2186 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greened4a90662011-07-11 18:25:51 +00002187 const Init *SomeSDNode = DefInit::Create(SDNodes.begin()->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002188
Chris Lattner6cefb772008-01-05 22:25:12 +00002189 for (unsigned iter = 0; iter != 2; ++iter) {
2190 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
David Greened4a90662011-07-11 18:25:51 +00002191 const DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002192
Chris Lattner6cefb772008-01-05 22:25:12 +00002193 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2194 // SomeSDnode so that we can parse this.
David Greened4a90662011-07-11 18:25:51 +00002195 std::vector<std::pair<const Init*, std::string> > Ops;
Chris Lattner6cefb772008-01-05 22:25:12 +00002196 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2197 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2198 DefaultInfo->getArgName(op)));
David Greened4a90662011-07-11 18:25:51 +00002199 const DagInit *DI = DagInit::Create(SomeSDNode, "", Ops);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002200
Chris Lattner6cefb772008-01-05 22:25:12 +00002201 // Create a TreePattern to parse this.
2202 TreePattern P(DefaultOps[iter][i], DI, false, *this);
2203 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2204
2205 // Copy the operands over into a DAGDefaultOperand.
2206 DAGDefaultOperand DefaultOpInfo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002207
Chris Lattner6cefb772008-01-05 22:25:12 +00002208 TreePatternNode *T = P.getTree(0);
2209 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2210 TreePatternNode *TPN = T->getChild(op);
2211 while (TPN->ApplyTypeConstraints(P, false))
2212 /* Resolve all types */;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002213
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002214 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002215 if (iter == 0)
2216 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00002217 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00002218 else
2219 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00002220 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002221 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002222 DefaultOpInfo.DefaultOps.push_back(TPN);
2223 }
2224
2225 // Insert it into the DefaultOperands map so we can find it later.
2226 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
2227 }
2228 }
2229}
2230
2231/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2232/// instruction input. Return true if this is a real use.
2233static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002234 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002235 // No name -> not interesting.
2236 if (Pat->getName().empty()) {
2237 if (Pat->isLeaf()) {
David Greened4a90662011-07-11 18:25:51 +00002238 const DefInit *DI = dynamic_cast<const DefInit*>(Pat->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00002239 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2240 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner6cefb772008-01-05 22:25:12 +00002241 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002242 }
2243 return false;
2244 }
2245
2246 Record *Rec;
2247 if (Pat->isLeaf()) {
David Greened4a90662011-07-11 18:25:51 +00002248 const DefInit *DI = dynamic_cast<const DefInit*>(Pat->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002249 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2250 Rec = DI->getDef();
2251 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00002252 Rec = Pat->getOperator();
2253 }
2254
2255 // SRCVALUE nodes are ignored.
2256 if (Rec->getName() == "srcvalue")
2257 return false;
2258
2259 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2260 if (!Slot) {
2261 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00002262 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00002263 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00002264 Record *SlotRec;
2265 if (Slot->isLeaf()) {
David Greened4a90662011-07-11 18:25:51 +00002266 SlotRec = dynamic_cast<const DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattner53d09bd2010-02-23 05:59:10 +00002267 } else {
2268 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2269 SlotRec = Slot->getOperator();
2270 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002271
Chris Lattner53d09bd2010-02-23 05:59:10 +00002272 // Ensure that the inputs agree if we've already seen this input.
2273 if (Rec != SlotRec)
2274 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00002275 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00002276 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00002277 return true;
2278}
2279
2280/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2281/// part of "I", the instruction), computing the set of inputs and outputs of
2282/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00002283void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00002284FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2285 std::map<std::string, TreePatternNode*> &InstInputs,
2286 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner6cefb772008-01-05 22:25:12 +00002287 std::vector<Record*> &InstImpResults) {
2288 if (Pat->isLeaf()) {
Chris Lattneracfb70f2010-04-20 06:30:25 +00002289 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002290 if (!isUse && Pat->getTransformFn())
2291 I->error("Cannot specify a transform function for a non-input value!");
2292 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002293 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002294
Chris Lattner84aa60b2010-02-17 06:53:36 +00002295 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002296 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2297 TreePatternNode *Dest = Pat->getChild(i);
2298 if (!Dest->isLeaf())
2299 I->error("implicitly defined value should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002300
David Greened4a90662011-07-11 18:25:51 +00002301 const DefInit *Val = dynamic_cast<const DefInit*>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002302 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2303 I->error("implicitly defined value should be a register!");
2304 InstImpResults.push_back(Val->getDef());
2305 }
2306 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002307 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002308
Chris Lattner84aa60b2010-02-17 06:53:36 +00002309 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002310 // If this is not a set, verify that the children nodes are not void typed,
2311 // and recurse.
2312 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002313 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002314 I->error("Cannot have void nodes inside of patterns!");
2315 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002316 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002317 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002318
Chris Lattner6cefb772008-01-05 22:25:12 +00002319 // If this is a non-leaf node with no children, treat it basically as if
2320 // it were a leaf. This handles nodes like (imm).
Chris Lattneracfb70f2010-04-20 06:30:25 +00002321 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002322
Chris Lattner6cefb772008-01-05 22:25:12 +00002323 if (!isUse && Pat->getTransformFn())
2324 I->error("Cannot specify a transform function for a non-input value!");
2325 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002326 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002327
Chris Lattner6cefb772008-01-05 22:25:12 +00002328 // Otherwise, this is a set, validate and collect instruction results.
2329 if (Pat->getNumChildren() == 0)
2330 I->error("set requires operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002331
Chris Lattner6cefb772008-01-05 22:25:12 +00002332 if (Pat->getTransformFn())
2333 I->error("Cannot specify a transform function on a set node!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002334
Chris Lattner6cefb772008-01-05 22:25:12 +00002335 // Check the set destinations.
2336 unsigned NumDests = Pat->getNumChildren()-1;
2337 for (unsigned i = 0; i != NumDests; ++i) {
2338 TreePatternNode *Dest = Pat->getChild(i);
2339 if (!Dest->isLeaf())
2340 I->error("set destination should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002341
David Greened4a90662011-07-11 18:25:51 +00002342 const DefInit *Val = dynamic_cast<const DefInit*>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002343 if (!Val)
2344 I->error("set destination should be a register!");
2345
2346 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Owen Andersonbea6f612011-06-27 21:06:21 +00002347 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002348 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002349 if (Dest->getName().empty())
2350 I->error("set destination must have a name!");
2351 if (InstResults.count(Dest->getName()))
2352 I->error("cannot set '" + Dest->getName() +"' multiple times");
2353 InstResults[Dest->getName()] = Dest;
2354 } else if (Val->getDef()->isSubClassOf("Register")) {
2355 InstImpResults.push_back(Val->getDef());
2356 } else {
2357 I->error("set destination should be a register!");
2358 }
2359 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002360
Chris Lattner6cefb772008-01-05 22:25:12 +00002361 // Verify and collect info from the computation.
2362 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattneracfb70f2010-04-20 06:30:25 +00002363 InstInputs, InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002364}
2365
Dan Gohmanee4fa192008-04-03 00:02:49 +00002366//===----------------------------------------------------------------------===//
2367// Instruction Analysis
2368//===----------------------------------------------------------------------===//
2369
2370class InstAnalyzer {
2371 const CodeGenDAGPatterns &CDP;
2372 bool &mayStore;
2373 bool &mayLoad;
Evan Cheng0f040a22011-03-15 05:09:26 +00002374 bool &IsBitcast;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002375 bool &HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002376 bool &IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002377public:
2378 InstAnalyzer(const CodeGenDAGPatterns &cdp,
Evan Cheng0f040a22011-03-15 05:09:26 +00002379 bool &maystore, bool &mayload, bool &isbc, bool &hse, bool &isv)
2380 : CDP(cdp), mayStore(maystore), mayLoad(mayload), IsBitcast(isbc),
2381 HasSideEffects(hse), IsVariadic(isv) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002382 }
2383
2384 /// Analyze - Analyze the specified instruction, returning true if the
2385 /// instruction had a pattern.
2386 bool Analyze(Record *InstRecord) {
2387 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2388 if (Pattern == 0) {
2389 HasSideEffects = 1;
2390 return false; // No pattern.
2391 }
2392
2393 // FIXME: Assume only the first tree is the pattern. The others are clobber
2394 // nodes.
2395 AnalyzeNode(Pattern->getTree(0));
2396 return true;
2397 }
2398
2399private:
Evan Cheng0f040a22011-03-15 05:09:26 +00002400 bool IsNodeBitcast(const TreePatternNode *N) const {
2401 if (HasSideEffects || mayLoad || mayStore || IsVariadic)
2402 return false;
2403
2404 if (N->getNumChildren() != 2)
2405 return false;
2406
2407 const TreePatternNode *N0 = N->getChild(0);
David Greened4a90662011-07-11 18:25:51 +00002408 if (!N0->isLeaf() || !dynamic_cast<const DefInit*>(N0->getLeafValue()))
Evan Cheng0f040a22011-03-15 05:09:26 +00002409 return false;
2410
2411 const TreePatternNode *N1 = N->getChild(1);
2412 if (N1->isLeaf())
2413 return false;
2414 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2415 return false;
2416
2417 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2418 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2419 return false;
2420 return OpInfo.getEnumName() == "ISD::BITCAST";
2421 }
2422
Dan Gohmanee4fa192008-04-03 00:02:49 +00002423 void AnalyzeNode(const TreePatternNode *N) {
2424 if (N->isLeaf()) {
David Greened4a90662011-07-11 18:25:51 +00002425 if (const DefInit *DI = dynamic_cast<const DefInit*>(N->getLeafValue())) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002426 Record *LeafRec = DI->getDef();
2427 // Handle ComplexPattern leaves.
2428 if (LeafRec->isSubClassOf("ComplexPattern")) {
2429 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2430 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2431 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2432 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2433 }
2434 }
2435 return;
2436 }
2437
2438 // Analyze children.
2439 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2440 AnalyzeNode(N->getChild(i));
2441
2442 // Ignore set nodes, which are not SDNodes.
Evan Cheng0f040a22011-03-15 05:09:26 +00002443 if (N->getOperator()->getName() == "set") {
2444 IsBitcast = IsNodeBitcast(N);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002445 return;
Evan Cheng0f040a22011-03-15 05:09:26 +00002446 }
Dan Gohmanee4fa192008-04-03 00:02:49 +00002447
2448 // Get information about the SDNode for the operator.
2449 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2450
2451 // Notice properties of the node.
2452 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2453 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2454 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
Chris Lattner1e506312010-03-19 05:34:15 +00002455 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002456
2457 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2458 // If this is an intrinsic, analyze it.
2459 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2460 mayLoad = true;// These may load memory.
2461
Dan Gohman7365c092010-08-05 23:36:21 +00002462 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002463 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2464
Dan Gohman7365c092010-08-05 23:36:21 +00002465 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002466 // WriteMem intrinsics can have other strange effects.
2467 HasSideEffects = true;
2468 }
2469 }
2470
2471};
2472
2473static void InferFromPattern(const CodeGenInstruction &Inst,
2474 bool &MayStore, bool &MayLoad,
Evan Cheng0f040a22011-03-15 05:09:26 +00002475 bool &IsBitcast,
Chris Lattner1e506312010-03-19 05:34:15 +00002476 bool &HasSideEffects, bool &IsVariadic,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002477 const CodeGenDAGPatterns &CDP) {
Evan Cheng0f040a22011-03-15 05:09:26 +00002478 MayStore = MayLoad = IsBitcast = HasSideEffects = IsVariadic = false;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002479
2480 bool HadPattern =
Evan Cheng0f040a22011-03-15 05:09:26 +00002481 InstAnalyzer(CDP, MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic)
Chris Lattner1e506312010-03-19 05:34:15 +00002482 .Analyze(Inst.TheDef);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002483
2484 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2485 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2486 // If we decided that this is a store from the pattern, then the .td file
2487 // entry is redundant.
2488 if (MayStore)
2489 fprintf(stderr,
2490 "Warning: mayStore flag explicitly set on instruction '%s'"
2491 " but flag already inferred from pattern.\n",
2492 Inst.TheDef->getName().c_str());
2493 MayStore = true;
2494 }
2495
2496 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2497 // If we decided that this is a load from the pattern, then the .td file
2498 // entry is redundant.
2499 if (MayLoad)
2500 fprintf(stderr,
2501 "Warning: mayLoad flag explicitly set on instruction '%s'"
2502 " but flag already inferred from pattern.\n",
2503 Inst.TheDef->getName().c_str());
2504 MayLoad = true;
2505 }
2506
2507 if (Inst.neverHasSideEffects) {
2508 if (HadPattern)
2509 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2510 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2511 HasSideEffects = false;
2512 }
2513
2514 if (Inst.hasSideEffects) {
2515 if (HasSideEffects)
2516 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2517 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2518 HasSideEffects = true;
2519 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002520
Chris Lattnerc240bb02010-11-01 04:03:32 +00002521 if (Inst.Operands.isVariadic)
Chris Lattner1e506312010-03-19 05:34:15 +00002522 IsVariadic = true; // Can warn if we want.
Dan Gohmanee4fa192008-04-03 00:02:49 +00002523}
2524
Chris Lattner6cefb772008-01-05 22:25:12 +00002525/// ParseInstructions - Parse all of the instructions, inlining and resolving
2526/// any fragments involved. This populates the Instructions list with fully
2527/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002528void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002529 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002530
Chris Lattner6cefb772008-01-05 22:25:12 +00002531 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
David Greened4a90662011-07-11 18:25:51 +00002532 const ListInit *LI = 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002533
David Greened4a90662011-07-11 18:25:51 +00002534 if (dynamic_cast<const ListInit*>(Instrs[i]->getValueInit("Pattern")))
Chris Lattner6cefb772008-01-05 22:25:12 +00002535 LI = Instrs[i]->getValueAsListInit("Pattern");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002536
Chris Lattner6cefb772008-01-05 22:25:12 +00002537 // If there is no pattern, only collect minimal information about the
2538 // instruction for its operand list. We have to assume that there is one
2539 // result, as we have no detailed info.
2540 if (!LI || LI->getSize() == 0) {
2541 std::vector<Record*> Results;
2542 std::vector<Record*> Operands;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002543
Chris Lattnerf30187a2010-03-19 00:07:20 +00002544 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002545
Chris Lattnerc240bb02010-11-01 04:03:32 +00002546 if (InstInfo.Operands.size() != 0) {
2547 if (InstInfo.Operands.NumDefs == 0) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002548 // These produce no results
Chris Lattnerc240bb02010-11-01 04:03:32 +00002549 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2550 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002551 } else {
2552 // Assume the first operand is the result.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002553 Results.push_back(InstInfo.Operands[0].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002554
Chris Lattner6cefb772008-01-05 22:25:12 +00002555 // The rest are inputs.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002556 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2557 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002558 }
2559 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002560
Chris Lattner6cefb772008-01-05 22:25:12 +00002561 // Create and insert the instruction.
2562 std::vector<Record*> ImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002563 Instructions.insert(std::make_pair(Instrs[i],
Chris Lattner62bcec82010-04-20 06:28:43 +00002564 DAGInstruction(0, Results, Operands, ImpResults)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002565 continue; // no pattern.
2566 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002567
Chris Lattner6cefb772008-01-05 22:25:12 +00002568 // Parse the instruction.
2569 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2570 // Inline pattern fragments into it.
2571 I->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002572
Chris Lattner6cefb772008-01-05 22:25:12 +00002573 // Infer as many types as possible. If we cannot infer all of them, we can
2574 // never do anything with this instruction pattern: report it to the user.
2575 if (!I->InferAllTypes())
2576 I->error("Could not infer all types in pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002577
2578 // InstInputs - Keep track of all of the inputs of the instruction, along
Chris Lattner6cefb772008-01-05 22:25:12 +00002579 // with the record they are declared as.
2580 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002581
Chris Lattner6cefb772008-01-05 22:25:12 +00002582 // InstResults - Keep track of all the virtual registers that are 'set'
2583 // in the instruction, including what reg class they are.
2584 std::map<std::string, TreePatternNode*> InstResults;
2585
Chris Lattner6cefb772008-01-05 22:25:12 +00002586 std::vector<Record*> InstImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002587
Chris Lattner6cefb772008-01-05 22:25:12 +00002588 // Verify that the top-level forms in the instruction are of void type, and
2589 // fill in the InstResults map.
2590 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2591 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002592 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002593 I->error("Top-level forms in instruction pattern should have"
2594 " void types");
2595
2596 // Find inputs and outputs, and verify the structure of the uses/defs.
2597 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002598 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002599 }
2600
2601 // Now that we have inputs and outputs of the pattern, inspect the operands
2602 // list for the instruction. This determines the order that operands are
2603 // added to the machine instruction the node corresponds to.
2604 unsigned NumResults = InstResults.size();
2605
2606 // Parse the operands list from the (ops) list, validating it.
2607 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002608 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002609
2610 // Check that all of the results occur first in the list.
2611 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002612 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002613 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerc240bb02010-11-01 04:03:32 +00002614 if (i == CGI.Operands.size())
Chris Lattner6cefb772008-01-05 22:25:12 +00002615 I->error("'" + InstResults.begin()->first +
2616 "' set but does not appear in operand list!");
Chris Lattnerc240bb02010-11-01 04:03:32 +00002617 const std::string &OpName = CGI.Operands[i].Name;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002618
Chris Lattner6cefb772008-01-05 22:25:12 +00002619 // Check that it exists in InstResults.
2620 TreePatternNode *RNode = InstResults[OpName];
2621 if (RNode == 0)
2622 I->error("Operand $" + OpName + " does not exist in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002623
Chris Lattner6cefb772008-01-05 22:25:12 +00002624 if (i == 0)
2625 Res0Node = RNode;
David Greened4a90662011-07-11 18:25:51 +00002626 Record *R = dynamic_cast<const DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner6cefb772008-01-05 22:25:12 +00002627 if (R == 0)
2628 I->error("Operand $" + OpName + " should be a set destination: all "
2629 "outputs must occur before inputs in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002630
Chris Lattnerc240bb02010-11-01 04:03:32 +00002631 if (CGI.Operands[i].Rec != R)
Chris Lattner6cefb772008-01-05 22:25:12 +00002632 I->error("Operand $" + OpName + " class mismatch!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002633
Chris Lattner6cefb772008-01-05 22:25:12 +00002634 // Remember the return type.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002635 Results.push_back(CGI.Operands[i].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002636
Chris Lattner6cefb772008-01-05 22:25:12 +00002637 // Okay, this one checks out.
2638 InstResults.erase(OpName);
2639 }
2640
2641 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2642 // the copy while we're checking the inputs.
2643 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2644
2645 std::vector<TreePatternNode*> ResultNodeOperands;
2646 std::vector<Record*> Operands;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002647 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2648 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner6cefb772008-01-05 22:25:12 +00002649 const std::string &OpName = Op.Name;
2650 if (OpName.empty())
2651 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2652
2653 if (!InstInputsCheck.count(OpName)) {
2654 // If this is an predicate operand or optional def operand with an
2655 // DefaultOps set filled in, we can ignore this. When we codegen it,
2656 // we will do so as always executed.
2657 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2658 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2659 // Does it have a non-empty DefaultOps field? If so, ignore this
2660 // operand.
2661 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2662 continue;
2663 }
2664 I->error("Operand $" + OpName +
2665 " does not appear in the instruction pattern");
2666 }
2667 TreePatternNode *InVal = InstInputsCheck[OpName];
2668 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002669
Chris Lattner6cefb772008-01-05 22:25:12 +00002670 if (InVal->isLeaf() &&
David Greened4a90662011-07-11 18:25:51 +00002671 dynamic_cast<const DefInit*>(InVal->getLeafValue())) {
2672 Record *InRec = static_cast<const DefInit*>(InVal->getLeafValue())->getDef();
Chris Lattner6cefb772008-01-05 22:25:12 +00002673 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2674 I->error("Operand $" + OpName + "'s register class disagrees"
2675 " between the operand and pattern");
2676 }
2677 Operands.push_back(Op.Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002678
Chris Lattner6cefb772008-01-05 22:25:12 +00002679 // Construct the result for the dest-pattern operand list.
2680 TreePatternNode *OpNode = InVal->clone();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002681
Chris Lattner6cefb772008-01-05 22:25:12 +00002682 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002683 OpNode->clearPredicateFns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002684
Chris Lattner6cefb772008-01-05 22:25:12 +00002685 // Promote the xform function to be an explicit node if set.
2686 if (Record *Xform = OpNode->getTransformFn()) {
2687 OpNode->setTransformFn(0);
2688 std::vector<TreePatternNode*> Children;
2689 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002690 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002691 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002692
Chris Lattner6cefb772008-01-05 22:25:12 +00002693 ResultNodeOperands.push_back(OpNode);
2694 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002695
Chris Lattner6cefb772008-01-05 22:25:12 +00002696 if (!InstInputsCheck.empty())
2697 I->error("Input operand $" + InstInputsCheck.begin()->first +
2698 " occurs in pattern but not in operands list!");
2699
2700 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002701 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2702 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002703 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002704 for (unsigned i = 0; i != NumResults; ++i)
2705 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002706
2707 // Create and insert the instruction.
Chris Lattneracfb70f2010-04-20 06:30:25 +00002708 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner62bcec82010-04-20 06:28:43 +00002709 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002710 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2711
2712 // Use a temporary tree pattern to infer all types and make sure that the
2713 // constructed result is correct. This depends on the instruction already
2714 // being inserted into the Instructions map.
2715 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002716 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002717
2718 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2719 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002720
Chris Lattner6cefb772008-01-05 22:25:12 +00002721 DEBUG(I->dump());
2722 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002723
Chris Lattner6cefb772008-01-05 22:25:12 +00002724 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002725 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2726 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002727 E = Instructions.end(); II != E; ++II) {
2728 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002729 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002730 if (I == 0) continue; // No pattern.
2731
2732 // FIXME: Assume only the first tree is the pattern. The others are clobber
2733 // nodes.
2734 TreePatternNode *Pattern = I->getTree(0);
2735 TreePatternNode *SrcPattern;
2736 if (Pattern->getOperator()->getName() == "set") {
2737 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2738 } else{
2739 // Not a set (store or something?)
2740 SrcPattern = Pattern;
2741 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002742
Chris Lattner6cefb772008-01-05 22:25:12 +00002743 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002744 AddPatternToMatch(I,
Jim Grosbach997759a2010-12-07 23:05:49 +00002745 PatternToMatch(Instr,
2746 Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002747 SrcPattern,
2748 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002749 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002750 Instr->getValueAsInt("AddedComplexity"),
2751 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002752 }
2753}
2754
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002755
2756typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2757
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002758static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002759 std::map<std::string, NameRecord> &Names,
2760 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002761 if (!P->getName().empty()) {
2762 NameRecord &Rec = Names[P->getName()];
2763 // If this is the first instance of the name, remember the node.
2764 if (Rec.second++ == 0)
2765 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002766 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002767 PatternTop->error("repetition of value: $" + P->getName() +
2768 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002769 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002770
Chris Lattner967d54a2010-02-23 06:35:45 +00002771 if (!P->isLeaf()) {
2772 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002773 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002774 }
2775}
2776
Chris Lattner25b6f912010-02-23 06:16:51 +00002777void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2778 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002779 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002780 std::string Reason;
2781 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002782 Pattern->error("Pattern can never match: " + Reason);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002783
Chris Lattner405f1252010-03-01 22:29:19 +00002784 // If the source pattern's root is a complex pattern, that complex pattern
2785 // must specify the nodes it can potentially match.
2786 if (const ComplexPattern *CP =
2787 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2788 if (CP->getRootNodes().empty())
2789 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2790 " could match");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002791
2792
Chris Lattner967d54a2010-02-23 06:35:45 +00002793 // Find all of the named values in the input and output, ensure they have the
2794 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002795 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002796 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2797 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002798
2799 // Scan all of the named values in the destination pattern, rejecting them if
2800 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002801 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002802 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002803 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002804 Pattern->error("Pattern has input without matching name in output: $" +
2805 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002806 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002807
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002808 // Scan all of the named values in the source pattern, rejecting them if the
2809 // name isn't used in the dest, and isn't used to tie two values together.
2810 for (std::map<std::string, NameRecord>::iterator
2811 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2812 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2813 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002814
Chris Lattner25b6f912010-02-23 06:16:51 +00002815 PatternsToMatch.push_back(PTM);
2816}
2817
2818
Dan Gohmanee4fa192008-04-03 00:02:49 +00002819
2820void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002821 const std::vector<const CodeGenInstruction*> &Instructions =
2822 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002823 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2824 CodeGenInstruction &InstInfo =
2825 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002826 // Determine properties of the instruction from its pattern.
Evan Cheng0f040a22011-03-15 05:09:26 +00002827 bool MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic;
2828 InferFromPattern(InstInfo, MayStore, MayLoad, IsBitcast,
2829 HasSideEffects, IsVariadic, *this);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002830 InstInfo.mayStore = MayStore;
2831 InstInfo.mayLoad = MayLoad;
Evan Cheng0f040a22011-03-15 05:09:26 +00002832 InstInfo.isBitcast = IsBitcast;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002833 InstInfo.hasSideEffects = HasSideEffects;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002834 InstInfo.Operands.isVariadic = IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002835 }
2836}
2837
Chris Lattner2cacec52010-03-15 06:00:16 +00002838/// Given a pattern result with an unresolved type, see if we can find one
2839/// instruction with an unresolved result type. Force this result type to an
2840/// arbitrary element if it's possible types to converge results.
2841static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2842 if (N->isLeaf())
2843 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002844
Chris Lattner2cacec52010-03-15 06:00:16 +00002845 // Analyze children.
2846 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2847 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2848 return true;
2849
2850 if (!N->getOperator()->isSubClassOf("Instruction"))
2851 return false;
2852
2853 // If this type is already concrete or completely unknown we can't do
2854 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00002855 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2856 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2857 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002858
Chris Lattnerd7349192010-03-19 21:37:09 +00002859 // Otherwise, force its type to the first possibility (an arbitrary choice).
2860 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2861 return true;
2862 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002863
Chris Lattnerd7349192010-03-19 21:37:09 +00002864 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00002865}
2866
Chris Lattnerfe718932008-01-06 01:10:31 +00002867void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002868 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2869
2870 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002871 Record *CurPattern = Patterns[i];
David Greened4a90662011-07-11 18:25:51 +00002872 const DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Chris Lattner310adf12010-03-27 02:53:27 +00002873 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002874
2875 // Inline pattern fragments into it.
2876 Pattern->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002877
David Greened4a90662011-07-11 18:25:51 +00002878 const ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00002879 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002880
Chris Lattner6cefb772008-01-05 22:25:12 +00002881 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00002882 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002883
Chris Lattner6cefb772008-01-05 22:25:12 +00002884 // Inline pattern fragments into it.
2885 Result->InlinePatternFragments();
2886
2887 if (Result->getNumTrees() != 1)
2888 Result->error("Cannot handle instructions producing instructions "
2889 "with temporaries yet!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002890
Chris Lattner6cefb772008-01-05 22:25:12 +00002891 bool IterateInference;
2892 bool InferredAllPatternTypes, InferredAllResultTypes;
2893 do {
2894 // Infer as many types as possible. If we cannot infer all of them, we
2895 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002896 InferredAllPatternTypes =
2897 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002898
Chris Lattner6cefb772008-01-05 22:25:12 +00002899 // Infer as many types as possible. If we cannot infer all of them, we
2900 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002901 InferredAllResultTypes =
2902 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002903
Chris Lattner6c6ba362010-03-18 23:15:10 +00002904 IterateInference = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002905
Chris Lattner6cefb772008-01-05 22:25:12 +00002906 // Apply the type of the result to the source pattern. This helps us
2907 // resolve cases where the input type is known to be a pointer type (which
2908 // is considered resolved), but the result knows it needs to be 32- or
2909 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00002910 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2911 Pattern->getTree(0)->getNumTypes());
2912 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00002913 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002914 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002915 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002916 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002917 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002918
Chris Lattner2cacec52010-03-15 06:00:16 +00002919 // If our iteration has converged and the input pattern's types are fully
2920 // resolved but the result pattern is not fully resolved, we may have a
2921 // situation where we have two instructions in the result pattern and
2922 // the instructions require a common register class, but don't care about
2923 // what actual MVT is used. This is actually a bug in our modelling:
2924 // output patterns should have register classes, not MVTs.
2925 //
2926 // In any case, to handle this, we just go through and disambiguate some
2927 // arbitrary types to the result pattern's nodes.
2928 if (!IterateInference && InferredAllPatternTypes &&
2929 !InferredAllResultTypes)
2930 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2931 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002932 } while (IterateInference);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002933
Chris Lattner6cefb772008-01-05 22:25:12 +00002934 // Verify that we inferred enough types that we can do something with the
2935 // pattern and result. If these fire the user has to add type casts.
2936 if (!InferredAllPatternTypes)
2937 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002938 if (!InferredAllResultTypes) {
2939 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002940 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002941 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002942
Chris Lattner6cefb772008-01-05 22:25:12 +00002943 // Validate that the input pattern is correct.
2944 std::map<std::string, TreePatternNode*> InstInputs;
2945 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00002946 std::vector<Record*> InstImpResults;
2947 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2948 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2949 InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002950 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002951
2952 // Promote the xform function to be an explicit node if set.
2953 TreePatternNode *DstPattern = Result->getOnlyTree();
2954 std::vector<TreePatternNode*> ResultNodeOperands;
2955 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2956 TreePatternNode *OpNode = DstPattern->getChild(ii);
2957 if (Record *Xform = OpNode->getTransformFn()) {
2958 OpNode->setTransformFn(0);
2959 std::vector<TreePatternNode*> Children;
2960 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002961 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002962 }
2963 ResultNodeOperands.push_back(OpNode);
2964 }
2965 DstPattern = Result->getOnlyTree();
2966 if (!DstPattern->isLeaf())
2967 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00002968 ResultNodeOperands,
2969 DstPattern->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002970
Chris Lattnerd7349192010-03-19 21:37:09 +00002971 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2972 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002973
Chris Lattner6cefb772008-01-05 22:25:12 +00002974 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2975 Temp.InferAllTypes();
2976
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002977
Chris Lattner25b6f912010-02-23 06:16:51 +00002978 AddPatternToMatch(Pattern,
Jim Grosbach997759a2010-12-07 23:05:49 +00002979 PatternToMatch(CurPattern,
2980 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerd7349192010-03-19 21:37:09 +00002981 Pattern->getTree(0),
2982 Temp.getOnlyTree(), InstImpResults,
2983 CurPattern->getValueAsInt("AddedComplexity"),
2984 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002985 }
2986}
2987
2988/// CombineChildVariants - Given a bunch of permutations of each child of the
2989/// 'operator' node, put them together in all possible ways.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002990static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00002991 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2992 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002993 CodeGenDAGPatterns &CDP,
2994 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002995 // Make sure that each operand has at least one variant to choose from.
2996 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2997 if (ChildVariants[i].empty())
2998 return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002999
Chris Lattner6cefb772008-01-05 22:25:12 +00003000 // The end result is an all-pairs construction of the resultant pattern.
3001 std::vector<unsigned> Idxs;
3002 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00003003 bool NotDone;
3004 do {
3005#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00003006 DEBUG(if (!Idxs.empty()) {
3007 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3008 for (unsigned i = 0; i < Idxs.size(); ++i) {
3009 errs() << Idxs[i] << " ";
3010 }
3011 errs() << "]\n";
3012 });
Scott Michel327d0652008-03-05 17:49:05 +00003013#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00003014 // Create the variant and add it to the output list.
3015 std::vector<TreePatternNode*> NewChildren;
3016 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3017 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00003018 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3019 Orig->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003020
Chris Lattner6cefb772008-01-05 22:25:12 +00003021 // Copy over properties.
3022 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00003023 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00003024 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00003025 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3026 R->setType(i, Orig->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003027
Scott Michel327d0652008-03-05 17:49:05 +00003028 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00003029 std::string ErrString;
3030 if (!R->canPatternMatch(ErrString, CDP)) {
3031 delete R;
3032 } else {
3033 bool AlreadyExists = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003034
Chris Lattner6cefb772008-01-05 22:25:12 +00003035 // Scan to see if this pattern has already been emitted. We can get
3036 // duplication due to things like commuting:
3037 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3038 // which are the same pattern. Ignore the dups.
3039 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003040 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003041 AlreadyExists = true;
3042 break;
3043 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003044
Chris Lattner6cefb772008-01-05 22:25:12 +00003045 if (AlreadyExists)
3046 delete R;
3047 else
3048 OutVariants.push_back(R);
3049 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003050
Scott Michel327d0652008-03-05 17:49:05 +00003051 // Increment indices to the next permutation by incrementing the
3052 // indicies from last index backward, e.g., generate the sequence
3053 // [0, 0], [0, 1], [1, 0], [1, 1].
3054 int IdxsIdx;
3055 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3056 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3057 Idxs[IdxsIdx] = 0;
3058 else
Chris Lattner6cefb772008-01-05 22:25:12 +00003059 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00003060 }
Scott Michel327d0652008-03-05 17:49:05 +00003061 NotDone = (IdxsIdx >= 0);
3062 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00003063}
3064
3065/// CombineChildVariants - A helper function for binary operators.
3066///
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003067static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00003068 const std::vector<TreePatternNode*> &LHS,
3069 const std::vector<TreePatternNode*> &RHS,
3070 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003071 CodeGenDAGPatterns &CDP,
3072 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003073 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3074 ChildVariants.push_back(LHS);
3075 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00003076 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003077}
Chris Lattner6cefb772008-01-05 22:25:12 +00003078
3079
3080static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3081 std::vector<TreePatternNode *> &Children) {
3082 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3083 Record *Operator = N->getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003084
Chris Lattner6cefb772008-01-05 22:25:12 +00003085 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00003086 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00003087 N->getTransformFn()) {
3088 Children.push_back(N);
3089 return;
3090 }
3091
3092 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3093 Children.push_back(N->getChild(0));
3094 else
3095 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3096
3097 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3098 Children.push_back(N->getChild(1));
3099 else
3100 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3101}
3102
3103/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3104/// the (potentially recursive) pattern by using algebraic laws.
3105///
3106static void GenerateVariantsOf(TreePatternNode *N,
3107 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003108 CodeGenDAGPatterns &CDP,
3109 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003110 // We cannot permute leaves.
3111 if (N->isLeaf()) {
3112 OutVariants.push_back(N);
3113 return;
3114 }
3115
3116 // Look up interesting info about the node.
3117 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3118
Jim Grosbachda4231f2009-03-26 16:17:51 +00003119 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00003120 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003121 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00003122 std::vector<TreePatternNode*> MaximalChildren;
3123 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3124
3125 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3126 // permutations.
3127 if (MaximalChildren.size() == 3) {
3128 // Find the variants of all of our maximal children.
3129 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003130 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3131 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3132 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003133
Chris Lattner6cefb772008-01-05 22:25:12 +00003134 // There are only two ways we can permute the tree:
3135 // (A op B) op C and A op (B op C)
3136 // Within these forms, we can also permute A/B/C.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003137
Chris Lattner6cefb772008-01-05 22:25:12 +00003138 // Generate legal pair permutations of A/B/C.
3139 std::vector<TreePatternNode*> ABVariants;
3140 std::vector<TreePatternNode*> BAVariants;
3141 std::vector<TreePatternNode*> ACVariants;
3142 std::vector<TreePatternNode*> CAVariants;
3143 std::vector<TreePatternNode*> BCVariants;
3144 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003145 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3146 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3147 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3148 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3149 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3150 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003151
3152 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00003153 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3154 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3155 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3156 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3157 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3158 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003159
3160 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00003161 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3162 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3163 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3164 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3165 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3166 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003167 return;
3168 }
3169 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003170
Chris Lattner6cefb772008-01-05 22:25:12 +00003171 // Compute permutations of all children.
3172 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3173 ChildVariants.resize(N->getNumChildren());
3174 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003175 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003176
3177 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00003178 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003179
3180 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003181 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3182 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3183 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3184 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003185 // Don't count children which are actually register references.
3186 unsigned NC = 0;
3187 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3188 TreePatternNode *Child = N->getChild(i);
3189 if (Child->isLeaf())
David Greened4a90662011-07-11 18:25:51 +00003190 if (const DefInit *DI =
3191 dynamic_cast<const DefInit*>(Child->getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003192 Record *RR = DI->getDef();
3193 if (RR->isSubClassOf("Register"))
3194 continue;
3195 }
3196 NC++;
3197 }
3198 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003199 if (isCommIntrinsic) {
3200 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3201 // operands are the commutative operands, and there might be more operands
3202 // after those.
3203 assert(NC >= 3 &&
3204 "Commutative intrinsic should have at least 3 childrean!");
3205 std::vector<std::vector<TreePatternNode*> > Variants;
3206 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3207 Variants.push_back(ChildVariants[2]);
3208 Variants.push_back(ChildVariants[1]);
3209 for (unsigned i = 3; i != NC; ++i)
3210 Variants.push_back(ChildVariants[i]);
3211 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3212 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00003213 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00003214 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003215 }
3216}
3217
3218
3219// GenerateVariants - Generate variants. For example, commutative patterns can
3220// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00003221void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00003222 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003223
Chris Lattner6cefb772008-01-05 22:25:12 +00003224 // Loop over all of the patterns we've collected, checking to see if we can
3225 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00003226 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00003227 // the .td file having to contain tons of variants of instructions.
3228 //
3229 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3230 // intentionally do not reconsider these. Any variants of added patterns have
3231 // already been added.
3232 //
3233 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00003234 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00003235 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00003236 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00003237 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00003238 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00003239 DEBUG(errs() << "\n");
Jim Grosbachbb168242010-10-08 18:13:57 +00003240 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3241 DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003242
3243 assert(!Variants.empty() && "Must create at least original variant!");
3244 Variants.erase(Variants.begin()); // Remove the original pattern.
3245
3246 if (Variants.empty()) // No variants for this pattern.
3247 continue;
3248
Chris Lattner569f1212009-08-23 04:44:11 +00003249 DEBUG(errs() << "FOUND VARIANTS OF: ";
3250 PatternsToMatch[i].getSrcPattern()->dump();
3251 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003252
3253 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3254 TreePatternNode *Variant = Variants[v];
3255
Chris Lattner569f1212009-08-23 04:44:11 +00003256 DEBUG(errs() << " VAR#" << v << ": ";
3257 Variant->dump();
3258 errs() << "\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003259
Chris Lattner6cefb772008-01-05 22:25:12 +00003260 // Scan to see if an instruction or explicit pattern already matches this.
3261 bool AlreadyExists = false;
3262 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00003263 // Skip if the top level predicates do not match.
3264 if (PatternsToMatch[i].getPredicates() !=
3265 PatternsToMatch[p].getPredicates())
3266 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00003267 // Check to see if this variant already exists.
Jim Grosbachbb168242010-10-08 18:13:57 +00003268 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3269 DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00003270 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003271 AlreadyExists = true;
3272 break;
3273 }
3274 }
3275 // If we already have it, ignore the variant.
3276 if (AlreadyExists) continue;
3277
3278 // Otherwise, add it to the list of patterns we have.
3279 PatternsToMatch.
Jim Grosbach997759a2010-12-07 23:05:49 +00003280 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3281 PatternsToMatch[i].getPredicates(),
Chris Lattner6cefb772008-01-05 22:25:12 +00003282 Variant, PatternsToMatch[i].getDstPattern(),
3283 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00003284 PatternsToMatch[i].getAddedComplexity(),
3285 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003286 }
3287
Chris Lattner569f1212009-08-23 04:44:11 +00003288 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003289 }
3290}
3291