blob: 3280e09274f6bf3f998153090710bd89df849557 [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"
Peter Collingbourne7c788882011-10-01 16:41:13 +000016#include "llvm/TableGen/Error.h"
17#include "llvm/TableGen/Record.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000018#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"
David Blaikiefdebc382012-01-17 04:43:56 +000021#include "llvm/Support/ErrorHandling.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000022#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000023#include <algorithm>
Chris Lattner6cefb772008-01-05 22:25:12 +000024using namespace llvm;
25
26//===----------------------------------------------------------------------===//
Chris Lattner2cacec52010-03-15 06:00:16 +000027// EEVT::TypeSet Implementation
28//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +000029
Owen Anderson825b72b2009-08-11 20:47:22 +000030static inline bool isInteger(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000031 return EVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000032}
Owen Anderson825b72b2009-08-11 20:47:22 +000033static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000034 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000035}
Owen Anderson825b72b2009-08-11 20:47:22 +000036static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000037 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000038}
Chris Lattner774ce292010-03-19 17:41:26 +000039static inline bool isScalar(MVT::SimpleValueType VT) {
40 return !EVT(VT).isVector();
41}
Duncan Sands83ec4b62008-06-06 12:08:01 +000042
Chris Lattner2cacec52010-03-15 06:00:16 +000043EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
44 if (VT == MVT::iAny)
45 EnforceInteger(TP);
46 else if (VT == MVT::fAny)
47 EnforceFloatingPoint(TP);
48 else if (VT == MVT::vAny)
49 EnforceVector(TP);
50 else {
51 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
52 VT == MVT::iPTRAny) && "Not a concrete type!");
53 TypeVec.push_back(VT);
54 }
Chris Lattner6cefb772008-01-05 22:25:12 +000055}
56
Chris Lattner2cacec52010-03-15 06:00:16 +000057
58EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
59 assert(!VTList.empty() && "empty list?");
60 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000061
Chris Lattner2cacec52010-03-15 06:00:16 +000062 if (!VTList.empty())
63 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
64 VTList[0] != MVT::fAny);
Jim Grosbachfbadcd02010-12-21 16:16:00 +000065
Chris Lattner0d7952e2010-03-27 20:32:26 +000066 // Verify no duplicates.
Chris Lattner2cacec52010-03-15 06:00:16 +000067 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner0d7952e2010-03-27 20:32:26 +000068 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner6cefb772008-01-05 22:25:12 +000069}
70
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000071/// FillWithPossibleTypes - Set to all legal types and return true, only valid
72/// on completely unknown type sets.
Chris Lattner774ce292010-03-19 17:41:26 +000073bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
74 bool (*Pred)(MVT::SimpleValueType),
75 const char *PredicateName) {
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000076 assert(isCompletelyUnknown());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000077 const std::vector<MVT::SimpleValueType> &LegalTypes =
Chris Lattner774ce292010-03-19 17:41:26 +000078 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +000079
Chris Lattner774ce292010-03-19 17:41:26 +000080 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
81 if (Pred == 0 || Pred(LegalTypes[i]))
82 TypeVec.push_back(LegalTypes[i]);
83
84 // If we have nothing that matches the predicate, bail out.
85 if (TypeVec.empty())
86 TP.error("Type inference contradiction found, no " +
Jim Grosbachfbadcd02010-12-21 16:16:00 +000087 std::string(PredicateName) + " types found");
Chris Lattner774ce292010-03-19 17:41:26 +000088 // No need to sort with one element.
89 if (TypeVec.size() == 1) return true;
90
91 // Remove duplicates.
92 array_pod_sort(TypeVec.begin(), TypeVec.end());
93 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000094
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000095 return true;
96}
Chris Lattner2cacec52010-03-15 06:00:16 +000097
98/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
99/// integer value type.
100bool EEVT::TypeSet::hasIntegerTypes() const {
101 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
102 if (isInteger(TypeVec[i]))
103 return true;
104 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000105}
Chris Lattner2cacec52010-03-15 06:00:16 +0000106
107/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
108/// a floating point value type.
109bool EEVT::TypeSet::hasFloatingPointTypes() const {
110 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
111 if (isFloatingPoint(TypeVec[i]))
112 return true;
113 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000114}
Chris Lattner2cacec52010-03-15 06:00:16 +0000115
116/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
117/// value type.
118bool EEVT::TypeSet::hasVectorTypes() const {
119 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
120 if (isVector(TypeVec[i]))
121 return true;
122 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +0000123}
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000124
Chris Lattner2cacec52010-03-15 06:00:16 +0000125
126std::string EEVT::TypeSet::getName() const {
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000127 if (TypeVec.empty()) return "<empty>";
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000128
Chris Lattner2cacec52010-03-15 06:00:16 +0000129 std::string Result;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000130
Chris Lattner2cacec52010-03-15 06:00:16 +0000131 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
132 std::string VTName = llvm::getEnumName(TypeVec[i]);
133 // Strip off MVT:: prefix if present.
134 if (VTName.substr(0,5) == "MVT::")
135 VTName = VTName.substr(5);
136 if (i) Result += ':';
137 Result += VTName;
138 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000139
Chris Lattner2cacec52010-03-15 06:00:16 +0000140 if (TypeVec.size() == 1)
141 return Result;
142 return "{" + Result + "}";
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000143}
Chris Lattner2cacec52010-03-15 06:00:16 +0000144
145/// MergeInTypeInfo - This merges in type information from the specified
146/// argument. If 'this' changes, it returns true. If the two types are
147/// contradictory (e.g. merge f32 into i32) then this throws an exception.
148bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
149 if (InVT.isCompletelyUnknown() || *this == InVT)
150 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000151
Chris Lattner2cacec52010-03-15 06:00:16 +0000152 if (isCompletelyUnknown()) {
153 *this = InVT;
154 return true;
155 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000156
Chris Lattner2cacec52010-03-15 06:00:16 +0000157 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000158
Chris Lattner2cacec52010-03-15 06:00:16 +0000159 // Handle the abstract cases, seeing if we can resolve them better.
160 switch (TypeVec[0]) {
161 default: break;
162 case MVT::iPTR:
163 case MVT::iPTRAny:
164 if (InVT.hasIntegerTypes()) {
165 EEVT::TypeSet InCopy(InVT);
166 InCopy.EnforceInteger(TP);
167 InCopy.EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000168
Chris Lattner2cacec52010-03-15 06:00:16 +0000169 if (InCopy.isConcrete()) {
170 // If the RHS has one integer type, upgrade iPTR to i32.
171 TypeVec[0] = InVT.TypeVec[0];
172 return true;
173 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000174
Chris Lattner2cacec52010-03-15 06:00:16 +0000175 // If the input has multiple scalar integers, this doesn't add any info.
176 if (!InCopy.isCompletelyUnknown())
177 return false;
178 }
179 break;
180 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000181
Chris Lattner2cacec52010-03-15 06:00:16 +0000182 // If the input constraint is iAny/iPTR and this is an integer type list,
183 // remove non-integer types from the list.
184 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
185 hasIntegerTypes()) {
186 bool MadeChange = EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000187
Chris Lattner2cacec52010-03-15 06:00:16 +0000188 // If we're merging in iPTR/iPTRAny and the node currently has a list of
189 // multiple different integer types, replace them with a single iPTR.
190 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
191 TypeVec.size() != 1) {
192 TypeVec.resize(1);
193 TypeVec[0] = InVT.TypeVec[0];
194 MadeChange = true;
195 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000196
Chris Lattner2cacec52010-03-15 06:00:16 +0000197 return MadeChange;
198 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000199
Chris Lattner2cacec52010-03-15 06:00:16 +0000200 // If this is a type list and the RHS is a typelist as well, eliminate entries
201 // from this list that aren't in the other one.
202 bool MadeChange = false;
203 TypeSet InputSet(*this);
204
205 for (unsigned i = 0; i != TypeVec.size(); ++i) {
206 bool InInVT = false;
207 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
208 if (TypeVec[i] == InVT.TypeVec[j]) {
209 InInVT = true;
210 break;
211 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000212
Chris Lattner2cacec52010-03-15 06:00:16 +0000213 if (InInVT) continue;
214 TypeVec.erase(TypeVec.begin()+i--);
215 MadeChange = true;
216 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000217
Chris Lattner2cacec52010-03-15 06:00:16 +0000218 // If we removed all of our types, we have a type contradiction.
219 if (!TypeVec.empty())
220 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000221
Chris Lattner2cacec52010-03-15 06:00:16 +0000222 // FIXME: Really want an SMLoc here!
223 TP.error("Type inference contradiction found, merging '" +
224 InVT.getName() + "' into '" + InputSet.getName() + "'");
225 return true; // unreachable
226}
227
228/// EnforceInteger - Remove all non-integer types from this set.
229bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000230 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000231 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000232 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattner2cacec52010-03-15 06:00:16 +0000233 if (!hasFloatingPointTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000234 return false;
235
236 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000237
Chris Lattner2cacec52010-03-15 06:00:16 +0000238 // Filter out all the fp types.
239 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000240 if (!isInteger(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000241 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000242
Chris Lattner2cacec52010-03-15 06:00:16 +0000243 if (TypeVec.empty())
244 TP.error("Type inference contradiction found, '" +
245 InputSet.getName() + "' needs to be integer");
Chris Lattner774ce292010-03-19 17:41:26 +0000246 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000247}
248
249/// EnforceFloatingPoint - Remove all integer types from this set.
250bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000251 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000252 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000253 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
254
Chris Lattner2cacec52010-03-15 06:00:16 +0000255 if (!hasIntegerTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000256 return false;
257
258 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000259
Chris Lattner2cacec52010-03-15 06:00:16 +0000260 // Filter out all the fp types.
261 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000262 if (!isFloatingPoint(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000263 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000264
Chris Lattner2cacec52010-03-15 06:00:16 +0000265 if (TypeVec.empty())
266 TP.error("Type inference contradiction found, '" +
267 InputSet.getName() + "' needs to be floating point");
Chris Lattner774ce292010-03-19 17:41:26 +0000268 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000269}
270
271/// EnforceScalar - Remove all vector types from this.
272bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000273 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000274 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000275 return FillWithPossibleTypes(TP, isScalar, "scalar");
276
Chris Lattner2cacec52010-03-15 06:00:16 +0000277 if (!hasVectorTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000278 return false;
279
280 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000281
Chris Lattner2cacec52010-03-15 06:00:16 +0000282 // Filter out all the vector types.
283 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000284 if (!isScalar(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000285 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000286
Chris Lattner2cacec52010-03-15 06:00:16 +0000287 if (TypeVec.empty())
288 TP.error("Type inference contradiction found, '" +
289 InputSet.getName() + "' needs to be scalar");
Chris Lattner774ce292010-03-19 17:41:26 +0000290 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000291}
292
293/// EnforceVector - Remove all vector types from this.
294bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Chris Lattner774ce292010-03-19 17:41:26 +0000295 // If we know nothing, then get the full set.
296 if (TypeVec.empty())
297 return FillWithPossibleTypes(TP, isVector, "vector");
298
Chris Lattner2cacec52010-03-15 06:00:16 +0000299 TypeSet InputSet(*this);
300 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000301
Chris Lattner2cacec52010-03-15 06:00:16 +0000302 // Filter out all the scalar types.
303 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000304 if (!isVector(TypeVec[i])) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000305 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner774ce292010-03-19 17:41:26 +0000306 MadeChange = true;
307 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000308
Chris Lattner2cacec52010-03-15 06:00:16 +0000309 if (TypeVec.empty())
310 TP.error("Type inference contradiction found, '" +
311 InputSet.getName() + "' needs to be a vector");
312 return MadeChange;
313}
314
315
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000316
Chris Lattner2cacec52010-03-15 06:00:16 +0000317/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
318/// this an other based on this information.
319bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
320 // Both operands must be integer or FP, but we don't care which.
321 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000322
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000323 if (isCompletelyUnknown())
324 MadeChange = FillWithPossibleTypes(TP);
325
326 if (Other.isCompletelyUnknown())
327 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000328
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000329 // If one side is known to be integer or known to be FP but the other side has
330 // no information, get at least the type integrality info in there.
331 if (!hasFloatingPointTypes())
332 MadeChange |= Other.EnforceInteger(TP);
333 else if (!hasIntegerTypes())
334 MadeChange |= Other.EnforceFloatingPoint(TP);
335 if (!Other.hasFloatingPointTypes())
336 MadeChange |= EnforceInteger(TP);
337 else if (!Other.hasIntegerTypes())
338 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000339
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000340 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
341 "Should have a type list now");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000342
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000343 // If one contains vectors but the other doesn't pull vectors out.
344 if (!hasVectorTypes())
345 MadeChange |= Other.EnforceScalar(TP);
346 if (!hasVectorTypes())
347 MadeChange |= EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000348
David Greene9d7f0112011-02-01 19:12:32 +0000349 if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
350 // If we are down to concrete types, this code does not currently
351 // handle nodes which have multiple types, where some types are
352 // integer, and some are fp. Assert that this is not the case.
353 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
354 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
355 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
356
357 // Otherwise, if these are both vector types, either this vector
358 // must have a larger bitsize than the other, or this element type
359 // must be larger than the other.
360 EVT Type(TypeVec[0]);
361 EVT OtherType(Other.TypeVec[0]);
362
363 if (hasVectorTypes() && Other.hasVectorTypes()) {
364 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
365 if (Type.getVectorElementType().getSizeInBits()
366 >= OtherType.getVectorElementType().getSizeInBits())
367 TP.error("Type inference contradiction found, '" +
368 getName() + "' element type not smaller than '" +
369 Other.getName() +"'!");
370 }
371 else
372 // For scalar types, the bitsize of this type must be larger
373 // than that of the other.
374 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
375 TP.error("Type inference contradiction found, '" +
376 getName() + "' is not smaller than '" +
377 Other.getName() +"'!");
378
379 }
380
381
382 // Handle int and fp as disjoint sets. This won't work for patterns
383 // that have mixed fp/int types but those are likely rare and would
384 // not have been accepted by this code previously.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000385
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000386 // Okay, find the smallest type from the current set and remove it from the
387 // largest set.
David Greenec83e2032011-02-04 17:01:53 +0000388 MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
David Greene9d7f0112011-02-01 19:12:32 +0000389 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
390 if (isInteger(TypeVec[i])) {
391 SmallestInt = TypeVec[i];
392 break;
393 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000394 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
David Greene9d7f0112011-02-01 19:12:32 +0000395 if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
396 SmallestInt = TypeVec[i];
397
David Greenec83e2032011-02-04 17:01:53 +0000398 MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
David Greene9d7f0112011-02-01 19:12:32 +0000399 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
400 if (isFloatingPoint(TypeVec[i])) {
401 SmallestFP = TypeVec[i];
402 break;
403 }
404 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
405 if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
406 SmallestFP = TypeVec[i];
407
408 int OtherIntSize = 0;
409 int OtherFPSize = 0;
410 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
411 Other.TypeVec.begin();
412 TVI != Other.TypeVec.end();
413 /* NULL */) {
414 if (isInteger(*TVI)) {
415 ++OtherIntSize;
416 if (*TVI == SmallestInt) {
417 TVI = Other.TypeVec.erase(TVI);
418 --OtherIntSize;
419 MadeChange = true;
420 continue;
421 }
422 }
423 else if (isFloatingPoint(*TVI)) {
424 ++OtherFPSize;
425 if (*TVI == SmallestFP) {
426 TVI = Other.TypeVec.erase(TVI);
427 --OtherFPSize;
428 MadeChange = true;
429 continue;
430 }
431 }
432 ++TVI;
433 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000434
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000435 // If this is the only type in the large set, the constraint can never be
436 // satisfied.
David Greene9d7f0112011-02-01 19:12:32 +0000437 if ((Other.hasIntegerTypes() && OtherIntSize == 0)
438 || (Other.hasFloatingPointTypes() && OtherFPSize == 0))
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000439 TP.error("Type inference contradiction found, '" +
440 Other.getName() + "' has nothing larger than '" + getName() +"'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000441
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000442 // Okay, find the largest type in the Other set and remove it from the
443 // current set.
David Greenec83e2032011-02-04 17:01:53 +0000444 MVT::SimpleValueType LargestInt = MVT::Other;
David Greene9d7f0112011-02-01 19:12:32 +0000445 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
446 if (isInteger(Other.TypeVec[i])) {
447 LargestInt = Other.TypeVec[i];
448 break;
449 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000450 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
David Greene9d7f0112011-02-01 19:12:32 +0000451 if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
452 LargestInt = Other.TypeVec[i];
453
David Greenec83e2032011-02-04 17:01:53 +0000454 MVT::SimpleValueType LargestFP = MVT::Other;
David Greene9d7f0112011-02-01 19:12:32 +0000455 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
456 if (isFloatingPoint(Other.TypeVec[i])) {
457 LargestFP = Other.TypeVec[i];
458 break;
459 }
460 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
461 if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
462 LargestFP = Other.TypeVec[i];
463
464 int IntSize = 0;
465 int FPSize = 0;
466 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
467 TypeVec.begin();
468 TVI != TypeVec.end();
469 /* NULL */) {
470 if (isInteger(*TVI)) {
471 ++IntSize;
472 if (*TVI == LargestInt) {
473 TVI = TypeVec.erase(TVI);
474 --IntSize;
475 MadeChange = true;
476 continue;
477 }
478 }
479 else if (isFloatingPoint(*TVI)) {
480 ++FPSize;
481 if (*TVI == LargestFP) {
482 TVI = TypeVec.erase(TVI);
483 --FPSize;
484 MadeChange = true;
485 continue;
486 }
487 }
488 ++TVI;
489 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000490
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000491 // If this is the only type in the small set, the constraint can never be
492 // satisfied.
David Greene9d7f0112011-02-01 19:12:32 +0000493 if ((hasIntegerTypes() && IntSize == 0)
494 || (hasFloatingPointTypes() && FPSize == 0))
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000495 TP.error("Type inference contradiction found, '" +
496 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000497
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000498 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000499}
500
501/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner66fb9d22010-03-24 00:01:16 +0000502/// whose element is specified by VTOperand.
503bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattner2cacec52010-03-15 06:00:16 +0000504 TreePattern &TP) {
Chris Lattner66fb9d22010-03-24 00:01:16 +0000505 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattner2cacec52010-03-15 06:00:16 +0000506 bool MadeChange = false;
Chris Lattner66fb9d22010-03-24 00:01:16 +0000507 MadeChange |= EnforceVector(TP);
508 MadeChange |= VTOperand.EnforceScalar(TP);
509
510 // If we know the vector type, it forces the scalar to agree.
511 if (isConcrete()) {
512 EVT IVT = getConcrete();
513 IVT = IVT.getVectorElementType();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000514 return MadeChange |
Chris Lattner66fb9d22010-03-24 00:01:16 +0000515 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
516 }
517
518 // If the scalar type is known, filter out vector types whose element types
519 // disagree.
520 if (!VTOperand.isConcrete())
521 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000522
Chris Lattner66fb9d22010-03-24 00:01:16 +0000523 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000524
Chris Lattner66fb9d22010-03-24 00:01:16 +0000525 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000526
Chris Lattner66fb9d22010-03-24 00:01:16 +0000527 // Filter out all the types which don't have the right element type.
528 for (unsigned i = 0; i != TypeVec.size(); ++i) {
529 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
530 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000531 TypeVec.erase(TypeVec.begin()+i--);
532 MadeChange = true;
533 }
Chris Lattner66fb9d22010-03-24 00:01:16 +0000534 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000535
Chris Lattner2cacec52010-03-15 06:00:16 +0000536 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
537 TP.error("Type inference contradiction found, forcing '" +
538 InputSet.getName() + "' to have a vector element");
539 return MadeChange;
540}
541
David Greene60322692011-01-24 20:53:18 +0000542/// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
543/// vector type specified by VTOperand.
544bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
545 TreePattern &TP) {
546 // "This" must be a vector and "VTOperand" must be a vector.
547 bool MadeChange = false;
548 MadeChange |= EnforceVector(TP);
549 MadeChange |= VTOperand.EnforceVector(TP);
550
551 // "This" must be larger than "VTOperand."
552 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
553
554 // If we know the vector type, it forces the scalar types to agree.
555 if (isConcrete()) {
556 EVT IVT = getConcrete();
557 IVT = IVT.getVectorElementType();
558
559 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
560 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
561 } else if (VTOperand.isConcrete()) {
562 EVT IVT = VTOperand.getConcrete();
563 IVT = IVT.getVectorElementType();
564
565 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
566 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
567 }
568
569 return MadeChange;
570}
571
Chris Lattner2cacec52010-03-15 06:00:16 +0000572//===----------------------------------------------------------------------===//
573// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000574
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000575bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
576 return LHS->getID() < RHS->getID();
577}
Scott Michel327d0652008-03-05 17:49:05 +0000578
579/// Dependent variable map for CodeGenDAGPattern variant generation
580typedef std::map<std::string, int> DepVarMap;
581
582/// Const iterator shorthand for DepVarMap
583typedef DepVarMap::const_iterator DepVarMap_citer;
584
Chris Lattner54379062011-04-17 21:38:24 +0000585static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel327d0652008-03-05 17:49:05 +0000586 if (N->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +0000587 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL)
Scott Michel327d0652008-03-05 17:49:05 +0000588 DepMap[N->getName()]++;
Scott Michel327d0652008-03-05 17:49:05 +0000589 } else {
590 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
591 FindDepVarsOf(N->getChild(i), DepMap);
592 }
593}
Chris Lattner54379062011-04-17 21:38:24 +0000594
595/// Find dependent variables within child patterns
596static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000597 DepVarMap depcounts;
598 FindDepVarsOf(N, depcounts);
599 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner54379062011-04-17 21:38:24 +0000600 if (i->second > 1) // std::pair<std::string, int>
Scott Michel327d0652008-03-05 17:49:05 +0000601 DepVars.insert(i->first);
Scott Michel327d0652008-03-05 17:49:05 +0000602 }
603}
604
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000605#ifndef NDEBUG
Chris Lattner54379062011-04-17 21:38:24 +0000606/// Dump the dependent variable set:
607static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000608 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000609 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000610 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000611 DEBUG(errs() << "[ ");
Jim Grosbachbb168242010-10-08 18:13:57 +0000612 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
613 e = DepVars.end(); i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000614 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000615 }
Chris Lattner569f1212009-08-23 04:44:11 +0000616 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000617 }
618}
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000619#endif
620
Chris Lattner54379062011-04-17 21:38:24 +0000621
622//===----------------------------------------------------------------------===//
623// TreePredicateFn Implementation
624//===----------------------------------------------------------------------===//
625
Chris Lattner7ed13912011-04-17 22:05:17 +0000626/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
627TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
628 assert((getPredCode().empty() || getImmCode().empty()) &&
629 ".td file corrupt: can't have a node predicate *and* an imm predicate");
630}
631
Chris Lattner54379062011-04-17 21:38:24 +0000632std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +0000633 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner54379062011-04-17 21:38:24 +0000634}
635
Chris Lattner7ed13912011-04-17 22:05:17 +0000636std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +0000637 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner7ed13912011-04-17 22:05:17 +0000638}
639
Chris Lattner54379062011-04-17 21:38:24 +0000640
641/// isAlwaysTrue - Return true if this is a noop predicate.
642bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000643 return getPredCode().empty() && getImmCode().empty();
Chris Lattner54379062011-04-17 21:38:24 +0000644}
645
646/// Return the name to use in the generated code to reference this, this is
647/// "Predicate_foo" if from a pattern fragment "foo".
648std::string TreePredicateFn::getFnName() const {
649 return "Predicate_" + PatFragRec->getRecord()->getName();
650}
651
652/// getCodeToRunOnSDNode - Return the code for the function body that
653/// evaluates this predicate. The argument is expected to be in "Node",
654/// not N. This handles casting and conversion to a concrete node type as
655/// appropriate.
656std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000657 // Handle immediate predicates first.
658 std::string ImmCode = getImmCode();
659 if (!ImmCode.empty()) {
660 std::string Result =
661 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner7ed13912011-04-17 22:05:17 +0000662 return Result + ImmCode;
663 }
664
665 // Handle arbitrary node predicates.
666 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner54379062011-04-17 21:38:24 +0000667 std::string ClassName;
668 if (PatFragRec->getOnlyTree()->isLeaf())
669 ClassName = "SDNode";
670 else {
671 Record *Op = PatFragRec->getOnlyTree()->getOperator();
672 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
673 }
674 std::string Result;
675 if (ClassName == "SDNode")
676 Result = " SDNode *N = Node;\n";
677 else
678 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
679
680 return Result + getPredCode();
Scott Michel327d0652008-03-05 17:49:05 +0000681}
682
Chris Lattner6cefb772008-01-05 22:25:12 +0000683//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000684// PatternToMatch implementation
685//
686
Chris Lattner48e86db2010-03-29 01:40:38 +0000687
688/// getPatternSize - Return the 'size' of this pattern. We want to match large
689/// patterns before small ones. This is used to determine the size of a
690/// pattern.
691static unsigned getPatternSize(const TreePatternNode *P,
692 const CodeGenDAGPatterns &CGP) {
693 unsigned Size = 3; // The node itself.
694 // If the root node is a ConstantSDNode, increases its size.
695 // e.g. (set R32:$dst, 0).
David Greene05bce0b2011-07-29 22:43:06 +0000696 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000697 Size += 2;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000698
Chris Lattner48e86db2010-03-29 01:40:38 +0000699 // FIXME: This is a hack to statically increase the priority of patterns
700 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
701 // Later we can allow complexity / cost for each pattern to be (optionally)
702 // specified. To get best possible pattern match we'll need to dynamically
703 // calculate the complexity of all patterns a dag can potentially map to.
704 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
705 if (AM)
706 Size += AM->getNumOperands() * 3;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000707
Chris Lattner48e86db2010-03-29 01:40:38 +0000708 // If this node has some predicate function that must match, it adds to the
709 // complexity of this node.
710 if (!P->getPredicateFns().empty())
711 ++Size;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000712
Chris Lattner48e86db2010-03-29 01:40:38 +0000713 // Count children in the count if they are also nodes.
714 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
715 TreePatternNode *Child = P->getChild(i);
716 if (!Child->isLeaf() && Child->getNumTypes() &&
717 Child->getType(0) != MVT::Other)
718 Size += getPatternSize(Child, CGP);
719 else if (Child->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +0000720 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000721 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
722 else if (Child->getComplexPatternInfo(CGP))
723 Size += getPatternSize(Child, CGP);
724 else if (!Child->getPredicateFns().empty())
725 ++Size;
726 }
727 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000728
Chris Lattner48e86db2010-03-29 01:40:38 +0000729 return Size;
730}
731
732/// Compute the complexity metric for the input pattern. This roughly
733/// corresponds to the number of nodes that are covered.
734unsigned PatternToMatch::
735getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
736 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
737}
738
739
Dan Gohman22bb3112008-08-22 00:20:26 +0000740/// getPredicateCheck - Return a single string containing all of this
741/// pattern's predicates concatenated with "&&" operators.
742///
743std::string PatternToMatch::getPredicateCheck() const {
744 std::string PredicateCheck;
745 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +0000746 if (DefInit *Pred = dynamic_cast<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
Craig Topper655b8de2012-02-05 07:21:30 +0000752 llvm_unreachable("Unknown predicate type!");
Dan Gohman22bb3112008-08-22 00:20:26 +0000753 }
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) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000843 case SDTCisVT:
844 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000845 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000846 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000847 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000848 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000849 case SDTCisInt:
850 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000851 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000852 case SDTCisFP:
853 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000854 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000855 case SDTCisVec:
856 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000857 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000858 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000859 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000860 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000861 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000862 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
863 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000864 }
865 case SDTCisVTSmallerThanOp: {
866 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
867 // have an integer type that is smaller than the VT.
868 if (!NodeToApply->isLeaf() ||
David Greene05bce0b2011-07-29 22:43:06 +0000869 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
870 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Chris Lattner6cefb772008-01-05 22:25:12 +0000871 ->isSubClassOf("ValueType"))
872 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000873 MVT::SimpleValueType VT =
David Greene05bce0b2011-07-29 22:43:06 +0000874 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000875
Chris Lattnercc878302010-03-24 00:06:46 +0000876 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000877
Chris Lattner2e68a022010-03-19 21:56:21 +0000878 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000879 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000880 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
881 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000882
Chris Lattnercc878302010-03-24 00:06:46 +0000883 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000884 }
885 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000886 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000887 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000888 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
889 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000890 return NodeToApply->getExtType(ResNo).
891 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000892 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000893 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000894 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000895 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000896 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
897 VResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000898
Chris Lattner66fb9d22010-03-24 00:01:16 +0000899 // Filter vector types out of VecOperand that don't have the right element
900 // type.
901 return VecOperand->getExtType(VResNo).
902 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000903 }
David Greene60322692011-01-24 20:53:18 +0000904 case SDTCisSubVecOfVec: {
905 unsigned VResNo = 0;
906 TreePatternNode *BigVecOperand =
907 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
908 VResNo);
909
910 // Filter vector types out of BigVecOperand that don't have the
911 // right subvector type.
912 return BigVecOperand->getExtType(VResNo).
913 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
914 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000915 }
David Blaikie58bd1512012-01-17 07:00:13 +0000916 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner6cefb772008-01-05 22:25:12 +0000917}
918
919//===----------------------------------------------------------------------===//
920// SDNodeInfo implementation
921//
922SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
923 EnumName = R->getValueAsString("Opcode");
924 SDClassName = R->getValueAsString("SDClass");
925 Record *TypeProfile = R->getValueAsDef("TypeProfile");
926 NumResults = TypeProfile->getValueAsInt("NumResults");
927 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000928
Chris Lattner6cefb772008-01-05 22:25:12 +0000929 // Parse the properties.
930 Properties = 0;
931 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
932 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
933 if (PropList[i]->getName() == "SDNPCommutative") {
934 Properties |= 1 << SDNPCommutative;
935 } else if (PropList[i]->getName() == "SDNPAssociative") {
936 Properties |= 1 << SDNPAssociative;
937 } else if (PropList[i]->getName() == "SDNPHasChain") {
938 Properties |= 1 << SDNPHasChain;
Chris Lattner036609b2010-12-23 18:28:41 +0000939 } else if (PropList[i]->getName() == "SDNPOutGlue") {
940 Properties |= 1 << SDNPOutGlue;
941 } else if (PropList[i]->getName() == "SDNPInGlue") {
942 Properties |= 1 << SDNPInGlue;
943 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
944 Properties |= 1 << SDNPOptInGlue;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000945 } else if (PropList[i]->getName() == "SDNPMayStore") {
946 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000947 } else if (PropList[i]->getName() == "SDNPMayLoad") {
948 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000949 } else if (PropList[i]->getName() == "SDNPSideEffect") {
950 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000951 } else if (PropList[i]->getName() == "SDNPMemOperand") {
952 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000953 } else if (PropList[i]->getName() == "SDNPVariadic") {
954 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000955 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000956 errs() << "Unknown SD Node property '" << PropList[i]->getName()
957 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000958 exit(1);
959 }
960 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000961
962
Chris Lattner6cefb772008-01-05 22:25:12 +0000963 // Parse the type constraints.
964 std::vector<Record*> ConstraintList =
965 TypeProfile->getValueAsListOfDefs("Constraints");
966 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
967}
968
Chris Lattner22579812010-02-28 00:22:30 +0000969/// getKnownType - If the type constraints on this node imply a fixed type
970/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000971/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +0000972MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +0000973 unsigned NumResults = getNumResults();
974 assert(NumResults <= 1 &&
975 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +0000976 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000977
Chris Lattner22579812010-02-28 00:22:30 +0000978 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
979 // Make sure that this applies to the correct node result.
980 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
981 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000982
Chris Lattner22579812010-02-28 00:22:30 +0000983 switch (TypeConstraints[i].ConstraintType) {
984 default: break;
985 case SDTypeConstraint::SDTCisVT:
986 return TypeConstraints[i].x.SDTCisVT_Info.VT;
987 case SDTypeConstraint::SDTCisPtrTy:
988 return MVT::iPTR;
989 }
990 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000991 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000992}
993
Chris Lattner6cefb772008-01-05 22:25:12 +0000994//===----------------------------------------------------------------------===//
995// TreePatternNode implementation
996//
997
998TreePatternNode::~TreePatternNode() {
999#if 0 // FIXME: implement refcounted tree nodes!
1000 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1001 delete getChild(i);
1002#endif
1003}
1004
Chris Lattnerd7349192010-03-19 21:37:09 +00001005static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1006 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +00001007 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +00001008 return 0; // All return nothing.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001009
Chris Lattner93dc92e2010-03-22 20:56:36 +00001010 if (Operator->isSubClassOf("Intrinsic"))
1011 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001012
Chris Lattnerd7349192010-03-19 21:37:09 +00001013 if (Operator->isSubClassOf("SDNode"))
1014 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001015
Chris Lattnerd7349192010-03-19 21:37:09 +00001016 if (Operator->isSubClassOf("PatFrag")) {
1017 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1018 // the forward reference case where one pattern fragment references another
1019 // before it is processed.
1020 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1021 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001022
Chris Lattnerd7349192010-03-19 21:37:09 +00001023 // Get the result tree.
David Greene05bce0b2011-07-29 22:43:06 +00001024 DagInit *Tree = Operator->getValueAsDag("Fragment");
Chris Lattnerd7349192010-03-19 21:37:09 +00001025 Record *Op = 0;
David Greene05bce0b2011-07-29 22:43:06 +00001026 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
1027 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
Chris Lattnerd7349192010-03-19 21:37:09 +00001028 assert(Op && "Invalid Fragment");
1029 return GetNumNodeResults(Op, CDP);
1030 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001031
Chris Lattnerd7349192010-03-19 21:37:09 +00001032 if (Operator->isSubClassOf("Instruction")) {
1033 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001034
1035 // FIXME: Should allow access to all the results here.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001036 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001037
Chris Lattner9414ae52010-03-27 20:09:24 +00001038 // Add on one implicit def if it has a resolvable type.
1039 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1040 ++NumDefsToAdd;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001041 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +00001042 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001043
Chris Lattnerd7349192010-03-19 21:37:09 +00001044 if (Operator->isSubClassOf("SDNodeXForm"))
1045 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001046
Chris Lattnerd7349192010-03-19 21:37:09 +00001047 Operator->dump();
1048 errs() << "Unhandled node in GetNumNodeResults\n";
1049 exit(1);
1050}
1051
1052void TreePatternNode::print(raw_ostream &OS) const {
1053 if (isLeaf())
1054 OS << *getLeafValue();
1055 else
1056 OS << '(' << getOperator()->getName();
1057
1058 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1059 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +00001060
1061 if (!isLeaf()) {
1062 if (getNumChildren() != 0) {
1063 OS << " ";
1064 getChild(0)->print(OS);
1065 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1066 OS << ", ";
1067 getChild(i)->print(OS);
1068 }
1069 }
1070 OS << ")";
1071 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001072
Dan Gohman0540e172008-10-15 06:17:21 +00001073 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner54379062011-04-17 21:38:24 +00001074 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +00001075 if (TransformFn)
1076 OS << "<<X:" << TransformFn->getName() << ">>";
1077 if (!getName().empty())
1078 OS << ":$" << getName();
1079
1080}
1081void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001082 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +00001083}
1084
Scott Michel327d0652008-03-05 17:49:05 +00001085/// isIsomorphicTo - Return true if this node is recursively
1086/// isomorphic to the specified node. For this comparison, the node's
1087/// entire state is considered. The assigned name is ignored, since
1088/// nodes with differing names are considered isomorphic. However, if
1089/// the assigned name is present in the dependent variable set, then
1090/// the assigned name is considered significant and the node is
1091/// isomorphic if the names match.
1092bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1093 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001094 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +00001095 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +00001096 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00001097 getTransformFn() != N->getTransformFn())
1098 return false;
1099
1100 if (isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001101 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1102 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +00001103 return ((DI->getDef() == NDI->getDef())
1104 && (DepVars.find(getName()) == DepVars.end()
1105 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +00001106 }
1107 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001108 return getLeafValue() == N->getLeafValue();
1109 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001110
Chris Lattner6cefb772008-01-05 22:25:12 +00001111 if (N->getOperator() != getOperator() ||
1112 N->getNumChildren() != getNumChildren()) return false;
1113 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00001114 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +00001115 return false;
1116 return true;
1117}
1118
1119/// clone - Make a copy of this tree and all of its children.
1120///
1121TreePatternNode *TreePatternNode::clone() const {
1122 TreePatternNode *New;
1123 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001124 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001125 } else {
1126 std::vector<TreePatternNode*> CChildren;
1127 CChildren.reserve(Children.size());
1128 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1129 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +00001130 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001131 }
1132 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001133 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +00001134 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00001135 New->setTransformFn(getTransformFn());
1136 return New;
1137}
1138
Chris Lattner47661322010-02-14 22:22:58 +00001139/// RemoveAllTypes - Recursively strip all the types of this tree.
1140void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +00001141 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1142 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +00001143 if (isLeaf()) return;
1144 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1145 getChild(i)->RemoveAllTypes();
1146}
1147
1148
Chris Lattner6cefb772008-01-05 22:25:12 +00001149/// SubstituteFormalArguments - Replace the formal arguments in this tree
1150/// with actual values specified by ArgMap.
1151void TreePatternNode::
1152SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1153 if (isLeaf()) return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001154
Chris Lattner6cefb772008-01-05 22:25:12 +00001155 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1156 TreePatternNode *Child = getChild(i);
1157 if (Child->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001158 Init *Val = Child->getLeafValue();
1159 if (dynamic_cast<DefInit*>(Val) &&
1160 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001161 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +00001162 TreePatternNode *NewChild = ArgMap[Child->getName()];
1163 assert(NewChild && "Couldn't find formal argument!");
1164 assert((Child->getPredicateFns().empty() ||
1165 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1166 "Non-empty child predicate clobbered!");
1167 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +00001168 }
1169 } else {
1170 getChild(i)->SubstituteFormalArguments(ArgMap);
1171 }
1172 }
1173}
1174
1175
1176/// InlinePatternFragments - If this pattern refers to any pattern
1177/// fragments, inline them into place, giving us a pattern without any
1178/// PatFrag references.
1179TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1180 if (isLeaf()) return this; // nothing to do.
1181 Record *Op = getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001182
Chris Lattner6cefb772008-01-05 22:25:12 +00001183 if (!Op->isSubClassOf("PatFrag")) {
1184 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00001185 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1186 TreePatternNode *Child = getChild(i);
1187 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1188
1189 assert((Child->getPredicateFns().empty() ||
1190 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1191 "Non-empty child predicate clobbered!");
1192
1193 setChild(i, NewChild);
1194 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001195 return this;
1196 }
1197
1198 // Otherwise, we found a reference to a fragment. First, look up its
1199 // TreePattern record.
1200 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001201
Chris Lattner6cefb772008-01-05 22:25:12 +00001202 // Verify that we are passing the right number of operands.
1203 if (Frag->getNumArgs() != Children.size())
1204 TP.error("'" + Op->getName() + "' fragment requires " +
1205 utostr(Frag->getNumArgs()) + " operands!");
1206
1207 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1208
Chris Lattner54379062011-04-17 21:38:24 +00001209 TreePredicateFn PredFn(Frag);
1210 if (!PredFn.isAlwaysTrue())
1211 FragTree->addPredicateFn(PredFn);
Dan Gohman0540e172008-10-15 06:17:21 +00001212
Chris Lattner6cefb772008-01-05 22:25:12 +00001213 // Resolve formal arguments to their actual value.
1214 if (Frag->getNumArgs()) {
1215 // Compute the map of formal to actual arguments.
1216 std::map<std::string, TreePatternNode*> ArgMap;
1217 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1218 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001219
Chris Lattner6cefb772008-01-05 22:25:12 +00001220 FragTree->SubstituteFormalArguments(ArgMap);
1221 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001222
Chris Lattner6cefb772008-01-05 22:25:12 +00001223 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001224 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1225 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +00001226
1227 // Transfer in the old predicates.
1228 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1229 FragTree->addPredicateFn(getPredicateFns()[i]);
1230
Chris Lattner6cefb772008-01-05 22:25:12 +00001231 // Get a new copy of this fragment to stitch into here.
1232 //delete this; // FIXME: implement refcounting!
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001233
Chris Lattner2ca698d2008-06-30 03:02:03 +00001234 // The fragment we inlined could have recursive inlining that is needed. See
1235 // if there are any pattern fragments in it and inline them as needed.
1236 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001237}
1238
1239/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +00001240/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +00001241/// references from the register file information, for example.
1242///
Chris Lattnerd7349192010-03-19 21:37:09 +00001243static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1244 bool NotRegisters, TreePattern &TP) {
Owen Andersonbea6f612011-06-27 21:06:21 +00001245 // Check to see if this is a register operand.
1246 if (R->isSubClassOf("RegisterOperand")) {
1247 assert(ResNo == 0 && "Regoperand ref only has one result!");
1248 if (NotRegisters)
1249 return EEVT::TypeSet(); // Unknown.
1250 Record *RegClass = R->getValueAsDef("RegClass");
1251 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1252 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1253 }
1254
Chris Lattner2cacec52010-03-15 06:00:16 +00001255 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +00001256 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00001257 assert(ResNo == 0 && "Regclass ref only has one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001258 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001259 return EEVT::TypeSet(); // Unknown.
1260 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1261 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001262 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001263
Chris Lattner640a3f52010-03-23 23:50:31 +00001264 if (R->isSubClassOf("PatFrag")) {
1265 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001266 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001267 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001268 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001269
Chris Lattner640a3f52010-03-23 23:50:31 +00001270 if (R->isSubClassOf("Register")) {
1271 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001272 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001273 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001274 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001275 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001276 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +00001277
1278 if (R->isSubClassOf("SubRegIndex")) {
1279 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1280 return EEVT::TypeSet();
1281 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001282
Chris Lattner640a3f52010-03-23 23:50:31 +00001283 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1284 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001285 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001286 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001287 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001288
Chris Lattner640a3f52010-03-23 23:50:31 +00001289 if (R->isSubClassOf("ComplexPattern")) {
1290 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001291 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001292 return EEVT::TypeSet(); // Unknown.
1293 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1294 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001295 }
1296 if (R->isSubClassOf("PointerLikeRegClass")) {
1297 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001298 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001299 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001300
Chris Lattner640a3f52010-03-23 23:50:31 +00001301 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1302 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001303 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001304 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001305 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001306
Chris Lattner6cefb772008-01-05 22:25:12 +00001307 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001308 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001309}
1310
Chris Lattnere67bde52008-01-06 05:36:50 +00001311
1312/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1313/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1314const CodeGenIntrinsic *TreePatternNode::
1315getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1316 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1317 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1318 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1319 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001320
1321 unsigned IID =
David Greene05bce0b2011-07-29 22:43:06 +00001322 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
Chris Lattnere67bde52008-01-06 05:36:50 +00001323 return &CDP.getIntrinsicInfo(IID);
1324}
1325
Chris Lattner47661322010-02-14 22:22:58 +00001326/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1327/// return the ComplexPattern information, otherwise return null.
1328const ComplexPattern *
1329TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1330 if (!isLeaf()) return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001331
David Greene05bce0b2011-07-29 22:43:06 +00001332 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
Chris Lattner47661322010-02-14 22:22:58 +00001333 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1334 return &CGP.getComplexPattern(DI->getDef());
1335 return 0;
1336}
1337
1338/// NodeHasProperty - Return true if this node has the specified property.
1339bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001340 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001341 if (isLeaf()) {
1342 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1343 return CP->hasProperty(Property);
1344 return false;
1345 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001346
Chris Lattner47661322010-02-14 22:22:58 +00001347 Record *Operator = getOperator();
1348 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001349
Chris Lattner47661322010-02-14 22:22:58 +00001350 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1351}
1352
1353
1354
1355
1356/// TreeHasProperty - Return true if any node in this tree has the specified
1357/// property.
1358bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001359 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001360 if (NodeHasProperty(Property, CGP))
1361 return true;
1362 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1363 if (getChild(i)->TreeHasProperty(Property, CGP))
1364 return true;
1365 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001366}
Chris Lattner47661322010-02-14 22:22:58 +00001367
Evan Cheng6bd95672008-06-16 20:29:38 +00001368/// isCommutativeIntrinsic - Return true if the node corresponds to a
1369/// commutative intrinsic.
1370bool
1371TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1372 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1373 return Int->isCommutative;
1374 return false;
1375}
1376
Chris Lattnere67bde52008-01-06 05:36:50 +00001377
Bob Wilson6c01ca92009-01-05 17:23:09 +00001378/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001379/// this node and its children in the tree. This returns true if it makes a
1380/// change, false otherwise. If a type contradiction is found, throw an
1381/// exception.
1382bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001383 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001384 if (isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001385 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001386 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001387 bool MadeChange = false;
1388 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1389 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1390 NotRegisters, TP), TP);
1391 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001392 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001393
David Greene05bce0b2011-07-29 22:43:06 +00001394 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001395 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001396
Chris Lattnerd7349192010-03-19 21:37:09 +00001397 // Int inits are always integers. :)
1398 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001399
Chris Lattnerd7349192010-03-19 21:37:09 +00001400 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001401 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001402
Chris Lattnerd7349192010-03-19 21:37:09 +00001403 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001404 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1405 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001406
Chris Lattner2cacec52010-03-15 06:00:16 +00001407 unsigned Size = EVT(VT).getSizeInBits();
1408 // Make sure that the value is representable for this type.
1409 if (Size >= 32) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001410
Chris Lattner2cacec52010-03-15 06:00:16 +00001411 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1412 if (Val == II->getValue()) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001413
Chris Lattner2cacec52010-03-15 06:00:16 +00001414 // If sign-extended doesn't fit, does it fit as unsigned?
1415 unsigned ValueMask;
1416 unsigned UnsignedVal;
1417 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1418 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001419
Chris Lattner2cacec52010-03-15 06:00:16 +00001420 if ((ValueMask & UnsignedVal) == UnsignedVal)
1421 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001422
Chris Lattner2cacec52010-03-15 06:00:16 +00001423 TP.error("Integer value '" + itostr(II->getValue())+
Chris Lattnerd7349192010-03-19 21:37:09 +00001424 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001425 return MadeChange;
1426 }
1427 return false;
1428 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001429
Chris Lattner6cefb772008-01-05 22:25:12 +00001430 // special handling for set, which isn't really an SDNode.
1431 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001432 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1433 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001434 unsigned NC = getNumChildren();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001435
Chris Lattnerd7349192010-03-19 21:37:09 +00001436 TreePatternNode *SetVal = getChild(NC-1);
1437 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1438
Chris Lattner6cefb772008-01-05 22:25:12 +00001439 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001440 TreePatternNode *Child = getChild(i);
1441 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001442
Chris Lattner6cefb772008-01-05 22:25:12 +00001443 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001444 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1445 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001446 }
1447 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001448 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001449
Chris Lattner310adf12010-03-27 02:53:27 +00001450 if (getOperator()->getName() == "implicit") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001451 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1452
Chris Lattner6cefb772008-01-05 22:25:12 +00001453 bool MadeChange = false;
1454 for (unsigned i = 0; i < getNumChildren(); ++i)
1455 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001456 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001457 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001458
Chris Lattner6eb30122010-02-23 05:51:07 +00001459 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001460 bool MadeChange = false;
1461 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1462 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001463
Chris Lattnerd7349192010-03-19 21:37:09 +00001464 assert(getChild(0)->getNumTypes() == 1 &&
1465 getChild(1)->getNumTypes() == 1 && "Unhandled case");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001466
Chris Lattner2cacec52010-03-15 06:00:16 +00001467 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1468 // what type it gets, so if it didn't get a concrete type just give it the
1469 // first viable type from the reg class.
Chris Lattnerd7349192010-03-19 21:37:09 +00001470 if (!getChild(1)->hasTypeSet(0) &&
1471 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1472 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1473 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001474 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001475 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001476 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001477
Chris Lattner6eb30122010-02-23 05:51:07 +00001478 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001479 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001480
Chris Lattner6cefb772008-01-05 22:25:12 +00001481 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001482 unsigned NumRetVTs = Int->IS.RetVTs.size();
1483 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001484
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001485 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001486 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001487
Chris Lattnerd7349192010-03-19 21:37:09 +00001488 if (getNumChildren() != NumParamVTs + 1)
Chris Lattnere67bde52008-01-06 05:36:50 +00001489 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001490 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001491 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001492
1493 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001494 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001495
Chris Lattnerd7349192010-03-19 21:37:09 +00001496 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1497 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001498
Chris Lattnerd7349192010-03-19 21:37:09 +00001499 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1500 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1501 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001502 }
1503 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001504 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001505
Chris Lattner6eb30122010-02-23 05:51:07 +00001506 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001507 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001508
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001509 // Check that the number of operands is sane. Negative operands -> varargs.
1510 if (NI.getNumOperands() >= 0 &&
1511 getNumChildren() != (unsigned)NI.getNumOperands())
1512 TP.error(getOperator()->getName() + " node requires exactly " +
1513 itostr(NI.getNumOperands()) + " operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001514
Chris Lattner6cefb772008-01-05 22:25:12 +00001515 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1516 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1517 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001518 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001519 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001520
Chris Lattner6eb30122010-02-23 05:51:07 +00001521 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001522 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001523 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001524 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001525
Chris Lattner0be6fe72010-03-27 19:15:02 +00001526 bool MadeChange = false;
1527
1528 // Apply the result types to the node, these come from the things in the
1529 // (outs) list of the instruction.
1530 // FIXME: Cap at one result so far.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001531 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001532 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1533 Record *ResultNode = Inst.getResult(ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001534
Chris Lattnera938ac62009-07-29 20:43:05 +00001535 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001536 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
Owen Andersonbea6f612011-06-27 21:06:21 +00001537 } else if (ResultNode->isSubClassOf("RegisterOperand")) {
1538 Record *RegClass = ResultNode->getValueAsDef("RegClass");
1539 const CodeGenRegisterClass &RC =
1540 CDP.getTargetInfo().getRegisterClass(RegClass);
1541 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001542 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001543 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001544 } else {
1545 assert(ResultNode->isSubClassOf("RegisterClass") &&
1546 "Operands should be register classes!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001547 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001548 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001549 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001550 }
Chris Lattner0be6fe72010-03-27 19:15:02 +00001551 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001552
Chris Lattner0be6fe72010-03-27 19:15:02 +00001553 // If the instruction has implicit defs, we apply the first one as a result.
1554 // FIXME: This sucks, it should apply all implicit defs.
1555 if (!InstInfo.ImplicitDefs.empty()) {
1556 unsigned ResNo = NumResultsToAdd;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001557
Chris Lattner9414ae52010-03-27 20:09:24 +00001558 // FIXME: Generalize to multiple possible types and multiple possible
1559 // ImplicitDefs.
1560 MVT::SimpleValueType VT =
1561 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001562
Chris Lattner9414ae52010-03-27 20:09:24 +00001563 if (VT != MVT::Other)
1564 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001565 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001566
Chris Lattner2cacec52010-03-15 06:00:16 +00001567 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1568 // be the same.
1569 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001570 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1571 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1572 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001573 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001574
1575 unsigned ChildNo = 0;
1576 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1577 Record *OperandNode = Inst.getOperand(i);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001578
Chris Lattner6cefb772008-01-05 22:25:12 +00001579 // If the instruction expects a predicate or optional def operand, we
1580 // codegen this by setting the operand to it's default value if it has a
1581 // non-empty DefaultOps field.
1582 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1583 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1584 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1585 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001586
Chris Lattner6cefb772008-01-05 22:25:12 +00001587 // Verify that we didn't run out of provided operands.
1588 if (ChildNo >= getNumChildren())
1589 TP.error("Instruction '" + getOperator()->getName() +
1590 "' expects more operands than were provided.");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001591
Owen Anderson825b72b2009-08-11 20:47:22 +00001592 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001593 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001594 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001595
Chris Lattner6cefb772008-01-05 22:25:12 +00001596 if (OperandNode->isSubClassOf("RegisterClass")) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001597 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001598 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001599 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Owen Andersonbea6f612011-06-27 21:06:21 +00001600 } else if (OperandNode->isSubClassOf("RegisterOperand")) {
1601 Record *RegClass = OperandNode->getValueAsDef("RegClass");
1602 const CodeGenRegisterClass &RC =
1603 CDP.getTargetInfo().getRegisterClass(RegClass);
1604 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001605 } else if (OperandNode->isSubClassOf("Operand")) {
1606 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattner0be6fe72010-03-27 19:15:02 +00001607 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001608 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001609 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001610 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001611 // Nothing to do.
Craig Topper655b8de2012-02-05 07:21:30 +00001612 } else
1613 llvm_unreachable("Unknown operand type!");
1614
Chris Lattner6cefb772008-01-05 22:25:12 +00001615 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1616 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001617
Christopher Lamb02f69372008-03-10 04:16:09 +00001618 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001619 TP.error("Instruction '" + getOperator()->getName() +
1620 "' was provided too many operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001621
Chris Lattner6cefb772008-01-05 22:25:12 +00001622 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001623 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001624
Chris Lattner6eb30122010-02-23 05:51:07 +00001625 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001626
Chris Lattner6eb30122010-02-23 05:51:07 +00001627 // Node transforms always take one operand.
1628 if (getNumChildren() != 1)
1629 TP.error("Node transform '" + getOperator()->getName() +
1630 "' requires one operand!");
1631
Chris Lattner2cacec52010-03-15 06:00:16 +00001632 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1633
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001634
Chris Lattner6eb30122010-02-23 05:51:07 +00001635 // If either the output or input of the xform does not have exact
1636 // type info. We assume they must be the same. Otherwise, it is perfectly
1637 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001638#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001639 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001640 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1641 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001642 return MadeChange;
1643 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001644#endif
1645 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001646}
1647
1648/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1649/// RHS of a commutative operation, not the on LHS.
1650static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1651 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1652 return true;
David Greene05bce0b2011-07-29 22:43:06 +00001653 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
Chris Lattner6cefb772008-01-05 22:25:12 +00001654 return true;
1655 return false;
1656}
1657
1658
1659/// canPatternMatch - If it is impossible for this pattern to match on this
1660/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001661/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001662/// that can never possibly work), and to prevent the pattern permuter from
1663/// generating stuff that is useless.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001664bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001665 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001666 if (isLeaf()) return true;
1667
1668 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1669 if (!getChild(i)->canPatternMatch(Reason, CDP))
1670 return false;
1671
1672 // If this is an intrinsic, handle cases that would make it not match. For
1673 // example, if an operand is required to be an immediate.
1674 if (getOperator()->isSubClassOf("Intrinsic")) {
1675 // TODO:
1676 return true;
1677 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001678
Chris Lattner6cefb772008-01-05 22:25:12 +00001679 // If this node is a commutative operator, check that the LHS isn't an
1680 // immediate.
1681 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001682 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1683 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001684 // Scan all of the operands of the node and make sure that only the last one
1685 // is a constant node, unless the RHS also is.
1686 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001687 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1688 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001689 if (OnlyOnRHSOfCommutative(getChild(i))) {
1690 Reason="Immediate value must be on the RHS of commutative operators!";
1691 return false;
1692 }
1693 }
1694 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001695
Chris Lattner6cefb772008-01-05 22:25:12 +00001696 return true;
1697}
1698
1699//===----------------------------------------------------------------------===//
1700// TreePattern implementation
1701//
1702
David Greene05bce0b2011-07-29 22:43:06 +00001703TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001704 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001705 isInputPattern = isInput;
1706 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattnerc2173052010-03-28 06:50:34 +00001707 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001708}
1709
David Greene05bce0b2011-07-29 22:43:06 +00001710TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001711 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001712 isInputPattern = isInput;
Chris Lattnerc2173052010-03-28 06:50:34 +00001713 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001714}
1715
1716TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001717 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001718 isInputPattern = isInput;
1719 Trees.push_back(Pat);
1720}
1721
Chris Lattner6cefb772008-01-05 22:25:12 +00001722void TreePattern::error(const std::string &Msg) const {
1723 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001724 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001725}
1726
Chris Lattner2cacec52010-03-15 06:00:16 +00001727void TreePattern::ComputeNamedNodes() {
1728 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1729 ComputeNamedNodes(Trees[i]);
1730}
1731
1732void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1733 if (!N->getName().empty())
1734 NamedNodes[N->getName()].push_back(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001735
Chris Lattner2cacec52010-03-15 06:00:16 +00001736 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1737 ComputeNamedNodes(N->getChild(i));
1738}
1739
Chris Lattnerd7349192010-03-19 21:37:09 +00001740
David Greene05bce0b2011-07-29 22:43:06 +00001741TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1742 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001743 Record *R = DI->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001744
Chris Lattnerc2173052010-03-28 06:50:34 +00001745 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbach66c9ee72011-07-06 23:38:13 +00001746 // TreePatternNode of its own. For example:
Chris Lattnerc2173052010-03-28 06:50:34 +00001747 /// (foo GPR, imm) -> (foo GPR, (imm))
1748 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenedcd35c72011-07-29 19:07:07 +00001749 return ParseTreePattern(
1750 DagInit::get(DI, "",
David Greene05bce0b2011-07-29 22:43:06 +00001751 std::vector<std::pair<Init*, std::string> >()),
David Greenedcd35c72011-07-29 19:07:07 +00001752 OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001753
Chris Lattnerc2173052010-03-28 06:50:34 +00001754 // Input argument?
1755 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001756 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001757 if (OpName.empty())
1758 error("'node' argument requires a name to match with operand list");
1759 Args.push_back(OpName);
1760 }
1761
1762 Res->setName(OpName);
1763 return Res;
1764 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001765
David Greene05bce0b2011-07-29 22:43:06 +00001766 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001767 if (!OpName.empty())
1768 error("Constant int argument should not have a name!");
1769 return new TreePatternNode(II, 1);
1770 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001771
David Greene05bce0b2011-07-29 22:43:06 +00001772 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001773 // Turn this into an IntInit.
David Greene05bce0b2011-07-29 22:43:06 +00001774 Init *II = BI->convertInitializerTo(IntRecTy::get());
1775 if (II == 0 || !dynamic_cast<IntInit*>(II))
Chris Lattnerc2173052010-03-28 06:50:34 +00001776 error("Bits value must be constants!");
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001777 return ParseTreePattern(II, OpName);
Chris Lattnerc2173052010-03-28 06:50:34 +00001778 }
1779
David Greene05bce0b2011-07-29 22:43:06 +00001780 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
Chris Lattnerc2173052010-03-28 06:50:34 +00001781 if (!Dag) {
1782 TheInit->dump();
1783 error("Pattern has unexpected init kind!");
1784 }
David Greene05bce0b2011-07-29 22:43:06 +00001785 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001786 if (!OpDef) error("Pattern has unexpected operator type!");
1787 Record *Operator = OpDef->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001788
Chris Lattner6cefb772008-01-05 22:25:12 +00001789 if (Operator->isSubClassOf("ValueType")) {
1790 // If the operator is a ValueType, then this must be "type cast" of a leaf
1791 // node.
1792 if (Dag->getNumArgs() != 1)
1793 error("Type cast only takes one operand!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001794
Chris Lattnerc2173052010-03-28 06:50:34 +00001795 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001796
Chris Lattner6cefb772008-01-05 22:25:12 +00001797 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001798 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1799 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001800
Chris Lattnerc2173052010-03-28 06:50:34 +00001801 if (!OpName.empty())
1802 error("ValueType cast should not have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001803 return New;
1804 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001805
Chris Lattner6cefb772008-01-05 22:25:12 +00001806 // Verify that this is something that makes sense for an operator.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001807 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begeman7cee8172009-03-19 05:21:56 +00001808 !Operator->isSubClassOf("SDNode") &&
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001809 !Operator->isSubClassOf("Instruction") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001810 !Operator->isSubClassOf("SDNodeXForm") &&
1811 !Operator->isSubClassOf("Intrinsic") &&
1812 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00001813 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00001814 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001815
Chris Lattner6cefb772008-01-05 22:25:12 +00001816 // Check to see if this is something that is illegal in an input pattern.
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001817 if (isInputPattern) {
1818 if (Operator->isSubClassOf("Instruction") ||
1819 Operator->isSubClassOf("SDNodeXForm"))
1820 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1821 } else {
1822 if (Operator->isSubClassOf("Intrinsic"))
1823 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001824
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001825 if (Operator->isSubClassOf("SDNode") &&
1826 Operator->getName() != "imm" &&
1827 Operator->getName() != "fpimm" &&
1828 Operator->getName() != "tglobaltlsaddr" &&
1829 Operator->getName() != "tconstpool" &&
1830 Operator->getName() != "tjumptable" &&
1831 Operator->getName() != "tframeindex" &&
1832 Operator->getName() != "texternalsym" &&
1833 Operator->getName() != "tblockaddress" &&
1834 Operator->getName() != "tglobaladdr" &&
1835 Operator->getName() != "bb" &&
1836 Operator->getName() != "vt")
1837 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1838 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001839
Chris Lattner6cefb772008-01-05 22:25:12 +00001840 std::vector<TreePatternNode*> Children;
Chris Lattnerc2173052010-03-28 06:50:34 +00001841
1842 // Parse all the operands.
1843 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1844 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001845
Chris Lattner6cefb772008-01-05 22:25:12 +00001846 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001847 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner6cefb772008-01-05 22:25:12 +00001848 // convert the intrinsic name to a number.
1849 if (Operator->isSubClassOf("Intrinsic")) {
1850 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1851 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1852
1853 // If this intrinsic returns void, it must have side-effects and thus a
1854 // chain.
Chris Lattnerc2173052010-03-28 06:50:34 +00001855 if (Int.IS.RetVTs.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001856 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001857 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner6cefb772008-01-05 22:25:12 +00001858 // Has side-effects, requires chain.
1859 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001860 else // Otherwise, no chain.
Chris Lattner6cefb772008-01-05 22:25:12 +00001861 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001862
David Greenedcd35c72011-07-29 19:07:07 +00001863 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001864 Children.insert(Children.begin(), IIDNode);
1865 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001866
Chris Lattnerd7349192010-03-19 21:37:09 +00001867 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1868 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattnerc2173052010-03-28 06:50:34 +00001869 Result->setName(OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001870
Chris Lattnerc2173052010-03-28 06:50:34 +00001871 if (!Dag->getName().empty()) {
1872 assert(Result->getName().empty());
1873 Result->setName(Dag->getName());
1874 }
Nate Begeman7cee8172009-03-19 05:21:56 +00001875 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001876}
1877
Chris Lattner7a0eb912010-03-28 08:38:32 +00001878/// SimplifyTree - See if we can simplify this tree to eliminate something that
1879/// will never match in favor of something obvious that will. This is here
1880/// strictly as a convenience to target authors because it allows them to write
1881/// more type generic things and have useless type casts fold away.
1882///
1883/// This returns true if any change is made.
1884static bool SimplifyTree(TreePatternNode *&N) {
1885 if (N->isLeaf())
1886 return false;
1887
1888 // If we have a bitconvert with a resolved type and if the source and
1889 // destination types are the same, then the bitconvert is useless, remove it.
1890 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattner7a0eb912010-03-28 08:38:32 +00001891 N->getExtType(0).isConcrete() &&
1892 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1893 N->getName().empty()) {
1894 N = N->getChild(0);
1895 SimplifyTree(N);
1896 return true;
1897 }
1898
1899 // Walk all children.
1900 bool MadeChange = false;
1901 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1902 TreePatternNode *Child = N->getChild(i);
1903 MadeChange |= SimplifyTree(Child);
1904 N->setChild(i, Child);
1905 }
1906 return MadeChange;
1907}
1908
1909
1910
Chris Lattner6cefb772008-01-05 22:25:12 +00001911/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001912/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001913/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001914bool TreePattern::
1915InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1916 if (NamedNodes.empty())
1917 ComputeNamedNodes();
1918
Chris Lattner6cefb772008-01-05 22:25:12 +00001919 bool MadeChange = true;
1920 while (MadeChange) {
1921 MadeChange = false;
Chris Lattner7a0eb912010-03-28 08:38:32 +00001922 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001923 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner7a0eb912010-03-28 08:38:32 +00001924 MadeChange |= SimplifyTree(Trees[i]);
1925 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001926
1927 // If there are constraints on our named nodes, apply them.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001928 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattner2cacec52010-03-15 06:00:16 +00001929 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1930 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001931
Chris Lattner2cacec52010-03-15 06:00:16 +00001932 // If we have input named node types, propagate their types to the named
1933 // values here.
1934 if (InNamedTypes) {
1935 // FIXME: Should be error?
1936 assert(InNamedTypes->count(I->getKey()) &&
1937 "Named node in output pattern but not input pattern?");
1938
1939 const SmallVectorImpl<TreePatternNode*> &InNodes =
1940 InNamedTypes->find(I->getKey())->second;
1941
1942 // The input types should be fully resolved by now.
1943 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1944 // If this node is a register class, and it is the root of the pattern
1945 // then we're mapping something onto an input register. We allow
1946 // changing the type of the input register in this case. This allows
1947 // us to match things like:
1948 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1949 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001950 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00001951 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
1952 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner2cacec52010-03-15 06:00:16 +00001953 continue;
1954 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001955
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001956 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001957 InNodes[0]->getNumTypes() == 1 &&
1958 "FIXME: cannot name multiple result nodes yet");
1959 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1960 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001961 }
1962 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001963
Chris Lattner2cacec52010-03-15 06:00:16 +00001964 // If there are multiple nodes with the same name, they must all have the
1965 // same type.
1966 if (I->second.size() > 1) {
1967 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001968 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001969 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001970 "FIXME: cannot name multiple result nodes yet");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001971
Chris Lattnerd7349192010-03-19 21:37:09 +00001972 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1973 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001974 }
1975 }
1976 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001977 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001978
Chris Lattner6cefb772008-01-05 22:25:12 +00001979 bool HasUnresolvedTypes = false;
1980 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1981 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1982 return !HasUnresolvedTypes;
1983}
1984
Daniel Dunbar1a551802009-07-03 00:10:29 +00001985void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001986 OS << getRecord()->getName();
1987 if (!Args.empty()) {
1988 OS << "(" << Args[0];
1989 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1990 OS << ", " << Args[i];
1991 OS << ")";
1992 }
1993 OS << ": ";
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001994
Chris Lattner6cefb772008-01-05 22:25:12 +00001995 if (Trees.size() > 1)
1996 OS << "[\n";
1997 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1998 OS << "\t";
1999 Trees[i]->print(OS);
2000 OS << "\n";
2001 }
2002
2003 if (Trees.size() > 1)
2004 OS << "]\n";
2005}
2006
Daniel Dunbar1a551802009-07-03 00:10:29 +00002007void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00002008
2009//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00002010// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00002011//
2012
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002013CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner67db8832010-12-13 00:23:57 +00002014 Records(R), Target(R) {
2015
Dale Johannesen49de9822009-02-05 01:49:45 +00002016 Intrinsics = LoadIntrinsics(Records, false);
2017 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00002018 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00002019 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00002020 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002021 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00002022 ParseDefaultOperands();
2023 ParseInstructions();
2024 ParsePatterns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002025
Chris Lattner6cefb772008-01-05 22:25:12 +00002026 // Generate variants. For example, commutative patterns can match
2027 // multiple ways. Add them to PatternsToMatch as well.
2028 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00002029
2030 // Infer instruction flags. For example, we can detect loads,
2031 // stores, and side effects in many cases by examining an
2032 // instruction's pattern.
2033 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00002034}
2035
Chris Lattnerfe718932008-01-06 01:10:31 +00002036CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002037 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002038 E = PatternFragments.end(); I != E; ++I)
2039 delete I->second;
2040}
2041
2042
Chris Lattnerfe718932008-01-06 01:10:31 +00002043Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00002044 Record *N = Records.getDef(Name);
2045 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002046 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00002047 exit(1);
2048 }
2049 return N;
2050}
2051
2052// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00002053void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002054 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2055 while (!Nodes.empty()) {
2056 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2057 Nodes.pop_back();
2058 }
2059
Jim Grosbachda4231f2009-03-26 16:17:51 +00002060 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00002061 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2062 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2063 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2064}
2065
2066/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2067/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002068void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002069 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2070 while (!Xforms.empty()) {
2071 Record *XFormNode = Xforms.back();
2072 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +00002073 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00002074 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002075
2076 Xforms.pop_back();
2077 }
2078}
2079
Chris Lattnerfe718932008-01-06 01:10:31 +00002080void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002081 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2082 while (!AMs.empty()) {
2083 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2084 AMs.pop_back();
2085 }
2086}
2087
2088
2089/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2090/// file, building up the PatternFragments map. After we've collected them all,
2091/// inline fragments together as necessary, so that there are no references left
2092/// inside a pattern fragment to a pattern fragment.
2093///
Chris Lattnerfe718932008-01-06 01:10:31 +00002094void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002095 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002096
Chris Lattnerdc32f982008-01-05 22:43:57 +00002097 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002098 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00002099 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattner6cefb772008-01-05 22:25:12 +00002100 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2101 PatternFragments[Fragments[i]] = P;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002102
Chris Lattnerdc32f982008-01-05 22:43:57 +00002103 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00002104 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002105 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002106
Chris Lattnerdc32f982008-01-05 22:43:57 +00002107 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00002108 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002109
Chris Lattner6cefb772008-01-05 22:25:12 +00002110 // Parse the operands list.
David Greene05bce0b2011-07-29 22:43:06 +00002111 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2112 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00002113 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00002114 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00002115 if (!OpsOp ||
2116 (OpsOp->getDef()->getName() != "ops" &&
2117 OpsOp->getDef()->getName() != "outs" &&
2118 OpsOp->getDef()->getName() != "ins"))
2119 P->error("Operands list should start with '(ops ... '!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002120
2121 // Copy over the arguments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002122 Args.clear();
2123 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
David Greene05bce0b2011-07-29 22:43:06 +00002124 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
2125 static_cast<DefInit*>(OpsList->getArg(j))->
Chris Lattner6cefb772008-01-05 22:25:12 +00002126 getDef()->getName() != "node")
2127 P->error("Operands list should all be 'node' values.");
2128 if (OpsList->getArgName(j).empty())
2129 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002130 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00002131 P->error("'" + OpsList->getArgName(j) +
2132 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002133 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00002134 Args.push_back(OpsList->getArgName(j));
2135 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002136
Chris Lattnerdc32f982008-01-05 22:43:57 +00002137 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00002138 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00002139 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002140
Chris Lattnerdc32f982008-01-05 22:43:57 +00002141 // If there is a code init for this fragment, keep track of the fact that
2142 // this fragment uses it.
Chris Lattner54379062011-04-17 21:38:24 +00002143 TreePredicateFn PredFn(P);
2144 if (!PredFn.isAlwaysTrue())
2145 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002146
Chris Lattner6cefb772008-01-05 22:25:12 +00002147 // If there is a node transformation corresponding to this, keep track of
2148 // it.
2149 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2150 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2151 P->getOnlyTree()->setTransformFn(Transform);
2152 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002153
Chris Lattner6cefb772008-01-05 22:25:12 +00002154 // Now that we've parsed all of the tree fragments, do a closure on them so
2155 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00002156 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2157 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00002158 ThePat->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002159
Chris Lattner6cefb772008-01-05 22:25:12 +00002160 // Infer as many types as possible. Don't worry about it if we don't infer
2161 // all of them, some may depend on the inputs of the pattern.
2162 try {
2163 ThePat->InferAllTypes();
2164 } catch (...) {
2165 // If this pattern fragment is not supported by this target (no types can
2166 // satisfy its constraints), just ignore it. If the bogus pattern is
2167 // actually used by instructions, the type consistency error will be
2168 // reported there.
2169 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002170
Chris Lattner6cefb772008-01-05 22:25:12 +00002171 // If debugging, print out the pattern fragment result.
2172 DEBUG(ThePat->dump());
2173 }
2174}
2175
Chris Lattnerfe718932008-01-06 01:10:31 +00002176void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002177 std::vector<Record*> DefaultOps[2];
2178 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
2179 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
2180
2181 // Find some SDNode.
2182 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greene05bce0b2011-07-29 22:43:06 +00002183 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002184
Chris Lattner6cefb772008-01-05 22:25:12 +00002185 for (unsigned iter = 0; iter != 2; ++iter) {
2186 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00002187 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002188
Chris Lattner6cefb772008-01-05 22:25:12 +00002189 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2190 // SomeSDnode so that we can parse this.
David Greene05bce0b2011-07-29 22:43:06 +00002191 std::vector<std::pair<Init*, std::string> > Ops;
Chris Lattner6cefb772008-01-05 22:25:12 +00002192 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2193 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2194 DefaultInfo->getArgName(op)));
David Greene05bce0b2011-07-29 22:43:06 +00002195 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002196
Chris Lattner6cefb772008-01-05 22:25:12 +00002197 // Create a TreePattern to parse this.
2198 TreePattern P(DefaultOps[iter][i], DI, false, *this);
2199 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2200
2201 // Copy the operands over into a DAGDefaultOperand.
2202 DAGDefaultOperand DefaultOpInfo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002203
Chris Lattner6cefb772008-01-05 22:25:12 +00002204 TreePatternNode *T = P.getTree(0);
2205 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2206 TreePatternNode *TPN = T->getChild(op);
2207 while (TPN->ApplyTypeConstraints(P, false))
2208 /* Resolve all types */;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002209
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002210 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002211 if (iter == 0)
2212 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00002213 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00002214 else
2215 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00002216 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002217 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002218 DefaultOpInfo.DefaultOps.push_back(TPN);
2219 }
2220
2221 // Insert it into the DefaultOperands map so we can find it later.
2222 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
2223 }
2224 }
2225}
2226
2227/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2228/// instruction input. Return true if this is a real use.
2229static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002230 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002231 // No name -> not interesting.
2232 if (Pat->getName().empty()) {
2233 if (Pat->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00002234 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00002235 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2236 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner6cefb772008-01-05 22:25:12 +00002237 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002238 }
2239 return false;
2240 }
2241
2242 Record *Rec;
2243 if (Pat->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00002244 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002245 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2246 Rec = DI->getDef();
2247 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00002248 Rec = Pat->getOperator();
2249 }
2250
2251 // SRCVALUE nodes are ignored.
2252 if (Rec->getName() == "srcvalue")
2253 return false;
2254
2255 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2256 if (!Slot) {
2257 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00002258 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00002259 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00002260 Record *SlotRec;
2261 if (Slot->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00002262 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattner53d09bd2010-02-23 05:59:10 +00002263 } else {
2264 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2265 SlotRec = Slot->getOperator();
2266 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002267
Chris Lattner53d09bd2010-02-23 05:59:10 +00002268 // Ensure that the inputs agree if we've already seen this input.
2269 if (Rec != SlotRec)
2270 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00002271 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00002272 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00002273 return true;
2274}
2275
2276/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2277/// part of "I", the instruction), computing the set of inputs and outputs of
2278/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00002279void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00002280FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2281 std::map<std::string, TreePatternNode*> &InstInputs,
2282 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner6cefb772008-01-05 22:25:12 +00002283 std::vector<Record*> &InstImpResults) {
2284 if (Pat->isLeaf()) {
Chris Lattneracfb70f2010-04-20 06:30:25 +00002285 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002286 if (!isUse && Pat->getTransformFn())
2287 I->error("Cannot specify a transform function for a non-input value!");
2288 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002289 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002290
Chris Lattner84aa60b2010-02-17 06:53:36 +00002291 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002292 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2293 TreePatternNode *Dest = Pat->getChild(i);
2294 if (!Dest->isLeaf())
2295 I->error("implicitly defined value should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002296
David Greene05bce0b2011-07-29 22:43:06 +00002297 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002298 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2299 I->error("implicitly defined value should be a register!");
2300 InstImpResults.push_back(Val->getDef());
2301 }
2302 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002303 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002304
Chris Lattner84aa60b2010-02-17 06:53:36 +00002305 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002306 // If this is not a set, verify that the children nodes are not void typed,
2307 // and recurse.
2308 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002309 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002310 I->error("Cannot have void nodes inside of patterns!");
2311 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002312 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002313 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002314
Chris Lattner6cefb772008-01-05 22:25:12 +00002315 // If this is a non-leaf node with no children, treat it basically as if
2316 // it were a leaf. This handles nodes like (imm).
Chris Lattneracfb70f2010-04-20 06:30:25 +00002317 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002318
Chris Lattner6cefb772008-01-05 22:25:12 +00002319 if (!isUse && Pat->getTransformFn())
2320 I->error("Cannot specify a transform function for a non-input value!");
2321 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002322 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002323
Chris Lattner6cefb772008-01-05 22:25:12 +00002324 // Otherwise, this is a set, validate and collect instruction results.
2325 if (Pat->getNumChildren() == 0)
2326 I->error("set requires operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002327
Chris Lattner6cefb772008-01-05 22:25:12 +00002328 if (Pat->getTransformFn())
2329 I->error("Cannot specify a transform function on a set node!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002330
Chris Lattner6cefb772008-01-05 22:25:12 +00002331 // Check the set destinations.
2332 unsigned NumDests = Pat->getNumChildren()-1;
2333 for (unsigned i = 0; i != NumDests; ++i) {
2334 TreePatternNode *Dest = Pat->getChild(i);
2335 if (!Dest->isLeaf())
2336 I->error("set destination should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002337
David Greene05bce0b2011-07-29 22:43:06 +00002338 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002339 if (!Val)
2340 I->error("set destination should be a register!");
2341
2342 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Owen Andersonbea6f612011-06-27 21:06:21 +00002343 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002344 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002345 if (Dest->getName().empty())
2346 I->error("set destination must have a name!");
2347 if (InstResults.count(Dest->getName()))
2348 I->error("cannot set '" + Dest->getName() +"' multiple times");
2349 InstResults[Dest->getName()] = Dest;
2350 } else if (Val->getDef()->isSubClassOf("Register")) {
2351 InstImpResults.push_back(Val->getDef());
2352 } else {
2353 I->error("set destination should be a register!");
2354 }
2355 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002356
Chris Lattner6cefb772008-01-05 22:25:12 +00002357 // Verify and collect info from the computation.
2358 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattneracfb70f2010-04-20 06:30:25 +00002359 InstInputs, InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002360}
2361
Dan Gohmanee4fa192008-04-03 00:02:49 +00002362//===----------------------------------------------------------------------===//
2363// Instruction Analysis
2364//===----------------------------------------------------------------------===//
2365
2366class InstAnalyzer {
2367 const CodeGenDAGPatterns &CDP;
2368 bool &mayStore;
2369 bool &mayLoad;
Evan Cheng0f040a22011-03-15 05:09:26 +00002370 bool &IsBitcast;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002371 bool &HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002372 bool &IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002373public:
2374 InstAnalyzer(const CodeGenDAGPatterns &cdp,
Evan Cheng0f040a22011-03-15 05:09:26 +00002375 bool &maystore, bool &mayload, bool &isbc, bool &hse, bool &isv)
2376 : CDP(cdp), mayStore(maystore), mayLoad(mayload), IsBitcast(isbc),
2377 HasSideEffects(hse), IsVariadic(isv) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002378 }
2379
2380 /// Analyze - Analyze the specified instruction, returning true if the
2381 /// instruction had a pattern.
2382 bool Analyze(Record *InstRecord) {
2383 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2384 if (Pattern == 0) {
2385 HasSideEffects = 1;
2386 return false; // No pattern.
2387 }
2388
2389 // FIXME: Assume only the first tree is the pattern. The others are clobber
2390 // nodes.
2391 AnalyzeNode(Pattern->getTree(0));
2392 return true;
2393 }
2394
2395private:
Evan Cheng0f040a22011-03-15 05:09:26 +00002396 bool IsNodeBitcast(const TreePatternNode *N) const {
2397 if (HasSideEffects || mayLoad || mayStore || IsVariadic)
2398 return false;
2399
2400 if (N->getNumChildren() != 2)
2401 return false;
2402
2403 const TreePatternNode *N0 = N->getChild(0);
David Greene05bce0b2011-07-29 22:43:06 +00002404 if (!N0->isLeaf() || !dynamic_cast<DefInit*>(N0->getLeafValue()))
Evan Cheng0f040a22011-03-15 05:09:26 +00002405 return false;
2406
2407 const TreePatternNode *N1 = N->getChild(1);
2408 if (N1->isLeaf())
2409 return false;
2410 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2411 return false;
2412
2413 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2414 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2415 return false;
2416 return OpInfo.getEnumName() == "ISD::BITCAST";
2417 }
2418
Dan Gohmanee4fa192008-04-03 00:02:49 +00002419 void AnalyzeNode(const TreePatternNode *N) {
2420 if (N->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00002421 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002422 Record *LeafRec = DI->getDef();
2423 // Handle ComplexPattern leaves.
2424 if (LeafRec->isSubClassOf("ComplexPattern")) {
2425 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2426 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2427 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2428 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2429 }
2430 }
2431 return;
2432 }
2433
2434 // Analyze children.
2435 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2436 AnalyzeNode(N->getChild(i));
2437
2438 // Ignore set nodes, which are not SDNodes.
Evan Cheng0f040a22011-03-15 05:09:26 +00002439 if (N->getOperator()->getName() == "set") {
2440 IsBitcast = IsNodeBitcast(N);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002441 return;
Evan Cheng0f040a22011-03-15 05:09:26 +00002442 }
Dan Gohmanee4fa192008-04-03 00:02:49 +00002443
2444 // Get information about the SDNode for the operator.
2445 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2446
2447 // Notice properties of the node.
2448 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2449 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2450 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
Chris Lattner1e506312010-03-19 05:34:15 +00002451 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002452
2453 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2454 // If this is an intrinsic, analyze it.
2455 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2456 mayLoad = true;// These may load memory.
2457
Dan Gohman7365c092010-08-05 23:36:21 +00002458 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002459 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2460
Dan Gohman7365c092010-08-05 23:36:21 +00002461 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002462 // WriteMem intrinsics can have other strange effects.
2463 HasSideEffects = true;
2464 }
2465 }
2466
2467};
2468
2469static void InferFromPattern(const CodeGenInstruction &Inst,
2470 bool &MayStore, bool &MayLoad,
Evan Cheng0f040a22011-03-15 05:09:26 +00002471 bool &IsBitcast,
Chris Lattner1e506312010-03-19 05:34:15 +00002472 bool &HasSideEffects, bool &IsVariadic,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002473 const CodeGenDAGPatterns &CDP) {
Evan Cheng0f040a22011-03-15 05:09:26 +00002474 MayStore = MayLoad = IsBitcast = HasSideEffects = IsVariadic = false;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002475
2476 bool HadPattern =
Evan Cheng0f040a22011-03-15 05:09:26 +00002477 InstAnalyzer(CDP, MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic)
Chris Lattner1e506312010-03-19 05:34:15 +00002478 .Analyze(Inst.TheDef);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002479
2480 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2481 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2482 // If we decided that this is a store from the pattern, then the .td file
2483 // entry is redundant.
2484 if (MayStore)
2485 fprintf(stderr,
2486 "Warning: mayStore flag explicitly set on instruction '%s'"
2487 " but flag already inferred from pattern.\n",
2488 Inst.TheDef->getName().c_str());
2489 MayStore = true;
2490 }
2491
2492 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2493 // If we decided that this is a load from the pattern, then the .td file
2494 // entry is redundant.
2495 if (MayLoad)
2496 fprintf(stderr,
2497 "Warning: mayLoad flag explicitly set on instruction '%s'"
2498 " but flag already inferred from pattern.\n",
2499 Inst.TheDef->getName().c_str());
2500 MayLoad = true;
2501 }
2502
2503 if (Inst.neverHasSideEffects) {
2504 if (HadPattern)
2505 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2506 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2507 HasSideEffects = false;
2508 }
2509
2510 if (Inst.hasSideEffects) {
2511 if (HasSideEffects)
2512 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2513 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2514 HasSideEffects = true;
2515 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002516
Chris Lattnerc240bb02010-11-01 04:03:32 +00002517 if (Inst.Operands.isVariadic)
Chris Lattner1e506312010-03-19 05:34:15 +00002518 IsVariadic = true; // Can warn if we want.
Dan Gohmanee4fa192008-04-03 00:02:49 +00002519}
2520
Chris Lattner6cefb772008-01-05 22:25:12 +00002521/// ParseInstructions - Parse all of the instructions, inlining and resolving
2522/// any fragments involved. This populates the Instructions list with fully
2523/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002524void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002525 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002526
Chris Lattner6cefb772008-01-05 22:25:12 +00002527 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00002528 ListInit *LI = 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002529
David Greene05bce0b2011-07-29 22:43:06 +00002530 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
Chris Lattner6cefb772008-01-05 22:25:12 +00002531 LI = Instrs[i]->getValueAsListInit("Pattern");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002532
Chris Lattner6cefb772008-01-05 22:25:12 +00002533 // If there is no pattern, only collect minimal information about the
2534 // instruction for its operand list. We have to assume that there is one
2535 // result, as we have no detailed info.
2536 if (!LI || LI->getSize() == 0) {
2537 std::vector<Record*> Results;
2538 std::vector<Record*> Operands;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002539
Chris Lattnerf30187a2010-03-19 00:07:20 +00002540 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002541
Chris Lattnerc240bb02010-11-01 04:03:32 +00002542 if (InstInfo.Operands.size() != 0) {
2543 if (InstInfo.Operands.NumDefs == 0) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002544 // These produce no results
Chris Lattnerc240bb02010-11-01 04:03:32 +00002545 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2546 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002547 } else {
2548 // Assume the first operand is the result.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002549 Results.push_back(InstInfo.Operands[0].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002550
Chris Lattner6cefb772008-01-05 22:25:12 +00002551 // The rest are inputs.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002552 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2553 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002554 }
2555 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002556
Chris Lattner6cefb772008-01-05 22:25:12 +00002557 // Create and insert the instruction.
2558 std::vector<Record*> ImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002559 Instructions.insert(std::make_pair(Instrs[i],
Chris Lattner62bcec82010-04-20 06:28:43 +00002560 DAGInstruction(0, Results, Operands, ImpResults)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002561 continue; // no pattern.
2562 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002563
Chris Lattner6cefb772008-01-05 22:25:12 +00002564 // Parse the instruction.
2565 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2566 // Inline pattern fragments into it.
2567 I->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002568
Chris Lattner6cefb772008-01-05 22:25:12 +00002569 // Infer as many types as possible. If we cannot infer all of them, we can
2570 // never do anything with this instruction pattern: report it to the user.
2571 if (!I->InferAllTypes())
2572 I->error("Could not infer all types in pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002573
2574 // InstInputs - Keep track of all of the inputs of the instruction, along
Chris Lattner6cefb772008-01-05 22:25:12 +00002575 // with the record they are declared as.
2576 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002577
Chris Lattner6cefb772008-01-05 22:25:12 +00002578 // InstResults - Keep track of all the virtual registers that are 'set'
2579 // in the instruction, including what reg class they are.
2580 std::map<std::string, TreePatternNode*> InstResults;
2581
Chris Lattner6cefb772008-01-05 22:25:12 +00002582 std::vector<Record*> InstImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002583
Chris Lattner6cefb772008-01-05 22:25:12 +00002584 // Verify that the top-level forms in the instruction are of void type, and
2585 // fill in the InstResults map.
2586 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2587 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002588 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002589 I->error("Top-level forms in instruction pattern should have"
2590 " void types");
2591
2592 // Find inputs and outputs, and verify the structure of the uses/defs.
2593 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002594 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002595 }
2596
2597 // Now that we have inputs and outputs of the pattern, inspect the operands
2598 // list for the instruction. This determines the order that operands are
2599 // added to the machine instruction the node corresponds to.
2600 unsigned NumResults = InstResults.size();
2601
2602 // Parse the operands list from the (ops) list, validating it.
2603 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002604 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002605
2606 // Check that all of the results occur first in the list.
2607 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002608 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002609 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerc240bb02010-11-01 04:03:32 +00002610 if (i == CGI.Operands.size())
Chris Lattner6cefb772008-01-05 22:25:12 +00002611 I->error("'" + InstResults.begin()->first +
2612 "' set but does not appear in operand list!");
Chris Lattnerc240bb02010-11-01 04:03:32 +00002613 const std::string &OpName = CGI.Operands[i].Name;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002614
Chris Lattner6cefb772008-01-05 22:25:12 +00002615 // Check that it exists in InstResults.
2616 TreePatternNode *RNode = InstResults[OpName];
2617 if (RNode == 0)
2618 I->error("Operand $" + OpName + " does not exist in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002619
Chris Lattner6cefb772008-01-05 22:25:12 +00002620 if (i == 0)
2621 Res0Node = RNode;
David Greene05bce0b2011-07-29 22:43:06 +00002622 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner6cefb772008-01-05 22:25:12 +00002623 if (R == 0)
2624 I->error("Operand $" + OpName + " should be a set destination: all "
2625 "outputs must occur before inputs in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002626
Chris Lattnerc240bb02010-11-01 04:03:32 +00002627 if (CGI.Operands[i].Rec != R)
Chris Lattner6cefb772008-01-05 22:25:12 +00002628 I->error("Operand $" + OpName + " class mismatch!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002629
Chris Lattner6cefb772008-01-05 22:25:12 +00002630 // Remember the return type.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002631 Results.push_back(CGI.Operands[i].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002632
Chris Lattner6cefb772008-01-05 22:25:12 +00002633 // Okay, this one checks out.
2634 InstResults.erase(OpName);
2635 }
2636
2637 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2638 // the copy while we're checking the inputs.
2639 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2640
2641 std::vector<TreePatternNode*> ResultNodeOperands;
2642 std::vector<Record*> Operands;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002643 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2644 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner6cefb772008-01-05 22:25:12 +00002645 const std::string &OpName = Op.Name;
2646 if (OpName.empty())
2647 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2648
2649 if (!InstInputsCheck.count(OpName)) {
2650 // If this is an predicate operand or optional def operand with an
2651 // DefaultOps set filled in, we can ignore this. When we codegen it,
2652 // we will do so as always executed.
2653 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2654 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2655 // Does it have a non-empty DefaultOps field? If so, ignore this
2656 // operand.
2657 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2658 continue;
2659 }
2660 I->error("Operand $" + OpName +
2661 " does not appear in the instruction pattern");
2662 }
2663 TreePatternNode *InVal = InstInputsCheck[OpName];
2664 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002665
Chris Lattner6cefb772008-01-05 22:25:12 +00002666 if (InVal->isLeaf() &&
David Greene05bce0b2011-07-29 22:43:06 +00002667 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2668 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Chris Lattner6cefb772008-01-05 22:25:12 +00002669 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2670 I->error("Operand $" + OpName + "'s register class disagrees"
2671 " between the operand and pattern");
2672 }
2673 Operands.push_back(Op.Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002674
Chris Lattner6cefb772008-01-05 22:25:12 +00002675 // Construct the result for the dest-pattern operand list.
2676 TreePatternNode *OpNode = InVal->clone();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002677
Chris Lattner6cefb772008-01-05 22:25:12 +00002678 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002679 OpNode->clearPredicateFns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002680
Chris Lattner6cefb772008-01-05 22:25:12 +00002681 // Promote the xform function to be an explicit node if set.
2682 if (Record *Xform = OpNode->getTransformFn()) {
2683 OpNode->setTransformFn(0);
2684 std::vector<TreePatternNode*> Children;
2685 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002686 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002687 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002688
Chris Lattner6cefb772008-01-05 22:25:12 +00002689 ResultNodeOperands.push_back(OpNode);
2690 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002691
Chris Lattner6cefb772008-01-05 22:25:12 +00002692 if (!InstInputsCheck.empty())
2693 I->error("Input operand $" + InstInputsCheck.begin()->first +
2694 " occurs in pattern but not in operands list!");
2695
2696 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002697 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2698 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002699 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002700 for (unsigned i = 0; i != NumResults; ++i)
2701 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002702
2703 // Create and insert the instruction.
Chris Lattneracfb70f2010-04-20 06:30:25 +00002704 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner62bcec82010-04-20 06:28:43 +00002705 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002706 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2707
2708 // Use a temporary tree pattern to infer all types and make sure that the
2709 // constructed result is correct. This depends on the instruction already
2710 // being inserted into the Instructions map.
2711 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002712 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002713
2714 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2715 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002716
Chris Lattner6cefb772008-01-05 22:25:12 +00002717 DEBUG(I->dump());
2718 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002719
Chris Lattner6cefb772008-01-05 22:25:12 +00002720 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002721 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2722 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002723 E = Instructions.end(); II != E; ++II) {
2724 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002725 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002726 if (I == 0) continue; // No pattern.
2727
2728 // FIXME: Assume only the first tree is the pattern. The others are clobber
2729 // nodes.
2730 TreePatternNode *Pattern = I->getTree(0);
2731 TreePatternNode *SrcPattern;
2732 if (Pattern->getOperator()->getName() == "set") {
2733 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2734 } else{
2735 // Not a set (store or something?)
2736 SrcPattern = Pattern;
2737 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002738
Chris Lattner6cefb772008-01-05 22:25:12 +00002739 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002740 AddPatternToMatch(I,
Jim Grosbach997759a2010-12-07 23:05:49 +00002741 PatternToMatch(Instr,
2742 Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002743 SrcPattern,
2744 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002745 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002746 Instr->getValueAsInt("AddedComplexity"),
2747 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002748 }
2749}
2750
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002751
2752typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2753
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002754static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002755 std::map<std::string, NameRecord> &Names,
2756 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002757 if (!P->getName().empty()) {
2758 NameRecord &Rec = Names[P->getName()];
2759 // If this is the first instance of the name, remember the node.
2760 if (Rec.second++ == 0)
2761 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002762 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002763 PatternTop->error("repetition of value: $" + P->getName() +
2764 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002765 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002766
Chris Lattner967d54a2010-02-23 06:35:45 +00002767 if (!P->isLeaf()) {
2768 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002769 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002770 }
2771}
2772
Chris Lattner25b6f912010-02-23 06:16:51 +00002773void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2774 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002775 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002776 std::string Reason;
2777 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002778 Pattern->error("Pattern can never match: " + Reason);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002779
Chris Lattner405f1252010-03-01 22:29:19 +00002780 // If the source pattern's root is a complex pattern, that complex pattern
2781 // must specify the nodes it can potentially match.
2782 if (const ComplexPattern *CP =
2783 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2784 if (CP->getRootNodes().empty())
2785 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2786 " could match");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002787
2788
Chris Lattner967d54a2010-02-23 06:35:45 +00002789 // Find all of the named values in the input and output, ensure they have the
2790 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002791 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002792 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2793 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002794
2795 // Scan all of the named values in the destination pattern, rejecting them if
2796 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002797 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002798 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002799 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002800 Pattern->error("Pattern has input without matching name in output: $" +
2801 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002802 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002803
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002804 // Scan all of the named values in the source pattern, rejecting them if the
2805 // name isn't used in the dest, and isn't used to tie two values together.
2806 for (std::map<std::string, NameRecord>::iterator
2807 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2808 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2809 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002810
Chris Lattner25b6f912010-02-23 06:16:51 +00002811 PatternsToMatch.push_back(PTM);
2812}
2813
2814
Dan Gohmanee4fa192008-04-03 00:02:49 +00002815
2816void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002817 const std::vector<const CodeGenInstruction*> &Instructions =
2818 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002819 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2820 CodeGenInstruction &InstInfo =
2821 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002822 // Determine properties of the instruction from its pattern.
Evan Cheng0f040a22011-03-15 05:09:26 +00002823 bool MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic;
2824 InferFromPattern(InstInfo, MayStore, MayLoad, IsBitcast,
2825 HasSideEffects, IsVariadic, *this);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002826 InstInfo.mayStore = MayStore;
2827 InstInfo.mayLoad = MayLoad;
Evan Cheng0f040a22011-03-15 05:09:26 +00002828 InstInfo.isBitcast = IsBitcast;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002829 InstInfo.hasSideEffects = HasSideEffects;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002830 InstInfo.Operands.isVariadic = IsVariadic;
Jakob Stoklund Olesenccbe6032011-10-14 01:00:49 +00002831
2832 // Sanity checks.
2833 if (InstInfo.isReMaterializable && InstInfo.hasSideEffects)
2834 throw TGError(InstInfo.TheDef->getLoc(), "The instruction " +
2835 InstInfo.TheDef->getName() +
2836 " is rematerializable AND has unmodeled side effects?");
Dan Gohmanee4fa192008-04-03 00:02:49 +00002837 }
2838}
2839
Chris Lattner2cacec52010-03-15 06:00:16 +00002840/// Given a pattern result with an unresolved type, see if we can find one
2841/// instruction with an unresolved result type. Force this result type to an
2842/// arbitrary element if it's possible types to converge results.
2843static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2844 if (N->isLeaf())
2845 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002846
Chris Lattner2cacec52010-03-15 06:00:16 +00002847 // Analyze children.
2848 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2849 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2850 return true;
2851
2852 if (!N->getOperator()->isSubClassOf("Instruction"))
2853 return false;
2854
2855 // If this type is already concrete or completely unknown we can't do
2856 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00002857 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2858 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2859 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002860
Chris Lattnerd7349192010-03-19 21:37:09 +00002861 // Otherwise, force its type to the first possibility (an arbitrary choice).
2862 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2863 return true;
2864 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002865
Chris Lattnerd7349192010-03-19 21:37:09 +00002866 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00002867}
2868
Chris Lattnerfe718932008-01-06 01:10:31 +00002869void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002870 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2871
2872 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002873 Record *CurPattern = Patterns[i];
David Greene05bce0b2011-07-29 22:43:06 +00002874 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Chris Lattner310adf12010-03-27 02:53:27 +00002875 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002876
2877 // Inline pattern fragments into it.
2878 Pattern->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002879
David Greene05bce0b2011-07-29 22:43:06 +00002880 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00002881 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002882
Chris Lattner6cefb772008-01-05 22:25:12 +00002883 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00002884 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002885
Chris Lattner6cefb772008-01-05 22:25:12 +00002886 // Inline pattern fragments into it.
2887 Result->InlinePatternFragments();
2888
2889 if (Result->getNumTrees() != 1)
2890 Result->error("Cannot handle instructions producing instructions "
2891 "with temporaries yet!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002892
Chris Lattner6cefb772008-01-05 22:25:12 +00002893 bool IterateInference;
2894 bool InferredAllPatternTypes, InferredAllResultTypes;
2895 do {
2896 // Infer as many types as possible. If we cannot infer all of them, we
2897 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002898 InferredAllPatternTypes =
2899 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002900
Chris Lattner6cefb772008-01-05 22:25:12 +00002901 // Infer as many types as possible. If we cannot infer all of them, we
2902 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002903 InferredAllResultTypes =
2904 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002905
Chris Lattner6c6ba362010-03-18 23:15:10 +00002906 IterateInference = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002907
Chris Lattner6cefb772008-01-05 22:25:12 +00002908 // Apply the type of the result to the source pattern. This helps us
2909 // resolve cases where the input type is known to be a pointer type (which
2910 // is considered resolved), but the result knows it needs to be 32- or
2911 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00002912 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2913 Pattern->getTree(0)->getNumTypes());
2914 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00002915 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002916 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002917 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002918 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002919 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002920
Chris Lattner2cacec52010-03-15 06:00:16 +00002921 // If our iteration has converged and the input pattern's types are fully
2922 // resolved but the result pattern is not fully resolved, we may have a
2923 // situation where we have two instructions in the result pattern and
2924 // the instructions require a common register class, but don't care about
2925 // what actual MVT is used. This is actually a bug in our modelling:
2926 // output patterns should have register classes, not MVTs.
2927 //
2928 // In any case, to handle this, we just go through and disambiguate some
2929 // arbitrary types to the result pattern's nodes.
2930 if (!IterateInference && InferredAllPatternTypes &&
2931 !InferredAllResultTypes)
2932 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2933 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002934 } while (IterateInference);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002935
Chris Lattner6cefb772008-01-05 22:25:12 +00002936 // Verify that we inferred enough types that we can do something with the
2937 // pattern and result. If these fire the user has to add type casts.
2938 if (!InferredAllPatternTypes)
2939 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002940 if (!InferredAllResultTypes) {
2941 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002942 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002943 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002944
Chris Lattner6cefb772008-01-05 22:25:12 +00002945 // Validate that the input pattern is correct.
2946 std::map<std::string, TreePatternNode*> InstInputs;
2947 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00002948 std::vector<Record*> InstImpResults;
2949 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2950 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2951 InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002952 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002953
2954 // Promote the xform function to be an explicit node if set.
2955 TreePatternNode *DstPattern = Result->getOnlyTree();
2956 std::vector<TreePatternNode*> ResultNodeOperands;
2957 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2958 TreePatternNode *OpNode = DstPattern->getChild(ii);
2959 if (Record *Xform = OpNode->getTransformFn()) {
2960 OpNode->setTransformFn(0);
2961 std::vector<TreePatternNode*> Children;
2962 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002963 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002964 }
2965 ResultNodeOperands.push_back(OpNode);
2966 }
2967 DstPattern = Result->getOnlyTree();
2968 if (!DstPattern->isLeaf())
2969 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00002970 ResultNodeOperands,
2971 DstPattern->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002972
Chris Lattnerd7349192010-03-19 21:37:09 +00002973 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2974 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002975
Chris Lattner6cefb772008-01-05 22:25:12 +00002976 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2977 Temp.InferAllTypes();
2978
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002979
Chris Lattner25b6f912010-02-23 06:16:51 +00002980 AddPatternToMatch(Pattern,
Jim Grosbach997759a2010-12-07 23:05:49 +00002981 PatternToMatch(CurPattern,
2982 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerd7349192010-03-19 21:37:09 +00002983 Pattern->getTree(0),
2984 Temp.getOnlyTree(), InstImpResults,
2985 CurPattern->getValueAsInt("AddedComplexity"),
2986 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002987 }
2988}
2989
2990/// CombineChildVariants - Given a bunch of permutations of each child of the
2991/// 'operator' node, put them together in all possible ways.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002992static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00002993 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2994 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002995 CodeGenDAGPatterns &CDP,
2996 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002997 // Make sure that each operand has at least one variant to choose from.
2998 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2999 if (ChildVariants[i].empty())
3000 return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003001
Chris Lattner6cefb772008-01-05 22:25:12 +00003002 // The end result is an all-pairs construction of the resultant pattern.
3003 std::vector<unsigned> Idxs;
3004 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00003005 bool NotDone;
3006 do {
3007#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00003008 DEBUG(if (!Idxs.empty()) {
3009 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3010 for (unsigned i = 0; i < Idxs.size(); ++i) {
3011 errs() << Idxs[i] << " ";
3012 }
3013 errs() << "]\n";
3014 });
Scott Michel327d0652008-03-05 17:49:05 +00003015#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00003016 // Create the variant and add it to the output list.
3017 std::vector<TreePatternNode*> NewChildren;
3018 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3019 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00003020 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3021 Orig->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003022
Chris Lattner6cefb772008-01-05 22:25:12 +00003023 // Copy over properties.
3024 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00003025 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00003026 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00003027 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3028 R->setType(i, Orig->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003029
Scott Michel327d0652008-03-05 17:49:05 +00003030 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00003031 std::string ErrString;
3032 if (!R->canPatternMatch(ErrString, CDP)) {
3033 delete R;
3034 } else {
3035 bool AlreadyExists = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003036
Chris Lattner6cefb772008-01-05 22:25:12 +00003037 // Scan to see if this pattern has already been emitted. We can get
3038 // duplication due to things like commuting:
3039 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3040 // which are the same pattern. Ignore the dups.
3041 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003042 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003043 AlreadyExists = true;
3044 break;
3045 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003046
Chris Lattner6cefb772008-01-05 22:25:12 +00003047 if (AlreadyExists)
3048 delete R;
3049 else
3050 OutVariants.push_back(R);
3051 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003052
Scott Michel327d0652008-03-05 17:49:05 +00003053 // Increment indices to the next permutation by incrementing the
3054 // indicies from last index backward, e.g., generate the sequence
3055 // [0, 0], [0, 1], [1, 0], [1, 1].
3056 int IdxsIdx;
3057 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3058 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3059 Idxs[IdxsIdx] = 0;
3060 else
Chris Lattner6cefb772008-01-05 22:25:12 +00003061 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00003062 }
Scott Michel327d0652008-03-05 17:49:05 +00003063 NotDone = (IdxsIdx >= 0);
3064 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00003065}
3066
3067/// CombineChildVariants - A helper function for binary operators.
3068///
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003069static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00003070 const std::vector<TreePatternNode*> &LHS,
3071 const std::vector<TreePatternNode*> &RHS,
3072 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003073 CodeGenDAGPatterns &CDP,
3074 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003075 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3076 ChildVariants.push_back(LHS);
3077 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00003078 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003079}
Chris Lattner6cefb772008-01-05 22:25:12 +00003080
3081
3082static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3083 std::vector<TreePatternNode *> &Children) {
3084 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3085 Record *Operator = N->getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003086
Chris Lattner6cefb772008-01-05 22:25:12 +00003087 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00003088 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00003089 N->getTransformFn()) {
3090 Children.push_back(N);
3091 return;
3092 }
3093
3094 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3095 Children.push_back(N->getChild(0));
3096 else
3097 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3098
3099 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3100 Children.push_back(N->getChild(1));
3101 else
3102 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3103}
3104
3105/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3106/// the (potentially recursive) pattern by using algebraic laws.
3107///
3108static void GenerateVariantsOf(TreePatternNode *N,
3109 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003110 CodeGenDAGPatterns &CDP,
3111 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003112 // We cannot permute leaves.
3113 if (N->isLeaf()) {
3114 OutVariants.push_back(N);
3115 return;
3116 }
3117
3118 // Look up interesting info about the node.
3119 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3120
Jim Grosbachda4231f2009-03-26 16:17:51 +00003121 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00003122 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003123 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00003124 std::vector<TreePatternNode*> MaximalChildren;
3125 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3126
3127 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3128 // permutations.
3129 if (MaximalChildren.size() == 3) {
3130 // Find the variants of all of our maximal children.
3131 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003132 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3133 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3134 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003135
Chris Lattner6cefb772008-01-05 22:25:12 +00003136 // There are only two ways we can permute the tree:
3137 // (A op B) op C and A op (B op C)
3138 // Within these forms, we can also permute A/B/C.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003139
Chris Lattner6cefb772008-01-05 22:25:12 +00003140 // Generate legal pair permutations of A/B/C.
3141 std::vector<TreePatternNode*> ABVariants;
3142 std::vector<TreePatternNode*> BAVariants;
3143 std::vector<TreePatternNode*> ACVariants;
3144 std::vector<TreePatternNode*> CAVariants;
3145 std::vector<TreePatternNode*> BCVariants;
3146 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003147 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3148 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3149 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3150 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3151 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3152 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003153
3154 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00003155 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3156 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3157 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3158 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3159 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3160 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003161
3162 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00003163 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3164 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3165 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3166 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3167 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3168 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003169 return;
3170 }
3171 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003172
Chris Lattner6cefb772008-01-05 22:25:12 +00003173 // Compute permutations of all children.
3174 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3175 ChildVariants.resize(N->getNumChildren());
3176 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003177 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003178
3179 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00003180 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003181
3182 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003183 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3184 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3185 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3186 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003187 // Don't count children which are actually register references.
3188 unsigned NC = 0;
3189 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3190 TreePatternNode *Child = N->getChild(i);
3191 if (Child->isLeaf())
David Greene05bce0b2011-07-29 22:43:06 +00003192 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003193 Record *RR = DI->getDef();
3194 if (RR->isSubClassOf("Register"))
3195 continue;
3196 }
3197 NC++;
3198 }
3199 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003200 if (isCommIntrinsic) {
3201 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3202 // operands are the commutative operands, and there might be more operands
3203 // after those.
3204 assert(NC >= 3 &&
3205 "Commutative intrinsic should have at least 3 childrean!");
3206 std::vector<std::vector<TreePatternNode*> > Variants;
3207 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3208 Variants.push_back(ChildVariants[2]);
3209 Variants.push_back(ChildVariants[1]);
3210 for (unsigned i = 3; i != NC; ++i)
3211 Variants.push_back(ChildVariants[i]);
3212 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3213 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00003214 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00003215 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003216 }
3217}
3218
3219
3220// GenerateVariants - Generate variants. For example, commutative patterns can
3221// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00003222void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00003223 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003224
Chris Lattner6cefb772008-01-05 22:25:12 +00003225 // Loop over all of the patterns we've collected, checking to see if we can
3226 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00003227 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00003228 // the .td file having to contain tons of variants of instructions.
3229 //
3230 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3231 // intentionally do not reconsider these. Any variants of added patterns have
3232 // already been added.
3233 //
3234 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00003235 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00003236 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00003237 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00003238 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00003239 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00003240 DEBUG(errs() << "\n");
Jim Grosbachbb168242010-10-08 18:13:57 +00003241 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3242 DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003243
3244 assert(!Variants.empty() && "Must create at least original variant!");
3245 Variants.erase(Variants.begin()); // Remove the original pattern.
3246
3247 if (Variants.empty()) // No variants for this pattern.
3248 continue;
3249
Chris Lattner569f1212009-08-23 04:44:11 +00003250 DEBUG(errs() << "FOUND VARIANTS OF: ";
3251 PatternsToMatch[i].getSrcPattern()->dump();
3252 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003253
3254 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3255 TreePatternNode *Variant = Variants[v];
3256
Chris Lattner569f1212009-08-23 04:44:11 +00003257 DEBUG(errs() << " VAR#" << v << ": ";
3258 Variant->dump();
3259 errs() << "\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003260
Chris Lattner6cefb772008-01-05 22:25:12 +00003261 // Scan to see if an instruction or explicit pattern already matches this.
3262 bool AlreadyExists = false;
3263 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00003264 // Skip if the top level predicates do not match.
3265 if (PatternsToMatch[i].getPredicates() !=
3266 PatternsToMatch[p].getPredicates())
3267 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00003268 // Check to see if this variant already exists.
Jim Grosbachbb168242010-10-08 18:13:57 +00003269 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3270 DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00003271 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003272 AlreadyExists = true;
3273 break;
3274 }
3275 }
3276 // If we already have it, ignore the variant.
3277 if (AlreadyExists) continue;
3278
3279 // Otherwise, add it to the list of patterns we have.
3280 PatternsToMatch.
Jim Grosbach997759a2010-12-07 23:05:49 +00003281 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3282 PatternsToMatch[i].getPredicates(),
Chris Lattner6cefb772008-01-05 22:25:12 +00003283 Variant, PatternsToMatch[i].getDstPattern(),
3284 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00003285 PatternsToMatch[i].getAddedComplexity(),
3286 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003287 }
3288
Chris Lattner569f1212009-08-23 04:44:11 +00003289 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003290 }
3291}
3292