blob: 5e1d3ae9dc455aee267f3287eaf891ea4a6029d7 [file] [log] [blame]
Chris Lattnerfe718932008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner6cefb772008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfe718932008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner6cefb772008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner93c7e412008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000016#include "Record.h"
17#include "llvm/ADT/StringExtras.h"
Chris Lattner2cacec52010-03-15 06:00:16 +000018#include "llvm/ADT/STLExtras.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include "llvm/Support/Debug.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000020#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000021#include <algorithm>
Chris Lattner6cefb772008-01-05 22:25:12 +000022using namespace llvm;
23
24//===----------------------------------------------------------------------===//
Chris Lattner2cacec52010-03-15 06:00:16 +000025// EEVT::TypeSet Implementation
26//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +000027
Owen Anderson825b72b2009-08-11 20:47:22 +000028static inline bool isInteger(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000029 return EVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000030}
Owen Anderson825b72b2009-08-11 20:47:22 +000031static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000032 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000033}
Owen Anderson825b72b2009-08-11 20:47:22 +000034static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000035 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000036}
Chris Lattner774ce292010-03-19 17:41:26 +000037static inline bool isScalar(MVT::SimpleValueType VT) {
38 return !EVT(VT).isVector();
39}
Duncan Sands83ec4b62008-06-06 12:08:01 +000040
Chris Lattner2cacec52010-03-15 06:00:16 +000041EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
42 if (VT == MVT::iAny)
43 EnforceInteger(TP);
44 else if (VT == MVT::fAny)
45 EnforceFloatingPoint(TP);
46 else if (VT == MVT::vAny)
47 EnforceVector(TP);
48 else {
49 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
50 VT == MVT::iPTRAny) && "Not a concrete type!");
51 TypeVec.push_back(VT);
52 }
Chris Lattner6cefb772008-01-05 22:25:12 +000053}
54
Chris Lattner2cacec52010-03-15 06:00:16 +000055
56EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
57 assert(!VTList.empty() && "empty list?");
58 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000059
Chris Lattner2cacec52010-03-15 06:00:16 +000060 if (!VTList.empty())
61 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
62 VTList[0] != MVT::fAny);
Jim Grosbachfbadcd02010-12-21 16:16:00 +000063
Chris Lattner0d7952e2010-03-27 20:32:26 +000064 // Verify no duplicates.
Chris Lattner2cacec52010-03-15 06:00:16 +000065 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner0d7952e2010-03-27 20:32:26 +000066 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner6cefb772008-01-05 22:25:12 +000067}
68
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000069/// FillWithPossibleTypes - Set to all legal types and return true, only valid
70/// on completely unknown type sets.
Chris Lattner774ce292010-03-19 17:41:26 +000071bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
72 bool (*Pred)(MVT::SimpleValueType),
73 const char *PredicateName) {
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000074 assert(isCompletelyUnknown());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000075 const std::vector<MVT::SimpleValueType> &LegalTypes =
Chris Lattner774ce292010-03-19 17:41:26 +000076 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +000077
Chris Lattner774ce292010-03-19 17:41:26 +000078 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
79 if (Pred == 0 || Pred(LegalTypes[i]))
80 TypeVec.push_back(LegalTypes[i]);
81
82 // If we have nothing that matches the predicate, bail out.
83 if (TypeVec.empty())
84 TP.error("Type inference contradiction found, no " +
Jim Grosbachfbadcd02010-12-21 16:16:00 +000085 std::string(PredicateName) + " types found");
Chris Lattner774ce292010-03-19 17:41:26 +000086 // No need to sort with one element.
87 if (TypeVec.size() == 1) return true;
88
89 // Remove duplicates.
90 array_pod_sort(TypeVec.begin(), TypeVec.end());
91 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000092
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000093 return true;
94}
Chris Lattner2cacec52010-03-15 06:00:16 +000095
96/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
97/// integer value type.
98bool EEVT::TypeSet::hasIntegerTypes() const {
99 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
100 if (isInteger(TypeVec[i]))
101 return true;
102 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000103}
Chris Lattner2cacec52010-03-15 06:00:16 +0000104
105/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
106/// a floating point value type.
107bool EEVT::TypeSet::hasFloatingPointTypes() const {
108 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109 if (isFloatingPoint(TypeVec[i]))
110 return true;
111 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000112}
Chris Lattner2cacec52010-03-15 06:00:16 +0000113
114/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
115/// value type.
116bool EEVT::TypeSet::hasVectorTypes() const {
117 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118 if (isVector(TypeVec[i]))
119 return true;
120 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +0000121}
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000122
Chris Lattner2cacec52010-03-15 06:00:16 +0000123
124std::string EEVT::TypeSet::getName() const {
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000125 if (TypeVec.empty()) return "<empty>";
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000126
Chris Lattner2cacec52010-03-15 06:00:16 +0000127 std::string Result;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000128
Chris Lattner2cacec52010-03-15 06:00:16 +0000129 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
130 std::string VTName = llvm::getEnumName(TypeVec[i]);
131 // Strip off MVT:: prefix if present.
132 if (VTName.substr(0,5) == "MVT::")
133 VTName = VTName.substr(5);
134 if (i) Result += ':';
135 Result += VTName;
136 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000137
Chris Lattner2cacec52010-03-15 06:00:16 +0000138 if (TypeVec.size() == 1)
139 return Result;
140 return "{" + Result + "}";
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000141}
Chris Lattner2cacec52010-03-15 06:00:16 +0000142
143/// MergeInTypeInfo - This merges in type information from the specified
144/// argument. If 'this' changes, it returns true. If the two types are
145/// contradictory (e.g. merge f32 into i32) then this throws an exception.
146bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
147 if (InVT.isCompletelyUnknown() || *this == InVT)
148 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000149
Chris Lattner2cacec52010-03-15 06:00:16 +0000150 if (isCompletelyUnknown()) {
151 *this = InVT;
152 return true;
153 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000154
Chris Lattner2cacec52010-03-15 06:00:16 +0000155 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000156
Chris Lattner2cacec52010-03-15 06:00:16 +0000157 // Handle the abstract cases, seeing if we can resolve them better.
158 switch (TypeVec[0]) {
159 default: break;
160 case MVT::iPTR:
161 case MVT::iPTRAny:
162 if (InVT.hasIntegerTypes()) {
163 EEVT::TypeSet InCopy(InVT);
164 InCopy.EnforceInteger(TP);
165 InCopy.EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000166
Chris Lattner2cacec52010-03-15 06:00:16 +0000167 if (InCopy.isConcrete()) {
168 // If the RHS has one integer type, upgrade iPTR to i32.
169 TypeVec[0] = InVT.TypeVec[0];
170 return true;
171 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000172
Chris Lattner2cacec52010-03-15 06:00:16 +0000173 // If the input has multiple scalar integers, this doesn't add any info.
174 if (!InCopy.isCompletelyUnknown())
175 return false;
176 }
177 break;
178 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000179
Chris Lattner2cacec52010-03-15 06:00:16 +0000180 // If the input constraint is iAny/iPTR and this is an integer type list,
181 // remove non-integer types from the list.
182 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
183 hasIntegerTypes()) {
184 bool MadeChange = EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000185
Chris Lattner2cacec52010-03-15 06:00:16 +0000186 // If we're merging in iPTR/iPTRAny and the node currently has a list of
187 // multiple different integer types, replace them with a single iPTR.
188 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
189 TypeVec.size() != 1) {
190 TypeVec.resize(1);
191 TypeVec[0] = InVT.TypeVec[0];
192 MadeChange = true;
193 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000194
Chris Lattner2cacec52010-03-15 06:00:16 +0000195 return MadeChange;
196 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000197
Chris Lattner2cacec52010-03-15 06:00:16 +0000198 // If this is a type list and the RHS is a typelist as well, eliminate entries
199 // from this list that aren't in the other one.
200 bool MadeChange = false;
201 TypeSet InputSet(*this);
202
203 for (unsigned i = 0; i != TypeVec.size(); ++i) {
204 bool InInVT = false;
205 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
206 if (TypeVec[i] == InVT.TypeVec[j]) {
207 InInVT = true;
208 break;
209 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000210
Chris Lattner2cacec52010-03-15 06:00:16 +0000211 if (InInVT) continue;
212 TypeVec.erase(TypeVec.begin()+i--);
213 MadeChange = true;
214 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000215
Chris Lattner2cacec52010-03-15 06:00:16 +0000216 // If we removed all of our types, we have a type contradiction.
217 if (!TypeVec.empty())
218 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000219
Chris Lattner2cacec52010-03-15 06:00:16 +0000220 // FIXME: Really want an SMLoc here!
221 TP.error("Type inference contradiction found, merging '" +
222 InVT.getName() + "' into '" + InputSet.getName() + "'");
223 return true; // unreachable
224}
225
226/// EnforceInteger - Remove all non-integer types from this set.
227bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000228 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000229 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000230 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattner2cacec52010-03-15 06:00:16 +0000231 if (!hasFloatingPointTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000232 return false;
233
234 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000235
Chris Lattner2cacec52010-03-15 06:00:16 +0000236 // Filter out all the fp types.
237 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000238 if (!isInteger(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000239 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000240
Chris Lattner2cacec52010-03-15 06:00:16 +0000241 if (TypeVec.empty())
242 TP.error("Type inference contradiction found, '" +
243 InputSet.getName() + "' needs to be integer");
Chris Lattner774ce292010-03-19 17:41:26 +0000244 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000245}
246
247/// EnforceFloatingPoint - Remove all integer types from this set.
248bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000249 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000250 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000251 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
252
Chris Lattner2cacec52010-03-15 06:00:16 +0000253 if (!hasIntegerTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000254 return false;
255
256 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000257
Chris Lattner2cacec52010-03-15 06:00:16 +0000258 // Filter out all the fp types.
259 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000260 if (!isFloatingPoint(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000261 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000262
Chris Lattner2cacec52010-03-15 06:00:16 +0000263 if (TypeVec.empty())
264 TP.error("Type inference contradiction found, '" +
265 InputSet.getName() + "' needs to be floating point");
Chris Lattner774ce292010-03-19 17:41:26 +0000266 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000267}
268
269/// EnforceScalar - Remove all vector types from this.
270bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000271 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000272 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000273 return FillWithPossibleTypes(TP, isScalar, "scalar");
274
Chris Lattner2cacec52010-03-15 06:00:16 +0000275 if (!hasVectorTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000276 return false;
277
278 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000279
Chris Lattner2cacec52010-03-15 06:00:16 +0000280 // Filter out all the vector types.
281 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000282 if (!isScalar(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000283 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000284
Chris Lattner2cacec52010-03-15 06:00:16 +0000285 if (TypeVec.empty())
286 TP.error("Type inference contradiction found, '" +
287 InputSet.getName() + "' needs to be scalar");
Chris Lattner774ce292010-03-19 17:41:26 +0000288 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000289}
290
291/// EnforceVector - Remove all vector types from this.
292bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Chris Lattner774ce292010-03-19 17:41:26 +0000293 // If we know nothing, then get the full set.
294 if (TypeVec.empty())
295 return FillWithPossibleTypes(TP, isVector, "vector");
296
Chris Lattner2cacec52010-03-15 06:00:16 +0000297 TypeSet InputSet(*this);
298 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000299
Chris Lattner2cacec52010-03-15 06:00:16 +0000300 // Filter out all the scalar types.
301 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000302 if (!isVector(TypeVec[i])) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000303 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner774ce292010-03-19 17:41:26 +0000304 MadeChange = true;
305 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000306
Chris Lattner2cacec52010-03-15 06:00:16 +0000307 if (TypeVec.empty())
308 TP.error("Type inference contradiction found, '" +
309 InputSet.getName() + "' needs to be a vector");
310 return MadeChange;
311}
312
313
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000314
Chris Lattner2cacec52010-03-15 06:00:16 +0000315/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
316/// this an other based on this information.
317bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
318 // Both operands must be integer or FP, but we don't care which.
319 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000320
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000321 if (isCompletelyUnknown())
322 MadeChange = FillWithPossibleTypes(TP);
323
324 if (Other.isCompletelyUnknown())
325 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000326
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000327 // If one side is known to be integer or known to be FP but the other side has
328 // no information, get at least the type integrality info in there.
329 if (!hasFloatingPointTypes())
330 MadeChange |= Other.EnforceInteger(TP);
331 else if (!hasIntegerTypes())
332 MadeChange |= Other.EnforceFloatingPoint(TP);
333 if (!Other.hasFloatingPointTypes())
334 MadeChange |= EnforceInteger(TP);
335 else if (!Other.hasIntegerTypes())
336 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000337
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000338 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
339 "Should have a type list now");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000340
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000341 // If one contains vectors but the other doesn't pull vectors out.
342 if (!hasVectorTypes())
343 MadeChange |= Other.EnforceScalar(TP);
344 if (!hasVectorTypes())
345 MadeChange |= EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000346
Chris Lattner2cacec52010-03-15 06:00:16 +0000347 // This code does not currently handle nodes which have multiple types,
348 // where some types are integer, and some are fp. Assert that this is not
349 // the case.
350 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
351 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
352 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000353
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000354 // Okay, find the smallest type from the current set and remove it from the
355 // largest set.
356 MVT::SimpleValueType Smallest = TypeVec[0];
357 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
358 if (TypeVec[i] < Smallest)
359 Smallest = TypeVec[i];
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000360
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000361 // If this is the only type in the large set, the constraint can never be
362 // satisfied.
363 if (Other.TypeVec.size() == 1 && Other.TypeVec[0] == Smallest)
364 TP.error("Type inference contradiction found, '" +
365 Other.getName() + "' has nothing larger than '" + getName() +"'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000366
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000367 SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
368 std::find(Other.TypeVec.begin(), Other.TypeVec.end(), Smallest);
369 if (TVI != Other.TypeVec.end()) {
370 Other.TypeVec.erase(TVI);
371 MadeChange = true;
372 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000373
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000374 // Okay, find the largest type in the Other set and remove it from the
375 // current set.
376 MVT::SimpleValueType Largest = Other.TypeVec[0];
377 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
378 if (Other.TypeVec[i] > Largest)
379 Largest = Other.TypeVec[i];
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000380
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000381 // If this is the only type in the small set, the constraint can never be
382 // satisfied.
383 if (TypeVec.size() == 1 && TypeVec[0] == Largest)
384 TP.error("Type inference contradiction found, '" +
385 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000386
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000387 TVI = std::find(TypeVec.begin(), TypeVec.end(), Largest);
388 if (TVI != TypeVec.end()) {
389 TypeVec.erase(TVI);
390 MadeChange = true;
391 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000392
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000393 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000394}
395
396/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner66fb9d22010-03-24 00:01:16 +0000397/// whose element is specified by VTOperand.
398bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattner2cacec52010-03-15 06:00:16 +0000399 TreePattern &TP) {
Chris Lattner66fb9d22010-03-24 00:01:16 +0000400 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattner2cacec52010-03-15 06:00:16 +0000401 bool MadeChange = false;
Chris Lattner66fb9d22010-03-24 00:01:16 +0000402 MadeChange |= EnforceVector(TP);
403 MadeChange |= VTOperand.EnforceScalar(TP);
404
405 // If we know the vector type, it forces the scalar to agree.
406 if (isConcrete()) {
407 EVT IVT = getConcrete();
408 IVT = IVT.getVectorElementType();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000409 return MadeChange |
Chris Lattner66fb9d22010-03-24 00:01:16 +0000410 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
411 }
412
413 // If the scalar type is known, filter out vector types whose element types
414 // disagree.
415 if (!VTOperand.isConcrete())
416 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000417
Chris Lattner66fb9d22010-03-24 00:01:16 +0000418 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000419
Chris Lattner66fb9d22010-03-24 00:01:16 +0000420 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000421
Chris Lattner66fb9d22010-03-24 00:01:16 +0000422 // Filter out all the types which don't have the right element type.
423 for (unsigned i = 0; i != TypeVec.size(); ++i) {
424 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
425 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000426 TypeVec.erase(TypeVec.begin()+i--);
427 MadeChange = true;
428 }
Chris Lattner66fb9d22010-03-24 00:01:16 +0000429 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000430
Chris Lattner2cacec52010-03-15 06:00:16 +0000431 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
432 TP.error("Type inference contradiction found, forcing '" +
433 InputSet.getName() + "' to have a vector element");
434 return MadeChange;
435}
436
David Greene60322692011-01-24 20:53:18 +0000437/// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
438/// vector type specified by VTOperand.
439bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
440 TreePattern &TP) {
441 // "This" must be a vector and "VTOperand" must be a vector.
442 bool MadeChange = false;
443 MadeChange |= EnforceVector(TP);
444 MadeChange |= VTOperand.EnforceVector(TP);
445
446 // "This" must be larger than "VTOperand."
447 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
448
449 // If we know the vector type, it forces the scalar types to agree.
450 if (isConcrete()) {
451 EVT IVT = getConcrete();
452 IVT = IVT.getVectorElementType();
453
454 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
455 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
456 } else if (VTOperand.isConcrete()) {
457 EVT IVT = VTOperand.getConcrete();
458 IVT = IVT.getVectorElementType();
459
460 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
461 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
462 }
463
464 return MadeChange;
465}
466
Chris Lattner2cacec52010-03-15 06:00:16 +0000467//===----------------------------------------------------------------------===//
468// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000469
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000470bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
471 return LHS->getID() < RHS->getID();
472}
Scott Michel327d0652008-03-05 17:49:05 +0000473
474/// Dependent variable map for CodeGenDAGPattern variant generation
475typedef std::map<std::string, int> DepVarMap;
476
477/// Const iterator shorthand for DepVarMap
478typedef DepVarMap::const_iterator DepVarMap_citer;
479
480namespace {
481void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
482 if (N->isLeaf()) {
483 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
484 DepMap[N->getName()]++;
485 }
486 } else {
487 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
488 FindDepVarsOf(N->getChild(i), DepMap);
489 }
490}
491
492//! Find dependent variables within child patterns
493/*!
494 */
495void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
496 DepVarMap depcounts;
497 FindDepVarsOf(N, depcounts);
498 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
499 if (i->second > 1) { // std::pair<std::string, int>
500 DepVars.insert(i->first);
501 }
502 }
503}
504
505//! Dump the dependent variable set:
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000506#ifndef NDEBUG
Scott Michel327d0652008-03-05 17:49:05 +0000507void DumpDepVars(MultipleUseVarSet &DepVars) {
508 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000509 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000510 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000511 DEBUG(errs() << "[ ");
Jim Grosbachbb168242010-10-08 18:13:57 +0000512 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
513 e = DepVars.end(); i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000514 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000515 }
Chris Lattner569f1212009-08-23 04:44:11 +0000516 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000517 }
518}
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000519#endif
520
Scott Michel327d0652008-03-05 17:49:05 +0000521}
522
Chris Lattner6cefb772008-01-05 22:25:12 +0000523//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000524// PatternToMatch implementation
525//
526
Chris Lattner48e86db2010-03-29 01:40:38 +0000527
528/// getPatternSize - Return the 'size' of this pattern. We want to match large
529/// patterns before small ones. This is used to determine the size of a
530/// pattern.
531static unsigned getPatternSize(const TreePatternNode *P,
532 const CodeGenDAGPatterns &CGP) {
533 unsigned Size = 3; // The node itself.
534 // If the root node is a ConstantSDNode, increases its size.
535 // e.g. (set R32:$dst, 0).
536 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
537 Size += 2;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000538
Chris Lattner48e86db2010-03-29 01:40:38 +0000539 // FIXME: This is a hack to statically increase the priority of patterns
540 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
541 // Later we can allow complexity / cost for each pattern to be (optionally)
542 // specified. To get best possible pattern match we'll need to dynamically
543 // calculate the complexity of all patterns a dag can potentially map to.
544 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
545 if (AM)
546 Size += AM->getNumOperands() * 3;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000547
Chris Lattner48e86db2010-03-29 01:40:38 +0000548 // If this node has some predicate function that must match, it adds to the
549 // complexity of this node.
550 if (!P->getPredicateFns().empty())
551 ++Size;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000552
Chris Lattner48e86db2010-03-29 01:40:38 +0000553 // Count children in the count if they are also nodes.
554 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
555 TreePatternNode *Child = P->getChild(i);
556 if (!Child->isLeaf() && Child->getNumTypes() &&
557 Child->getType(0) != MVT::Other)
558 Size += getPatternSize(Child, CGP);
559 else if (Child->isLeaf()) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000560 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000561 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
562 else if (Child->getComplexPatternInfo(CGP))
563 Size += getPatternSize(Child, CGP);
564 else if (!Child->getPredicateFns().empty())
565 ++Size;
566 }
567 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000568
Chris Lattner48e86db2010-03-29 01:40:38 +0000569 return Size;
570}
571
572/// Compute the complexity metric for the input pattern. This roughly
573/// corresponds to the number of nodes that are covered.
574unsigned PatternToMatch::
575getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
576 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
577}
578
579
Dan Gohman22bb3112008-08-22 00:20:26 +0000580/// getPredicateCheck - Return a single string containing all of this
581/// pattern's predicates concatenated with "&&" operators.
582///
583std::string PatternToMatch::getPredicateCheck() const {
584 std::string PredicateCheck;
585 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
586 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
587 Record *Def = Pred->getDef();
588 if (!Def->isSubClassOf("Predicate")) {
589#ifndef NDEBUG
590 Def->dump();
591#endif
592 assert(0 && "Unknown predicate type!");
593 }
594 if (!PredicateCheck.empty())
595 PredicateCheck += " && ";
596 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
597 }
598 }
599
600 return PredicateCheck;
601}
602
603//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000604// SDTypeConstraint implementation
605//
606
607SDTypeConstraint::SDTypeConstraint(Record *R) {
608 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000609
Chris Lattner6cefb772008-01-05 22:25:12 +0000610 if (R->isSubClassOf("SDTCisVT")) {
611 ConstraintType = SDTCisVT;
612 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerc8122612010-03-28 06:04:39 +0000613 if (x.SDTCisVT_Info.VT == MVT::isVoid)
614 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000615
Chris Lattner6cefb772008-01-05 22:25:12 +0000616 } else if (R->isSubClassOf("SDTCisPtrTy")) {
617 ConstraintType = SDTCisPtrTy;
618 } else if (R->isSubClassOf("SDTCisInt")) {
619 ConstraintType = SDTCisInt;
620 } else if (R->isSubClassOf("SDTCisFP")) {
621 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000622 } else if (R->isSubClassOf("SDTCisVec")) {
623 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000624 } else if (R->isSubClassOf("SDTCisSameAs")) {
625 ConstraintType = SDTCisSameAs;
626 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
627 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
628 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000629 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000630 R->getValueAsInt("OtherOperandNum");
631 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
632 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000633 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000634 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000635 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
636 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000637 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene60322692011-01-24 20:53:18 +0000638 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
639 ConstraintType = SDTCisSubVecOfVec;
640 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
641 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000642 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000643 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000644 exit(1);
645 }
646}
647
648/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000649/// N, and the result number in ResNo.
650static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
651 const SDNodeInfo &NodeInfo,
652 unsigned &ResNo) {
653 unsigned NumResults = NodeInfo.getNumResults();
654 if (OpNo < NumResults) {
655 ResNo = OpNo;
656 return N;
657 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000658
Chris Lattner2e68a022010-03-19 21:56:21 +0000659 OpNo -= NumResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000660
Chris Lattner2e68a022010-03-19 21:56:21 +0000661 if (OpNo >= N->getNumChildren()) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000662 errs() << "Invalid operand number in type constraint "
Chris Lattner2e68a022010-03-19 21:56:21 +0000663 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000664 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000665 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000666 exit(1);
667 }
668
Chris Lattner2e68a022010-03-19 21:56:21 +0000669 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000670}
671
672/// ApplyTypeConstraint - Given a node in a pattern, apply this type
673/// constraint to the nodes operands. This returns true if it makes a
674/// change, false otherwise. If a type contradiction is found, throw an
675/// exception.
676bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
677 const SDNodeInfo &NodeInfo,
678 TreePattern &TP) const {
Chris Lattner2e68a022010-03-19 21:56:21 +0000679 unsigned ResNo = 0; // The result number being referenced.
680 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000681
Chris Lattner6cefb772008-01-05 22:25:12 +0000682 switch (ConstraintType) {
683 default: assert(0 && "Unknown constraint type!");
684 case SDTCisVT:
685 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000686 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000687 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000688 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000689 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000690 case SDTCisInt:
691 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000692 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000693 case SDTCisFP:
694 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000695 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000696 case SDTCisVec:
697 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000698 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000699 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000700 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000701 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000702 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000703 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
704 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000705 }
706 case SDTCisVTSmallerThanOp: {
707 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
708 // have an integer type that is smaller than the VT.
709 if (!NodeToApply->isLeaf() ||
710 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
711 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
712 ->isSubClassOf("ValueType"))
713 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000714 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000715 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000716
Chris Lattnercc878302010-03-24 00:06:46 +0000717 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000718
Chris Lattner2e68a022010-03-19 21:56:21 +0000719 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000720 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000721 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
722 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000723
Chris Lattnercc878302010-03-24 00:06:46 +0000724 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000725 }
726 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000727 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000728 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000729 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
730 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000731 return NodeToApply->getExtType(ResNo).
732 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000733 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000734 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000735 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000736 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000737 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
738 VResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000739
Chris Lattner66fb9d22010-03-24 00:01:16 +0000740 // Filter vector types out of VecOperand that don't have the right element
741 // type.
742 return VecOperand->getExtType(VResNo).
743 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000744 }
David Greene60322692011-01-24 20:53:18 +0000745 case SDTCisSubVecOfVec: {
746 unsigned VResNo = 0;
747 TreePatternNode *BigVecOperand =
748 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
749 VResNo);
750
751 // Filter vector types out of BigVecOperand that don't have the
752 // right subvector type.
753 return BigVecOperand->getExtType(VResNo).
754 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
755 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000756 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000757 return false;
758}
759
760//===----------------------------------------------------------------------===//
761// SDNodeInfo implementation
762//
763SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
764 EnumName = R->getValueAsString("Opcode");
765 SDClassName = R->getValueAsString("SDClass");
766 Record *TypeProfile = R->getValueAsDef("TypeProfile");
767 NumResults = TypeProfile->getValueAsInt("NumResults");
768 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000769
Chris Lattner6cefb772008-01-05 22:25:12 +0000770 // Parse the properties.
771 Properties = 0;
772 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
773 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
774 if (PropList[i]->getName() == "SDNPCommutative") {
775 Properties |= 1 << SDNPCommutative;
776 } else if (PropList[i]->getName() == "SDNPAssociative") {
777 Properties |= 1 << SDNPAssociative;
778 } else if (PropList[i]->getName() == "SDNPHasChain") {
779 Properties |= 1 << SDNPHasChain;
Chris Lattner036609b2010-12-23 18:28:41 +0000780 } else if (PropList[i]->getName() == "SDNPOutGlue") {
781 Properties |= 1 << SDNPOutGlue;
782 } else if (PropList[i]->getName() == "SDNPInGlue") {
783 Properties |= 1 << SDNPInGlue;
784 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
785 Properties |= 1 << SDNPOptInGlue;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000786 } else if (PropList[i]->getName() == "SDNPMayStore") {
787 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000788 } else if (PropList[i]->getName() == "SDNPMayLoad") {
789 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000790 } else if (PropList[i]->getName() == "SDNPSideEffect") {
791 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000792 } else if (PropList[i]->getName() == "SDNPMemOperand") {
793 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000794 } else if (PropList[i]->getName() == "SDNPVariadic") {
795 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000796 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000797 errs() << "Unknown SD Node property '" << PropList[i]->getName()
798 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000799 exit(1);
800 }
801 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000802
803
Chris Lattner6cefb772008-01-05 22:25:12 +0000804 // Parse the type constraints.
805 std::vector<Record*> ConstraintList =
806 TypeProfile->getValueAsListOfDefs("Constraints");
807 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
808}
809
Chris Lattner22579812010-02-28 00:22:30 +0000810/// getKnownType - If the type constraints on this node imply a fixed type
811/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000812/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +0000813MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +0000814 unsigned NumResults = getNumResults();
815 assert(NumResults <= 1 &&
816 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +0000817 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000818
Chris Lattner22579812010-02-28 00:22:30 +0000819 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
820 // Make sure that this applies to the correct node result.
821 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
822 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000823
Chris Lattner22579812010-02-28 00:22:30 +0000824 switch (TypeConstraints[i].ConstraintType) {
825 default: break;
826 case SDTypeConstraint::SDTCisVT:
827 return TypeConstraints[i].x.SDTCisVT_Info.VT;
828 case SDTypeConstraint::SDTCisPtrTy:
829 return MVT::iPTR;
830 }
831 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000832 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000833}
834
Chris Lattner6cefb772008-01-05 22:25:12 +0000835//===----------------------------------------------------------------------===//
836// TreePatternNode implementation
837//
838
839TreePatternNode::~TreePatternNode() {
840#if 0 // FIXME: implement refcounted tree nodes!
841 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
842 delete getChild(i);
843#endif
844}
845
Chris Lattnerd7349192010-03-19 21:37:09 +0000846static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
847 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +0000848 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +0000849 return 0; // All return nothing.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000850
Chris Lattner93dc92e2010-03-22 20:56:36 +0000851 if (Operator->isSubClassOf("Intrinsic"))
852 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000853
Chris Lattnerd7349192010-03-19 21:37:09 +0000854 if (Operator->isSubClassOf("SDNode"))
855 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000856
Chris Lattnerd7349192010-03-19 21:37:09 +0000857 if (Operator->isSubClassOf("PatFrag")) {
858 // If we've already parsed this pattern fragment, get it. Otherwise, handle
859 // the forward reference case where one pattern fragment references another
860 // before it is processed.
861 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
862 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000863
Chris Lattnerd7349192010-03-19 21:37:09 +0000864 // Get the result tree.
865 DagInit *Tree = Operator->getValueAsDag("Fragment");
866 Record *Op = 0;
867 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
868 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
869 assert(Op && "Invalid Fragment");
870 return GetNumNodeResults(Op, CDP);
871 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000872
Chris Lattnerd7349192010-03-19 21:37:09 +0000873 if (Operator->isSubClassOf("Instruction")) {
874 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +0000875
876 // FIXME: Should allow access to all the results here.
Chris Lattnerc240bb02010-11-01 04:03:32 +0000877 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000878
Chris Lattner9414ae52010-03-27 20:09:24 +0000879 // Add on one implicit def if it has a resolvable type.
880 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
881 ++NumDefsToAdd;
Chris Lattner0be6fe72010-03-27 19:15:02 +0000882 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +0000883 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000884
Chris Lattnerd7349192010-03-19 21:37:09 +0000885 if (Operator->isSubClassOf("SDNodeXForm"))
886 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000887
Chris Lattnerd7349192010-03-19 21:37:09 +0000888 Operator->dump();
889 errs() << "Unhandled node in GetNumNodeResults\n";
890 exit(1);
891}
892
893void TreePatternNode::print(raw_ostream &OS) const {
894 if (isLeaf())
895 OS << *getLeafValue();
896 else
897 OS << '(' << getOperator()->getName();
898
899 for (unsigned i = 0, e = Types.size(); i != e; ++i)
900 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000901
902 if (!isLeaf()) {
903 if (getNumChildren() != 0) {
904 OS << " ";
905 getChild(0)->print(OS);
906 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
907 OS << ", ";
908 getChild(i)->print(OS);
909 }
910 }
911 OS << ")";
912 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000913
Dan Gohman0540e172008-10-15 06:17:21 +0000914 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
915 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000916 if (TransformFn)
917 OS << "<<X:" << TransformFn->getName() << ">>";
918 if (!getName().empty())
919 OS << ":$" << getName();
920
921}
922void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000923 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000924}
925
Scott Michel327d0652008-03-05 17:49:05 +0000926/// isIsomorphicTo - Return true if this node is recursively
927/// isomorphic to the specified node. For this comparison, the node's
928/// entire state is considered. The assigned name is ignored, since
929/// nodes with differing names are considered isomorphic. However, if
930/// the assigned name is present in the dependent variable set, then
931/// the assigned name is considered significant and the node is
932/// isomorphic if the names match.
933bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
934 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000935 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +0000936 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000937 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000938 getTransformFn() != N->getTransformFn())
939 return false;
940
941 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000942 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
943 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000944 return ((DI->getDef() == NDI->getDef())
945 && (DepVars.find(getName()) == DepVars.end()
946 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000947 }
948 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000949 return getLeafValue() == N->getLeafValue();
950 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000951
Chris Lattner6cefb772008-01-05 22:25:12 +0000952 if (N->getOperator() != getOperator() ||
953 N->getNumChildren() != getNumChildren()) return false;
954 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000955 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000956 return false;
957 return true;
958}
959
960/// clone - Make a copy of this tree and all of its children.
961///
962TreePatternNode *TreePatternNode::clone() const {
963 TreePatternNode *New;
964 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +0000965 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000966 } else {
967 std::vector<TreePatternNode*> CChildren;
968 CChildren.reserve(Children.size());
969 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
970 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +0000971 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000972 }
973 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +0000974 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +0000975 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000976 New->setTransformFn(getTransformFn());
977 return New;
978}
979
Chris Lattner47661322010-02-14 22:22:58 +0000980/// RemoveAllTypes - Recursively strip all the types of this tree.
981void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +0000982 for (unsigned i = 0, e = Types.size(); i != e; ++i)
983 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +0000984 if (isLeaf()) return;
985 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
986 getChild(i)->RemoveAllTypes();
987}
988
989
Chris Lattner6cefb772008-01-05 22:25:12 +0000990/// SubstituteFormalArguments - Replace the formal arguments in this tree
991/// with actual values specified by ArgMap.
992void TreePatternNode::
993SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
994 if (isLeaf()) return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000995
Chris Lattner6cefb772008-01-05 22:25:12 +0000996 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
997 TreePatternNode *Child = getChild(i);
998 if (Child->isLeaf()) {
999 Init *Val = Child->getLeafValue();
1000 if (dynamic_cast<DefInit*>(Val) &&
1001 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
1002 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +00001003 TreePatternNode *NewChild = ArgMap[Child->getName()];
1004 assert(NewChild && "Couldn't find formal argument!");
1005 assert((Child->getPredicateFns().empty() ||
1006 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1007 "Non-empty child predicate clobbered!");
1008 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +00001009 }
1010 } else {
1011 getChild(i)->SubstituteFormalArguments(ArgMap);
1012 }
1013 }
1014}
1015
1016
1017/// InlinePatternFragments - If this pattern refers to any pattern
1018/// fragments, inline them into place, giving us a pattern without any
1019/// PatFrag references.
1020TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1021 if (isLeaf()) return this; // nothing to do.
1022 Record *Op = getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001023
Chris Lattner6cefb772008-01-05 22:25:12 +00001024 if (!Op->isSubClassOf("PatFrag")) {
1025 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00001026 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1027 TreePatternNode *Child = getChild(i);
1028 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1029
1030 assert((Child->getPredicateFns().empty() ||
1031 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1032 "Non-empty child predicate clobbered!");
1033
1034 setChild(i, NewChild);
1035 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001036 return this;
1037 }
1038
1039 // Otherwise, we found a reference to a fragment. First, look up its
1040 // TreePattern record.
1041 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001042
Chris Lattner6cefb772008-01-05 22:25:12 +00001043 // Verify that we are passing the right number of operands.
1044 if (Frag->getNumArgs() != Children.size())
1045 TP.error("'" + Op->getName() + "' fragment requires " +
1046 utostr(Frag->getNumArgs()) + " operands!");
1047
1048 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1049
Dan Gohman0540e172008-10-15 06:17:21 +00001050 std::string Code = Op->getValueAsCode("Predicate");
1051 if (!Code.empty())
1052 FragTree->addPredicateFn("Predicate_"+Op->getName());
1053
Chris Lattner6cefb772008-01-05 22:25:12 +00001054 // Resolve formal arguments to their actual value.
1055 if (Frag->getNumArgs()) {
1056 // Compute the map of formal to actual arguments.
1057 std::map<std::string, TreePatternNode*> ArgMap;
1058 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1059 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001060
Chris Lattner6cefb772008-01-05 22:25:12 +00001061 FragTree->SubstituteFormalArguments(ArgMap);
1062 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001063
Chris Lattner6cefb772008-01-05 22:25:12 +00001064 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001065 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1066 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +00001067
1068 // Transfer in the old predicates.
1069 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1070 FragTree->addPredicateFn(getPredicateFns()[i]);
1071
Chris Lattner6cefb772008-01-05 22:25:12 +00001072 // Get a new copy of this fragment to stitch into here.
1073 //delete this; // FIXME: implement refcounting!
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001074
Chris Lattner2ca698d2008-06-30 03:02:03 +00001075 // The fragment we inlined could have recursive inlining that is needed. See
1076 // if there are any pattern fragments in it and inline them as needed.
1077 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001078}
1079
1080/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +00001081/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +00001082/// references from the register file information, for example.
1083///
Chris Lattnerd7349192010-03-19 21:37:09 +00001084static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1085 bool NotRegisters, TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001086 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +00001087 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00001088 assert(ResNo == 0 && "Regclass ref only has one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001089 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001090 return EEVT::TypeSet(); // Unknown.
1091 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1092 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001093 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001094
Chris Lattner640a3f52010-03-23 23:50:31 +00001095 if (R->isSubClassOf("PatFrag")) {
1096 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001097 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001098 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001099 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001100
Chris Lattner640a3f52010-03-23 23:50:31 +00001101 if (R->isSubClassOf("Register")) {
1102 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001103 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001104 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001105 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001106 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001107 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +00001108
1109 if (R->isSubClassOf("SubRegIndex")) {
1110 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1111 return EEVT::TypeSet();
1112 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001113
Chris Lattner640a3f52010-03-23 23:50:31 +00001114 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1115 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001116 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001117 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001118 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001119
Chris Lattner640a3f52010-03-23 23:50:31 +00001120 if (R->isSubClassOf("ComplexPattern")) {
1121 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001122 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001123 return EEVT::TypeSet(); // Unknown.
1124 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1125 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001126 }
1127 if (R->isSubClassOf("PointerLikeRegClass")) {
1128 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001129 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001130 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001131
Chris Lattner640a3f52010-03-23 23:50:31 +00001132 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1133 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001134 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001135 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001136 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001137
Chris Lattner6cefb772008-01-05 22:25:12 +00001138 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001139 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001140}
1141
Chris Lattnere67bde52008-01-06 05:36:50 +00001142
1143/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1144/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1145const CodeGenIntrinsic *TreePatternNode::
1146getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1147 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1148 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1149 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1150 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001151
1152 unsigned IID =
Chris Lattnere67bde52008-01-06 05:36:50 +00001153 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1154 return &CDP.getIntrinsicInfo(IID);
1155}
1156
Chris Lattner47661322010-02-14 22:22:58 +00001157/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1158/// return the ComplexPattern information, otherwise return null.
1159const ComplexPattern *
1160TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1161 if (!isLeaf()) return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001162
Chris Lattner47661322010-02-14 22:22:58 +00001163 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1164 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1165 return &CGP.getComplexPattern(DI->getDef());
1166 return 0;
1167}
1168
1169/// NodeHasProperty - Return true if this node has the specified property.
1170bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001171 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001172 if (isLeaf()) {
1173 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1174 return CP->hasProperty(Property);
1175 return false;
1176 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001177
Chris Lattner47661322010-02-14 22:22:58 +00001178 Record *Operator = getOperator();
1179 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001180
Chris Lattner47661322010-02-14 22:22:58 +00001181 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1182}
1183
1184
1185
1186
1187/// TreeHasProperty - Return true if any node in this tree has the specified
1188/// property.
1189bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001190 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001191 if (NodeHasProperty(Property, CGP))
1192 return true;
1193 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1194 if (getChild(i)->TreeHasProperty(Property, CGP))
1195 return true;
1196 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001197}
Chris Lattner47661322010-02-14 22:22:58 +00001198
Evan Cheng6bd95672008-06-16 20:29:38 +00001199/// isCommutativeIntrinsic - Return true if the node corresponds to a
1200/// commutative intrinsic.
1201bool
1202TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1203 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1204 return Int->isCommutative;
1205 return false;
1206}
1207
Chris Lattnere67bde52008-01-06 05:36:50 +00001208
Bob Wilson6c01ca92009-01-05 17:23:09 +00001209/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001210/// this node and its children in the tree. This returns true if it makes a
1211/// change, false otherwise. If a type contradiction is found, throw an
1212/// exception.
1213bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001214 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001215 if (isLeaf()) {
1216 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1217 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001218 bool MadeChange = false;
1219 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1220 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1221 NotRegisters, TP), TP);
1222 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001223 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001224
Chris Lattner523f6a52010-02-14 21:10:15 +00001225 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001226 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001227
Chris Lattnerd7349192010-03-19 21:37:09 +00001228 // Int inits are always integers. :)
1229 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001230
Chris Lattnerd7349192010-03-19 21:37:09 +00001231 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001232 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001233
Chris Lattnerd7349192010-03-19 21:37:09 +00001234 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001235 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1236 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001237
Chris Lattner2cacec52010-03-15 06:00:16 +00001238 unsigned Size = EVT(VT).getSizeInBits();
1239 // Make sure that the value is representable for this type.
1240 if (Size >= 32) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001241
Chris Lattner2cacec52010-03-15 06:00:16 +00001242 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1243 if (Val == II->getValue()) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001244
Chris Lattner2cacec52010-03-15 06:00:16 +00001245 // If sign-extended doesn't fit, does it fit as unsigned?
1246 unsigned ValueMask;
1247 unsigned UnsignedVal;
1248 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1249 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001250
Chris Lattner2cacec52010-03-15 06:00:16 +00001251 if ((ValueMask & UnsignedVal) == UnsignedVal)
1252 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001253
Chris Lattner2cacec52010-03-15 06:00:16 +00001254 TP.error("Integer value '" + itostr(II->getValue())+
Chris Lattnerd7349192010-03-19 21:37:09 +00001255 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001256 return MadeChange;
1257 }
1258 return false;
1259 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001260
Chris Lattner6cefb772008-01-05 22:25:12 +00001261 // special handling for set, which isn't really an SDNode.
1262 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001263 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1264 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001265 unsigned NC = getNumChildren();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001266
Chris Lattnerd7349192010-03-19 21:37:09 +00001267 TreePatternNode *SetVal = getChild(NC-1);
1268 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1269
Chris Lattner6cefb772008-01-05 22:25:12 +00001270 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001271 TreePatternNode *Child = getChild(i);
1272 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001273
Chris Lattner6cefb772008-01-05 22:25:12 +00001274 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001275 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1276 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001277 }
1278 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001279 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001280
Chris Lattner310adf12010-03-27 02:53:27 +00001281 if (getOperator()->getName() == "implicit") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001282 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1283
Chris Lattner6cefb772008-01-05 22:25:12 +00001284 bool MadeChange = false;
1285 for (unsigned i = 0; i < getNumChildren(); ++i)
1286 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001287 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001288 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001289
Chris Lattner6eb30122010-02-23 05:51:07 +00001290 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001291 bool MadeChange = false;
1292 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1293 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001294
Chris Lattnerd7349192010-03-19 21:37:09 +00001295 assert(getChild(0)->getNumTypes() == 1 &&
1296 getChild(1)->getNumTypes() == 1 && "Unhandled case");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001297
Chris Lattner2cacec52010-03-15 06:00:16 +00001298 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1299 // what type it gets, so if it didn't get a concrete type just give it the
1300 // first viable type from the reg class.
Chris Lattnerd7349192010-03-19 21:37:09 +00001301 if (!getChild(1)->hasTypeSet(0) &&
1302 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1303 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1304 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001305 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001306 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001307 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001308
Chris Lattner6eb30122010-02-23 05:51:07 +00001309 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001310 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001311
Chris Lattner6cefb772008-01-05 22:25:12 +00001312 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001313 unsigned NumRetVTs = Int->IS.RetVTs.size();
1314 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001315
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001316 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001317 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001318
Chris Lattnerd7349192010-03-19 21:37:09 +00001319 if (getNumChildren() != NumParamVTs + 1)
Chris Lattnere67bde52008-01-06 05:36:50 +00001320 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001321 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001322 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001323
1324 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001325 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001326
Chris Lattnerd7349192010-03-19 21:37:09 +00001327 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1328 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001329
Chris Lattnerd7349192010-03-19 21:37:09 +00001330 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1331 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1332 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001333 }
1334 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001335 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001336
Chris Lattner6eb30122010-02-23 05:51:07 +00001337 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001338 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001339
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001340 // Check that the number of operands is sane. Negative operands -> varargs.
1341 if (NI.getNumOperands() >= 0 &&
1342 getNumChildren() != (unsigned)NI.getNumOperands())
1343 TP.error(getOperator()->getName() + " node requires exactly " +
1344 itostr(NI.getNumOperands()) + " operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001345
Chris Lattner6cefb772008-01-05 22:25:12 +00001346 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1347 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1348 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001349 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001350 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001351
Chris Lattner6eb30122010-02-23 05:51:07 +00001352 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001353 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001354 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001355 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001356
Chris Lattner0be6fe72010-03-27 19:15:02 +00001357 bool MadeChange = false;
1358
1359 // Apply the result types to the node, these come from the things in the
1360 // (outs) list of the instruction.
1361 // FIXME: Cap at one result so far.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001362 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001363 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1364 Record *ResultNode = Inst.getResult(ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001365
Chris Lattnera938ac62009-07-29 20:43:05 +00001366 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001367 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001368 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001369 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001370 } else {
1371 assert(ResultNode->isSubClassOf("RegisterClass") &&
1372 "Operands should be register classes!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001373 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001374 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001375 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001376 }
Chris Lattner0be6fe72010-03-27 19:15:02 +00001377 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001378
Chris Lattner0be6fe72010-03-27 19:15:02 +00001379 // If the instruction has implicit defs, we apply the first one as a result.
1380 // FIXME: This sucks, it should apply all implicit defs.
1381 if (!InstInfo.ImplicitDefs.empty()) {
1382 unsigned ResNo = NumResultsToAdd;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001383
Chris Lattner9414ae52010-03-27 20:09:24 +00001384 // FIXME: Generalize to multiple possible types and multiple possible
1385 // ImplicitDefs.
1386 MVT::SimpleValueType VT =
1387 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001388
Chris Lattner9414ae52010-03-27 20:09:24 +00001389 if (VT != MVT::Other)
1390 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001391 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001392
Chris Lattner2cacec52010-03-15 06:00:16 +00001393 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1394 // be the same.
1395 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001396 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1397 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1398 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001399 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001400
1401 unsigned ChildNo = 0;
1402 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1403 Record *OperandNode = Inst.getOperand(i);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001404
Chris Lattner6cefb772008-01-05 22:25:12 +00001405 // If the instruction expects a predicate or optional def operand, we
1406 // codegen this by setting the operand to it's default value if it has a
1407 // non-empty DefaultOps field.
1408 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1409 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1410 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1411 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001412
Chris Lattner6cefb772008-01-05 22:25:12 +00001413 // Verify that we didn't run out of provided operands.
1414 if (ChildNo >= getNumChildren())
1415 TP.error("Instruction '" + getOperator()->getName() +
1416 "' expects more operands than were provided.");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001417
Owen Anderson825b72b2009-08-11 20:47:22 +00001418 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001419 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001420 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001421
Chris Lattner6cefb772008-01-05 22:25:12 +00001422 if (OperandNode->isSubClassOf("RegisterClass")) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001423 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001424 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001425 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001426 } else if (OperandNode->isSubClassOf("Operand")) {
1427 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattner0be6fe72010-03-27 19:15:02 +00001428 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001429 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001430 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001431 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001432 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001433 } else {
1434 assert(0 && "Unknown operand type!");
1435 abort();
1436 }
1437 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1438 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001439
Christopher Lamb02f69372008-03-10 04:16:09 +00001440 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001441 TP.error("Instruction '" + getOperator()->getName() +
1442 "' was provided too many operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001443
Chris Lattner6cefb772008-01-05 22:25:12 +00001444 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001445 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001446
Chris Lattner6eb30122010-02-23 05:51:07 +00001447 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001448
Chris Lattner6eb30122010-02-23 05:51:07 +00001449 // Node transforms always take one operand.
1450 if (getNumChildren() != 1)
1451 TP.error("Node transform '" + getOperator()->getName() +
1452 "' requires one operand!");
1453
Chris Lattner2cacec52010-03-15 06:00:16 +00001454 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1455
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001456
Chris Lattner6eb30122010-02-23 05:51:07 +00001457 // If either the output or input of the xform does not have exact
1458 // type info. We assume they must be the same. Otherwise, it is perfectly
1459 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001460#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001461 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001462 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1463 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001464 return MadeChange;
1465 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001466#endif
1467 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001468}
1469
1470/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1471/// RHS of a commutative operation, not the on LHS.
1472static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1473 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1474 return true;
1475 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1476 return true;
1477 return false;
1478}
1479
1480
1481/// canPatternMatch - If it is impossible for this pattern to match on this
1482/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001483/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001484/// that can never possibly work), and to prevent the pattern permuter from
1485/// generating stuff that is useless.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001486bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001487 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001488 if (isLeaf()) return true;
1489
1490 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1491 if (!getChild(i)->canPatternMatch(Reason, CDP))
1492 return false;
1493
1494 // If this is an intrinsic, handle cases that would make it not match. For
1495 // example, if an operand is required to be an immediate.
1496 if (getOperator()->isSubClassOf("Intrinsic")) {
1497 // TODO:
1498 return true;
1499 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001500
Chris Lattner6cefb772008-01-05 22:25:12 +00001501 // If this node is a commutative operator, check that the LHS isn't an
1502 // immediate.
1503 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001504 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1505 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001506 // Scan all of the operands of the node and make sure that only the last one
1507 // is a constant node, unless the RHS also is.
1508 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001509 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1510 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001511 if (OnlyOnRHSOfCommutative(getChild(i))) {
1512 Reason="Immediate value must be on the RHS of commutative operators!";
1513 return false;
1514 }
1515 }
1516 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001517
Chris Lattner6cefb772008-01-05 22:25:12 +00001518 return true;
1519}
1520
1521//===----------------------------------------------------------------------===//
1522// TreePattern implementation
1523//
1524
1525TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001526 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001527 isInputPattern = isInput;
1528 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattnerc2173052010-03-28 06:50:34 +00001529 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001530}
1531
1532TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001533 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001534 isInputPattern = isInput;
Chris Lattnerc2173052010-03-28 06:50:34 +00001535 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001536}
1537
1538TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001539 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001540 isInputPattern = isInput;
1541 Trees.push_back(Pat);
1542}
1543
Chris Lattner6cefb772008-01-05 22:25:12 +00001544void TreePattern::error(const std::string &Msg) const {
1545 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001546 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001547}
1548
Chris Lattner2cacec52010-03-15 06:00:16 +00001549void TreePattern::ComputeNamedNodes() {
1550 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1551 ComputeNamedNodes(Trees[i]);
1552}
1553
1554void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1555 if (!N->getName().empty())
1556 NamedNodes[N->getName()].push_back(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001557
Chris Lattner2cacec52010-03-15 06:00:16 +00001558 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1559 ComputeNamedNodes(N->getChild(i));
1560}
1561
Chris Lattnerd7349192010-03-19 21:37:09 +00001562
Chris Lattnerc2173052010-03-28 06:50:34 +00001563TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1564 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
1565 Record *R = DI->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001566
Chris Lattnerc2173052010-03-28 06:50:34 +00001567 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1568 // TreePatternNode if its own. For example:
1569 /// (foo GPR, imm) -> (foo GPR, (imm))
1570 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1571 return ParseTreePattern(new DagInit(DI, "",
1572 std::vector<std::pair<Init*, std::string> >()),
1573 OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001574
Chris Lattnerc2173052010-03-28 06:50:34 +00001575 // Input argument?
1576 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001577 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001578 if (OpName.empty())
1579 error("'node' argument requires a name to match with operand list");
1580 Args.push_back(OpName);
1581 }
1582
1583 Res->setName(OpName);
1584 return Res;
1585 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001586
Chris Lattnerc2173052010-03-28 06:50:34 +00001587 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
1588 if (!OpName.empty())
1589 error("Constant int argument should not have a name!");
1590 return new TreePatternNode(II, 1);
1591 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001592
Chris Lattnerc2173052010-03-28 06:50:34 +00001593 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
1594 // Turn this into an IntInit.
1595 Init *II = BI->convertInitializerTo(new IntRecTy());
1596 if (II == 0 || !dynamic_cast<IntInit*>(II))
1597 error("Bits value must be constants!");
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001598 return ParseTreePattern(II, OpName);
Chris Lattnerc2173052010-03-28 06:50:34 +00001599 }
1600
1601 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
1602 if (!Dag) {
1603 TheInit->dump();
1604 error("Pattern has unexpected init kind!");
1605 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001606 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1607 if (!OpDef) error("Pattern has unexpected operator type!");
1608 Record *Operator = OpDef->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001609
Chris Lattner6cefb772008-01-05 22:25:12 +00001610 if (Operator->isSubClassOf("ValueType")) {
1611 // If the operator is a ValueType, then this must be "type cast" of a leaf
1612 // node.
1613 if (Dag->getNumArgs() != 1)
1614 error("Type cast only takes one operand!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001615
Chris Lattnerc2173052010-03-28 06:50:34 +00001616 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001617
Chris Lattner6cefb772008-01-05 22:25:12 +00001618 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001619 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1620 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001621
Chris Lattnerc2173052010-03-28 06:50:34 +00001622 if (!OpName.empty())
1623 error("ValueType cast should not have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001624 return New;
1625 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001626
Chris Lattner6cefb772008-01-05 22:25:12 +00001627 // Verify that this is something that makes sense for an operator.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001628 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begeman7cee8172009-03-19 05:21:56 +00001629 !Operator->isSubClassOf("SDNode") &&
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001630 !Operator->isSubClassOf("Instruction") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001631 !Operator->isSubClassOf("SDNodeXForm") &&
1632 !Operator->isSubClassOf("Intrinsic") &&
1633 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00001634 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00001635 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001636
Chris Lattner6cefb772008-01-05 22:25:12 +00001637 // Check to see if this is something that is illegal in an input pattern.
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001638 if (isInputPattern) {
1639 if (Operator->isSubClassOf("Instruction") ||
1640 Operator->isSubClassOf("SDNodeXForm"))
1641 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1642 } else {
1643 if (Operator->isSubClassOf("Intrinsic"))
1644 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001645
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001646 if (Operator->isSubClassOf("SDNode") &&
1647 Operator->getName() != "imm" &&
1648 Operator->getName() != "fpimm" &&
1649 Operator->getName() != "tglobaltlsaddr" &&
1650 Operator->getName() != "tconstpool" &&
1651 Operator->getName() != "tjumptable" &&
1652 Operator->getName() != "tframeindex" &&
1653 Operator->getName() != "texternalsym" &&
1654 Operator->getName() != "tblockaddress" &&
1655 Operator->getName() != "tglobaladdr" &&
1656 Operator->getName() != "bb" &&
1657 Operator->getName() != "vt")
1658 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1659 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001660
Chris Lattner6cefb772008-01-05 22:25:12 +00001661 std::vector<TreePatternNode*> Children;
Chris Lattnerc2173052010-03-28 06:50:34 +00001662
1663 // Parse all the operands.
1664 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1665 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001666
Chris Lattner6cefb772008-01-05 22:25:12 +00001667 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001668 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner6cefb772008-01-05 22:25:12 +00001669 // convert the intrinsic name to a number.
1670 if (Operator->isSubClassOf("Intrinsic")) {
1671 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1672 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1673
1674 // If this intrinsic returns void, it must have side-effects and thus a
1675 // chain.
Chris Lattnerc2173052010-03-28 06:50:34 +00001676 if (Int.IS.RetVTs.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001677 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001678 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner6cefb772008-01-05 22:25:12 +00001679 // Has side-effects, requires chain.
1680 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001681 else // Otherwise, no chain.
Chris Lattner6cefb772008-01-05 22:25:12 +00001682 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001683
Chris Lattnerd7349192010-03-19 21:37:09 +00001684 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001685 Children.insert(Children.begin(), IIDNode);
1686 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001687
Chris Lattnerd7349192010-03-19 21:37:09 +00001688 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1689 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattnerc2173052010-03-28 06:50:34 +00001690 Result->setName(OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001691
Chris Lattnerc2173052010-03-28 06:50:34 +00001692 if (!Dag->getName().empty()) {
1693 assert(Result->getName().empty());
1694 Result->setName(Dag->getName());
1695 }
Nate Begeman7cee8172009-03-19 05:21:56 +00001696 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001697}
1698
Chris Lattner7a0eb912010-03-28 08:38:32 +00001699/// SimplifyTree - See if we can simplify this tree to eliminate something that
1700/// will never match in favor of something obvious that will. This is here
1701/// strictly as a convenience to target authors because it allows them to write
1702/// more type generic things and have useless type casts fold away.
1703///
1704/// This returns true if any change is made.
1705static bool SimplifyTree(TreePatternNode *&N) {
1706 if (N->isLeaf())
1707 return false;
1708
1709 // If we have a bitconvert with a resolved type and if the source and
1710 // destination types are the same, then the bitconvert is useless, remove it.
1711 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattner7a0eb912010-03-28 08:38:32 +00001712 N->getExtType(0).isConcrete() &&
1713 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1714 N->getName().empty()) {
1715 N = N->getChild(0);
1716 SimplifyTree(N);
1717 return true;
1718 }
1719
1720 // Walk all children.
1721 bool MadeChange = false;
1722 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1723 TreePatternNode *Child = N->getChild(i);
1724 MadeChange |= SimplifyTree(Child);
1725 N->setChild(i, Child);
1726 }
1727 return MadeChange;
1728}
1729
1730
1731
Chris Lattner6cefb772008-01-05 22:25:12 +00001732/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001733/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001734/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001735bool TreePattern::
1736InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1737 if (NamedNodes.empty())
1738 ComputeNamedNodes();
1739
Chris Lattner6cefb772008-01-05 22:25:12 +00001740 bool MadeChange = true;
1741 while (MadeChange) {
1742 MadeChange = false;
Chris Lattner7a0eb912010-03-28 08:38:32 +00001743 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001744 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner7a0eb912010-03-28 08:38:32 +00001745 MadeChange |= SimplifyTree(Trees[i]);
1746 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001747
1748 // If there are constraints on our named nodes, apply them.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001749 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattner2cacec52010-03-15 06:00:16 +00001750 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1751 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001752
Chris Lattner2cacec52010-03-15 06:00:16 +00001753 // If we have input named node types, propagate their types to the named
1754 // values here.
1755 if (InNamedTypes) {
1756 // FIXME: Should be error?
1757 assert(InNamedTypes->count(I->getKey()) &&
1758 "Named node in output pattern but not input pattern?");
1759
1760 const SmallVectorImpl<TreePatternNode*> &InNodes =
1761 InNamedTypes->find(I->getKey())->second;
1762
1763 // The input types should be fully resolved by now.
1764 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1765 // If this node is a register class, and it is the root of the pattern
1766 // then we're mapping something onto an input register. We allow
1767 // changing the type of the input register in this case. This allows
1768 // us to match things like:
1769 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1770 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1771 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1772 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1773 continue;
1774 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001775
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001776 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001777 InNodes[0]->getNumTypes() == 1 &&
1778 "FIXME: cannot name multiple result nodes yet");
1779 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1780 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001781 }
1782 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001783
Chris Lattner2cacec52010-03-15 06:00:16 +00001784 // If there are multiple nodes with the same name, they must all have the
1785 // same type.
1786 if (I->second.size() > 1) {
1787 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001788 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001789 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001790 "FIXME: cannot name multiple result nodes yet");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001791
Chris Lattnerd7349192010-03-19 21:37:09 +00001792 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1793 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001794 }
1795 }
1796 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001797 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001798
Chris Lattner6cefb772008-01-05 22:25:12 +00001799 bool HasUnresolvedTypes = false;
1800 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1801 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1802 return !HasUnresolvedTypes;
1803}
1804
Daniel Dunbar1a551802009-07-03 00:10:29 +00001805void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001806 OS << getRecord()->getName();
1807 if (!Args.empty()) {
1808 OS << "(" << Args[0];
1809 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1810 OS << ", " << Args[i];
1811 OS << ")";
1812 }
1813 OS << ": ";
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001814
Chris Lattner6cefb772008-01-05 22:25:12 +00001815 if (Trees.size() > 1)
1816 OS << "[\n";
1817 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1818 OS << "\t";
1819 Trees[i]->print(OS);
1820 OS << "\n";
1821 }
1822
1823 if (Trees.size() > 1)
1824 OS << "]\n";
1825}
1826
Daniel Dunbar1a551802009-07-03 00:10:29 +00001827void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001828
1829//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001830// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001831//
1832
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001833CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner67db8832010-12-13 00:23:57 +00001834 Records(R), Target(R) {
1835
Dale Johannesen49de9822009-02-05 01:49:45 +00001836 Intrinsics = LoadIntrinsics(Records, false);
1837 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001838 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001839 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001840 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001841 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001842 ParseDefaultOperands();
1843 ParseInstructions();
1844 ParsePatterns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001845
Chris Lattner6cefb772008-01-05 22:25:12 +00001846 // Generate variants. For example, commutative patterns can match
1847 // multiple ways. Add them to PatternsToMatch as well.
1848 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001849
1850 // Infer instruction flags. For example, we can detect loads,
1851 // stores, and side effects in many cases by examining an
1852 // instruction's pattern.
1853 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001854}
1855
Chris Lattnerfe718932008-01-06 01:10:31 +00001856CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001857 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001858 E = PatternFragments.end(); I != E; ++I)
1859 delete I->second;
1860}
1861
1862
Chris Lattnerfe718932008-01-06 01:10:31 +00001863Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001864 Record *N = Records.getDef(Name);
1865 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001866 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001867 exit(1);
1868 }
1869 return N;
1870}
1871
1872// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001873void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001874 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1875 while (!Nodes.empty()) {
1876 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1877 Nodes.pop_back();
1878 }
1879
Jim Grosbachda4231f2009-03-26 16:17:51 +00001880 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001881 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1882 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1883 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1884}
1885
1886/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1887/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001888void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001889 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1890 while (!Xforms.empty()) {
1891 Record *XFormNode = Xforms.back();
1892 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1893 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001894 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001895
1896 Xforms.pop_back();
1897 }
1898}
1899
Chris Lattnerfe718932008-01-06 01:10:31 +00001900void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001901 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1902 while (!AMs.empty()) {
1903 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1904 AMs.pop_back();
1905 }
1906}
1907
1908
1909/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1910/// file, building up the PatternFragments map. After we've collected them all,
1911/// inline fragments together as necessary, so that there are no references left
1912/// inside a pattern fragment to a pattern fragment.
1913///
Chris Lattnerfe718932008-01-06 01:10:31 +00001914void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001915 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001916
Chris Lattnerdc32f982008-01-05 22:43:57 +00001917 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001918 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1919 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1920 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1921 PatternFragments[Fragments[i]] = P;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001922
Chris Lattnerdc32f982008-01-05 22:43:57 +00001923 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001924 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001925 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001926
Chris Lattnerdc32f982008-01-05 22:43:57 +00001927 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001928 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001929
Chris Lattner6cefb772008-01-05 22:25:12 +00001930 // Parse the operands list.
1931 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1932 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1933 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001934 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001935 if (!OpsOp ||
1936 (OpsOp->getDef()->getName() != "ops" &&
1937 OpsOp->getDef()->getName() != "outs" &&
1938 OpsOp->getDef()->getName() != "ins"))
1939 P->error("Operands list should start with '(ops ... '!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001940
1941 // Copy over the arguments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001942 Args.clear();
1943 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1944 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1945 static_cast<DefInit*>(OpsList->getArg(j))->
1946 getDef()->getName() != "node")
1947 P->error("Operands list should all be 'node' values.");
1948 if (OpsList->getArgName(j).empty())
1949 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001950 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001951 P->error("'" + OpsList->getArgName(j) +
1952 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001953 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001954 Args.push_back(OpsList->getArgName(j));
1955 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001956
Chris Lattnerdc32f982008-01-05 22:43:57 +00001957 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001958 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001959 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001960
Chris Lattnerdc32f982008-01-05 22:43:57 +00001961 // If there is a code init for this fragment, keep track of the fact that
1962 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001963 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001964 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001965 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001966
Chris Lattner6cefb772008-01-05 22:25:12 +00001967 // If there is a node transformation corresponding to this, keep track of
1968 // it.
1969 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1970 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1971 P->getOnlyTree()->setTransformFn(Transform);
1972 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001973
Chris Lattner6cefb772008-01-05 22:25:12 +00001974 // Now that we've parsed all of the tree fragments, do a closure on them so
1975 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001976 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1977 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001978 ThePat->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001979
Chris Lattner6cefb772008-01-05 22:25:12 +00001980 // Infer as many types as possible. Don't worry about it if we don't infer
1981 // all of them, some may depend on the inputs of the pattern.
1982 try {
1983 ThePat->InferAllTypes();
1984 } catch (...) {
1985 // If this pattern fragment is not supported by this target (no types can
1986 // satisfy its constraints), just ignore it. If the bogus pattern is
1987 // actually used by instructions, the type consistency error will be
1988 // reported there.
1989 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001990
Chris Lattner6cefb772008-01-05 22:25:12 +00001991 // If debugging, print out the pattern fragment result.
1992 DEBUG(ThePat->dump());
1993 }
1994}
1995
Chris Lattnerfe718932008-01-06 01:10:31 +00001996void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001997 std::vector<Record*> DefaultOps[2];
1998 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1999 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
2000
2001 // Find some SDNode.
2002 assert(!SDNodes.empty() && "No SDNodes parsed?");
2003 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002004
Chris Lattner6cefb772008-01-05 22:25:12 +00002005 for (unsigned iter = 0; iter != 2; ++iter) {
2006 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
2007 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002008
Chris Lattner6cefb772008-01-05 22:25:12 +00002009 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2010 // SomeSDnode so that we can parse this.
2011 std::vector<std::pair<Init*, std::string> > Ops;
2012 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2013 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2014 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00002015 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002016
Chris Lattner6cefb772008-01-05 22:25:12 +00002017 // Create a TreePattern to parse this.
2018 TreePattern P(DefaultOps[iter][i], DI, false, *this);
2019 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2020
2021 // Copy the operands over into a DAGDefaultOperand.
2022 DAGDefaultOperand DefaultOpInfo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002023
Chris Lattner6cefb772008-01-05 22:25:12 +00002024 TreePatternNode *T = P.getTree(0);
2025 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2026 TreePatternNode *TPN = T->getChild(op);
2027 while (TPN->ApplyTypeConstraints(P, false))
2028 /* Resolve all types */;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002029
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002030 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002031 if (iter == 0)
2032 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00002033 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00002034 else
2035 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00002036 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002037 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002038 DefaultOpInfo.DefaultOps.push_back(TPN);
2039 }
2040
2041 // Insert it into the DefaultOperands map so we can find it later.
2042 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
2043 }
2044 }
2045}
2046
2047/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2048/// instruction input. Return true if this is a real use.
2049static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002050 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002051 // No name -> not interesting.
2052 if (Pat->getName().empty()) {
2053 if (Pat->isLeaf()) {
2054 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2055 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
2056 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002057 }
2058 return false;
2059 }
2060
2061 Record *Rec;
2062 if (Pat->isLeaf()) {
2063 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2064 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2065 Rec = DI->getDef();
2066 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00002067 Rec = Pat->getOperator();
2068 }
2069
2070 // SRCVALUE nodes are ignored.
2071 if (Rec->getName() == "srcvalue")
2072 return false;
2073
2074 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2075 if (!Slot) {
2076 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00002077 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00002078 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00002079 Record *SlotRec;
2080 if (Slot->isLeaf()) {
2081 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
2082 } else {
2083 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2084 SlotRec = Slot->getOperator();
2085 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002086
Chris Lattner53d09bd2010-02-23 05:59:10 +00002087 // Ensure that the inputs agree if we've already seen this input.
2088 if (Rec != SlotRec)
2089 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00002090 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00002091 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00002092 return true;
2093}
2094
2095/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2096/// part of "I", the instruction), computing the set of inputs and outputs of
2097/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00002098void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00002099FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2100 std::map<std::string, TreePatternNode*> &InstInputs,
2101 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner6cefb772008-01-05 22:25:12 +00002102 std::vector<Record*> &InstImpResults) {
2103 if (Pat->isLeaf()) {
Chris Lattneracfb70f2010-04-20 06:30:25 +00002104 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002105 if (!isUse && Pat->getTransformFn())
2106 I->error("Cannot specify a transform function for a non-input value!");
2107 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002108 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002109
Chris Lattner84aa60b2010-02-17 06:53:36 +00002110 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002111 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2112 TreePatternNode *Dest = Pat->getChild(i);
2113 if (!Dest->isLeaf())
2114 I->error("implicitly defined value should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002115
Chris Lattner6cefb772008-01-05 22:25:12 +00002116 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2117 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2118 I->error("implicitly defined value should be a register!");
2119 InstImpResults.push_back(Val->getDef());
2120 }
2121 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002122 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002123
Chris Lattner84aa60b2010-02-17 06:53:36 +00002124 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002125 // If this is not a set, verify that the children nodes are not void typed,
2126 // and recurse.
2127 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002128 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002129 I->error("Cannot have void nodes inside of patterns!");
2130 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002131 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002132 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002133
Chris Lattner6cefb772008-01-05 22:25:12 +00002134 // If this is a non-leaf node with no children, treat it basically as if
2135 // it were a leaf. This handles nodes like (imm).
Chris Lattneracfb70f2010-04-20 06:30:25 +00002136 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002137
Chris Lattner6cefb772008-01-05 22:25:12 +00002138 if (!isUse && Pat->getTransformFn())
2139 I->error("Cannot specify a transform function for a non-input value!");
2140 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002141 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002142
Chris Lattner6cefb772008-01-05 22:25:12 +00002143 // Otherwise, this is a set, validate and collect instruction results.
2144 if (Pat->getNumChildren() == 0)
2145 I->error("set requires operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002146
Chris Lattner6cefb772008-01-05 22:25:12 +00002147 if (Pat->getTransformFn())
2148 I->error("Cannot specify a transform function on a set node!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002149
Chris Lattner6cefb772008-01-05 22:25:12 +00002150 // Check the set destinations.
2151 unsigned NumDests = Pat->getNumChildren()-1;
2152 for (unsigned i = 0; i != NumDests; ++i) {
2153 TreePatternNode *Dest = Pat->getChild(i);
2154 if (!Dest->isLeaf())
2155 I->error("set destination should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002156
Chris Lattner6cefb772008-01-05 22:25:12 +00002157 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2158 if (!Val)
2159 I->error("set destination should be a register!");
2160
2161 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002162 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002163 if (Dest->getName().empty())
2164 I->error("set destination must have a name!");
2165 if (InstResults.count(Dest->getName()))
2166 I->error("cannot set '" + Dest->getName() +"' multiple times");
2167 InstResults[Dest->getName()] = Dest;
2168 } else if (Val->getDef()->isSubClassOf("Register")) {
2169 InstImpResults.push_back(Val->getDef());
2170 } else {
2171 I->error("set destination should be a register!");
2172 }
2173 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002174
Chris Lattner6cefb772008-01-05 22:25:12 +00002175 // Verify and collect info from the computation.
2176 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattneracfb70f2010-04-20 06:30:25 +00002177 InstInputs, InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002178}
2179
Dan Gohmanee4fa192008-04-03 00:02:49 +00002180//===----------------------------------------------------------------------===//
2181// Instruction Analysis
2182//===----------------------------------------------------------------------===//
2183
2184class InstAnalyzer {
2185 const CodeGenDAGPatterns &CDP;
2186 bool &mayStore;
2187 bool &mayLoad;
2188 bool &HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002189 bool &IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002190public:
2191 InstAnalyzer(const CodeGenDAGPatterns &cdp,
Chris Lattner1e506312010-03-19 05:34:15 +00002192 bool &maystore, bool &mayload, bool &hse, bool &isv)
2193 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
2194 IsVariadic(isv) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002195 }
2196
2197 /// Analyze - Analyze the specified instruction, returning true if the
2198 /// instruction had a pattern.
2199 bool Analyze(Record *InstRecord) {
2200 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2201 if (Pattern == 0) {
2202 HasSideEffects = 1;
2203 return false; // No pattern.
2204 }
2205
2206 // FIXME: Assume only the first tree is the pattern. The others are clobber
2207 // nodes.
2208 AnalyzeNode(Pattern->getTree(0));
2209 return true;
2210 }
2211
2212private:
2213 void AnalyzeNode(const TreePatternNode *N) {
2214 if (N->isLeaf()) {
2215 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2216 Record *LeafRec = DI->getDef();
2217 // Handle ComplexPattern leaves.
2218 if (LeafRec->isSubClassOf("ComplexPattern")) {
2219 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2220 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2221 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2222 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2223 }
2224 }
2225 return;
2226 }
2227
2228 // Analyze children.
2229 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2230 AnalyzeNode(N->getChild(i));
2231
2232 // Ignore set nodes, which are not SDNodes.
2233 if (N->getOperator()->getName() == "set")
2234 return;
2235
2236 // Get information about the SDNode for the operator.
2237 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2238
2239 // Notice properties of the node.
2240 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2241 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2242 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
Chris Lattner1e506312010-03-19 05:34:15 +00002243 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002244
2245 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2246 // If this is an intrinsic, analyze it.
2247 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2248 mayLoad = true;// These may load memory.
2249
Dan Gohman7365c092010-08-05 23:36:21 +00002250 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002251 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2252
Dan Gohman7365c092010-08-05 23:36:21 +00002253 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002254 // WriteMem intrinsics can have other strange effects.
2255 HasSideEffects = true;
2256 }
2257 }
2258
2259};
2260
2261static void InferFromPattern(const CodeGenInstruction &Inst,
2262 bool &MayStore, bool &MayLoad,
Chris Lattner1e506312010-03-19 05:34:15 +00002263 bool &HasSideEffects, bool &IsVariadic,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002264 const CodeGenDAGPatterns &CDP) {
Chris Lattner1e506312010-03-19 05:34:15 +00002265 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002266
2267 bool HadPattern =
Chris Lattner1e506312010-03-19 05:34:15 +00002268 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2269 .Analyze(Inst.TheDef);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002270
2271 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2272 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2273 // If we decided that this is a store from the pattern, then the .td file
2274 // entry is redundant.
2275 if (MayStore)
2276 fprintf(stderr,
2277 "Warning: mayStore flag explicitly set on instruction '%s'"
2278 " but flag already inferred from pattern.\n",
2279 Inst.TheDef->getName().c_str());
2280 MayStore = true;
2281 }
2282
2283 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2284 // If we decided that this is a load from the pattern, then the .td file
2285 // entry is redundant.
2286 if (MayLoad)
2287 fprintf(stderr,
2288 "Warning: mayLoad flag explicitly set on instruction '%s'"
2289 " but flag already inferred from pattern.\n",
2290 Inst.TheDef->getName().c_str());
2291 MayLoad = true;
2292 }
2293
2294 if (Inst.neverHasSideEffects) {
2295 if (HadPattern)
2296 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2297 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2298 HasSideEffects = false;
2299 }
2300
2301 if (Inst.hasSideEffects) {
2302 if (HasSideEffects)
2303 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2304 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2305 HasSideEffects = true;
2306 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002307
Chris Lattnerc240bb02010-11-01 04:03:32 +00002308 if (Inst.Operands.isVariadic)
Chris Lattner1e506312010-03-19 05:34:15 +00002309 IsVariadic = true; // Can warn if we want.
Dan Gohmanee4fa192008-04-03 00:02:49 +00002310}
2311
Chris Lattner6cefb772008-01-05 22:25:12 +00002312/// ParseInstructions - Parse all of the instructions, inlining and resolving
2313/// any fragments involved. This populates the Instructions list with fully
2314/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002315void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002316 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002317
Chris Lattner6cefb772008-01-05 22:25:12 +00002318 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2319 ListInit *LI = 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002320
Chris Lattner6cefb772008-01-05 22:25:12 +00002321 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2322 LI = Instrs[i]->getValueAsListInit("Pattern");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002323
Chris Lattner6cefb772008-01-05 22:25:12 +00002324 // If there is no pattern, only collect minimal information about the
2325 // instruction for its operand list. We have to assume that there is one
2326 // result, as we have no detailed info.
2327 if (!LI || LI->getSize() == 0) {
2328 std::vector<Record*> Results;
2329 std::vector<Record*> Operands;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002330
Chris Lattnerf30187a2010-03-19 00:07:20 +00002331 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002332
Chris Lattnerc240bb02010-11-01 04:03:32 +00002333 if (InstInfo.Operands.size() != 0) {
2334 if (InstInfo.Operands.NumDefs == 0) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002335 // These produce no results
Chris Lattnerc240bb02010-11-01 04:03:32 +00002336 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2337 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002338 } else {
2339 // Assume the first operand is the result.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002340 Results.push_back(InstInfo.Operands[0].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002341
Chris Lattner6cefb772008-01-05 22:25:12 +00002342 // The rest are inputs.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002343 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2344 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002345 }
2346 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002347
Chris Lattner6cefb772008-01-05 22:25:12 +00002348 // Create and insert the instruction.
2349 std::vector<Record*> ImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002350 Instructions.insert(std::make_pair(Instrs[i],
Chris Lattner62bcec82010-04-20 06:28:43 +00002351 DAGInstruction(0, Results, Operands, ImpResults)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002352 continue; // no pattern.
2353 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002354
Chris Lattner6cefb772008-01-05 22:25:12 +00002355 // Parse the instruction.
2356 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2357 // Inline pattern fragments into it.
2358 I->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002359
Chris Lattner6cefb772008-01-05 22:25:12 +00002360 // Infer as many types as possible. If we cannot infer all of them, we can
2361 // never do anything with this instruction pattern: report it to the user.
2362 if (!I->InferAllTypes())
2363 I->error("Could not infer all types in pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002364
2365 // InstInputs - Keep track of all of the inputs of the instruction, along
Chris Lattner6cefb772008-01-05 22:25:12 +00002366 // with the record they are declared as.
2367 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002368
Chris Lattner6cefb772008-01-05 22:25:12 +00002369 // InstResults - Keep track of all the virtual registers that are 'set'
2370 // in the instruction, including what reg class they are.
2371 std::map<std::string, TreePatternNode*> InstResults;
2372
Chris Lattner6cefb772008-01-05 22:25:12 +00002373 std::vector<Record*> InstImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002374
Chris Lattner6cefb772008-01-05 22:25:12 +00002375 // Verify that the top-level forms in the instruction are of void type, and
2376 // fill in the InstResults map.
2377 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2378 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002379 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002380 I->error("Top-level forms in instruction pattern should have"
2381 " void types");
2382
2383 // Find inputs and outputs, and verify the structure of the uses/defs.
2384 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002385 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002386 }
2387
2388 // Now that we have inputs and outputs of the pattern, inspect the operands
2389 // list for the instruction. This determines the order that operands are
2390 // added to the machine instruction the node corresponds to.
2391 unsigned NumResults = InstResults.size();
2392
2393 // Parse the operands list from the (ops) list, validating it.
2394 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002395 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002396
2397 // Check that all of the results occur first in the list.
2398 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002399 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002400 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerc240bb02010-11-01 04:03:32 +00002401 if (i == CGI.Operands.size())
Chris Lattner6cefb772008-01-05 22:25:12 +00002402 I->error("'" + InstResults.begin()->first +
2403 "' set but does not appear in operand list!");
Chris Lattnerc240bb02010-11-01 04:03:32 +00002404 const std::string &OpName = CGI.Operands[i].Name;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002405
Chris Lattner6cefb772008-01-05 22:25:12 +00002406 // Check that it exists in InstResults.
2407 TreePatternNode *RNode = InstResults[OpName];
2408 if (RNode == 0)
2409 I->error("Operand $" + OpName + " does not exist in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002410
Chris Lattner6cefb772008-01-05 22:25:12 +00002411 if (i == 0)
2412 Res0Node = RNode;
2413 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2414 if (R == 0)
2415 I->error("Operand $" + OpName + " should be a set destination: all "
2416 "outputs must occur before inputs in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002417
Chris Lattnerc240bb02010-11-01 04:03:32 +00002418 if (CGI.Operands[i].Rec != R)
Chris Lattner6cefb772008-01-05 22:25:12 +00002419 I->error("Operand $" + OpName + " class mismatch!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002420
Chris Lattner6cefb772008-01-05 22:25:12 +00002421 // Remember the return type.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002422 Results.push_back(CGI.Operands[i].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002423
Chris Lattner6cefb772008-01-05 22:25:12 +00002424 // Okay, this one checks out.
2425 InstResults.erase(OpName);
2426 }
2427
2428 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2429 // the copy while we're checking the inputs.
2430 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2431
2432 std::vector<TreePatternNode*> ResultNodeOperands;
2433 std::vector<Record*> Operands;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002434 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2435 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner6cefb772008-01-05 22:25:12 +00002436 const std::string &OpName = Op.Name;
2437 if (OpName.empty())
2438 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2439
2440 if (!InstInputsCheck.count(OpName)) {
2441 // If this is an predicate operand or optional def operand with an
2442 // DefaultOps set filled in, we can ignore this. When we codegen it,
2443 // we will do so as always executed.
2444 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2445 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2446 // Does it have a non-empty DefaultOps field? If so, ignore this
2447 // operand.
2448 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2449 continue;
2450 }
2451 I->error("Operand $" + OpName +
2452 " does not appear in the instruction pattern");
2453 }
2454 TreePatternNode *InVal = InstInputsCheck[OpName];
2455 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002456
Chris Lattner6cefb772008-01-05 22:25:12 +00002457 if (InVal->isLeaf() &&
2458 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2459 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2460 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2461 I->error("Operand $" + OpName + "'s register class disagrees"
2462 " between the operand and pattern");
2463 }
2464 Operands.push_back(Op.Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002465
Chris Lattner6cefb772008-01-05 22:25:12 +00002466 // Construct the result for the dest-pattern operand list.
2467 TreePatternNode *OpNode = InVal->clone();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002468
Chris Lattner6cefb772008-01-05 22:25:12 +00002469 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002470 OpNode->clearPredicateFns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002471
Chris Lattner6cefb772008-01-05 22:25:12 +00002472 // Promote the xform function to be an explicit node if set.
2473 if (Record *Xform = OpNode->getTransformFn()) {
2474 OpNode->setTransformFn(0);
2475 std::vector<TreePatternNode*> Children;
2476 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002477 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002478 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002479
Chris Lattner6cefb772008-01-05 22:25:12 +00002480 ResultNodeOperands.push_back(OpNode);
2481 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002482
Chris Lattner6cefb772008-01-05 22:25:12 +00002483 if (!InstInputsCheck.empty())
2484 I->error("Input operand $" + InstInputsCheck.begin()->first +
2485 " occurs in pattern but not in operands list!");
2486
2487 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002488 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2489 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002490 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002491 for (unsigned i = 0; i != NumResults; ++i)
2492 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002493
2494 // Create and insert the instruction.
Chris Lattneracfb70f2010-04-20 06:30:25 +00002495 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner62bcec82010-04-20 06:28:43 +00002496 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002497 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2498
2499 // Use a temporary tree pattern to infer all types and make sure that the
2500 // constructed result is correct. This depends on the instruction already
2501 // being inserted into the Instructions map.
2502 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002503 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002504
2505 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2506 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002507
Chris Lattner6cefb772008-01-05 22:25:12 +00002508 DEBUG(I->dump());
2509 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002510
Chris Lattner6cefb772008-01-05 22:25:12 +00002511 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002512 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2513 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002514 E = Instructions.end(); II != E; ++II) {
2515 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002516 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002517 if (I == 0) continue; // No pattern.
2518
2519 // FIXME: Assume only the first tree is the pattern. The others are clobber
2520 // nodes.
2521 TreePatternNode *Pattern = I->getTree(0);
2522 TreePatternNode *SrcPattern;
2523 if (Pattern->getOperator()->getName() == "set") {
2524 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2525 } else{
2526 // Not a set (store or something?)
2527 SrcPattern = Pattern;
2528 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002529
Chris Lattner6cefb772008-01-05 22:25:12 +00002530 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002531 AddPatternToMatch(I,
Jim Grosbach997759a2010-12-07 23:05:49 +00002532 PatternToMatch(Instr,
2533 Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002534 SrcPattern,
2535 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002536 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002537 Instr->getValueAsInt("AddedComplexity"),
2538 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002539 }
2540}
2541
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002542
2543typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2544
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002545static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002546 std::map<std::string, NameRecord> &Names,
2547 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002548 if (!P->getName().empty()) {
2549 NameRecord &Rec = Names[P->getName()];
2550 // If this is the first instance of the name, remember the node.
2551 if (Rec.second++ == 0)
2552 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002553 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002554 PatternTop->error("repetition of value: $" + P->getName() +
2555 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002556 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002557
Chris Lattner967d54a2010-02-23 06:35:45 +00002558 if (!P->isLeaf()) {
2559 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002560 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002561 }
2562}
2563
Chris Lattner25b6f912010-02-23 06:16:51 +00002564void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2565 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002566 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002567 std::string Reason;
2568 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002569 Pattern->error("Pattern can never match: " + Reason);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002570
Chris Lattner405f1252010-03-01 22:29:19 +00002571 // If the source pattern's root is a complex pattern, that complex pattern
2572 // must specify the nodes it can potentially match.
2573 if (const ComplexPattern *CP =
2574 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2575 if (CP->getRootNodes().empty())
2576 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2577 " could match");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002578
2579
Chris Lattner967d54a2010-02-23 06:35:45 +00002580 // Find all of the named values in the input and output, ensure they have the
2581 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002582 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002583 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2584 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002585
2586 // Scan all of the named values in the destination pattern, rejecting them if
2587 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002588 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002589 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002590 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002591 Pattern->error("Pattern has input without matching name in output: $" +
2592 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002593 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002594
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002595 // Scan all of the named values in the source pattern, rejecting them if the
2596 // name isn't used in the dest, and isn't used to tie two values together.
2597 for (std::map<std::string, NameRecord>::iterator
2598 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2599 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2600 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002601
Chris Lattner25b6f912010-02-23 06:16:51 +00002602 PatternsToMatch.push_back(PTM);
2603}
2604
2605
Dan Gohmanee4fa192008-04-03 00:02:49 +00002606
2607void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002608 const std::vector<const CodeGenInstruction*> &Instructions =
2609 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002610 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2611 CodeGenInstruction &InstInfo =
2612 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002613 // Determine properties of the instruction from its pattern.
Chris Lattner1e506312010-03-19 05:34:15 +00002614 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2615 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2616 *this);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002617 InstInfo.mayStore = MayStore;
2618 InstInfo.mayLoad = MayLoad;
2619 InstInfo.hasSideEffects = HasSideEffects;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002620 InstInfo.Operands.isVariadic = IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002621 }
2622}
2623
Chris Lattner2cacec52010-03-15 06:00:16 +00002624/// Given a pattern result with an unresolved type, see if we can find one
2625/// instruction with an unresolved result type. Force this result type to an
2626/// arbitrary element if it's possible types to converge results.
2627static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2628 if (N->isLeaf())
2629 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002630
Chris Lattner2cacec52010-03-15 06:00:16 +00002631 // Analyze children.
2632 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2633 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2634 return true;
2635
2636 if (!N->getOperator()->isSubClassOf("Instruction"))
2637 return false;
2638
2639 // If this type is already concrete or completely unknown we can't do
2640 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00002641 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2642 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2643 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002644
Chris Lattnerd7349192010-03-19 21:37:09 +00002645 // Otherwise, force its type to the first possibility (an arbitrary choice).
2646 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2647 return true;
2648 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002649
Chris Lattnerd7349192010-03-19 21:37:09 +00002650 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00002651}
2652
Chris Lattnerfe718932008-01-06 01:10:31 +00002653void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002654 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2655
2656 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002657 Record *CurPattern = Patterns[i];
2658 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Chris Lattner310adf12010-03-27 02:53:27 +00002659 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002660
2661 // Inline pattern fragments into it.
2662 Pattern->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002663
Chris Lattnerd7349192010-03-19 21:37:09 +00002664 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00002665 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002666
Chris Lattner6cefb772008-01-05 22:25:12 +00002667 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00002668 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002669
Chris Lattner6cefb772008-01-05 22:25:12 +00002670 // Inline pattern fragments into it.
2671 Result->InlinePatternFragments();
2672
2673 if (Result->getNumTrees() != 1)
2674 Result->error("Cannot handle instructions producing instructions "
2675 "with temporaries yet!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002676
Chris Lattner6cefb772008-01-05 22:25:12 +00002677 bool IterateInference;
2678 bool InferredAllPatternTypes, InferredAllResultTypes;
2679 do {
2680 // Infer as many types as possible. If we cannot infer all of them, we
2681 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002682 InferredAllPatternTypes =
2683 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002684
Chris Lattner6cefb772008-01-05 22:25:12 +00002685 // Infer as many types as possible. If we cannot infer all of them, we
2686 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002687 InferredAllResultTypes =
2688 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002689
Chris Lattner6c6ba362010-03-18 23:15:10 +00002690 IterateInference = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002691
Chris Lattner6cefb772008-01-05 22:25:12 +00002692 // Apply the type of the result to the source pattern. This helps us
2693 // resolve cases where the input type is known to be a pointer type (which
2694 // is considered resolved), but the result knows it needs to be 32- or
2695 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00002696 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2697 Pattern->getTree(0)->getNumTypes());
2698 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00002699 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002700 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002701 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002702 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002703 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002704
Chris Lattner2cacec52010-03-15 06:00:16 +00002705 // If our iteration has converged and the input pattern's types are fully
2706 // resolved but the result pattern is not fully resolved, we may have a
2707 // situation where we have two instructions in the result pattern and
2708 // the instructions require a common register class, but don't care about
2709 // what actual MVT is used. This is actually a bug in our modelling:
2710 // output patterns should have register classes, not MVTs.
2711 //
2712 // In any case, to handle this, we just go through and disambiguate some
2713 // arbitrary types to the result pattern's nodes.
2714 if (!IterateInference && InferredAllPatternTypes &&
2715 !InferredAllResultTypes)
2716 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2717 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002718 } while (IterateInference);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002719
Chris Lattner6cefb772008-01-05 22:25:12 +00002720 // Verify that we inferred enough types that we can do something with the
2721 // pattern and result. If these fire the user has to add type casts.
2722 if (!InferredAllPatternTypes)
2723 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002724 if (!InferredAllResultTypes) {
2725 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002726 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002727 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002728
Chris Lattner6cefb772008-01-05 22:25:12 +00002729 // Validate that the input pattern is correct.
2730 std::map<std::string, TreePatternNode*> InstInputs;
2731 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00002732 std::vector<Record*> InstImpResults;
2733 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2734 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2735 InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002736 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002737
2738 // Promote the xform function to be an explicit node if set.
2739 TreePatternNode *DstPattern = Result->getOnlyTree();
2740 std::vector<TreePatternNode*> ResultNodeOperands;
2741 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2742 TreePatternNode *OpNode = DstPattern->getChild(ii);
2743 if (Record *Xform = OpNode->getTransformFn()) {
2744 OpNode->setTransformFn(0);
2745 std::vector<TreePatternNode*> Children;
2746 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002747 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002748 }
2749 ResultNodeOperands.push_back(OpNode);
2750 }
2751 DstPattern = Result->getOnlyTree();
2752 if (!DstPattern->isLeaf())
2753 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00002754 ResultNodeOperands,
2755 DstPattern->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002756
Chris Lattnerd7349192010-03-19 21:37:09 +00002757 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2758 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002759
Chris Lattner6cefb772008-01-05 22:25:12 +00002760 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2761 Temp.InferAllTypes();
2762
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002763
Chris Lattner25b6f912010-02-23 06:16:51 +00002764 AddPatternToMatch(Pattern,
Jim Grosbach997759a2010-12-07 23:05:49 +00002765 PatternToMatch(CurPattern,
2766 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerd7349192010-03-19 21:37:09 +00002767 Pattern->getTree(0),
2768 Temp.getOnlyTree(), InstImpResults,
2769 CurPattern->getValueAsInt("AddedComplexity"),
2770 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002771 }
2772}
2773
2774/// CombineChildVariants - Given a bunch of permutations of each child of the
2775/// 'operator' node, put them together in all possible ways.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002776static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00002777 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2778 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002779 CodeGenDAGPatterns &CDP,
2780 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002781 // Make sure that each operand has at least one variant to choose from.
2782 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2783 if (ChildVariants[i].empty())
2784 return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002785
Chris Lattner6cefb772008-01-05 22:25:12 +00002786 // The end result is an all-pairs construction of the resultant pattern.
2787 std::vector<unsigned> Idxs;
2788 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002789 bool NotDone;
2790 do {
2791#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002792 DEBUG(if (!Idxs.empty()) {
2793 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2794 for (unsigned i = 0; i < Idxs.size(); ++i) {
2795 errs() << Idxs[i] << " ";
2796 }
2797 errs() << "]\n";
2798 });
Scott Michel327d0652008-03-05 17:49:05 +00002799#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002800 // Create the variant and add it to the output list.
2801 std::vector<TreePatternNode*> NewChildren;
2802 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2803 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00002804 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2805 Orig->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002806
Chris Lattner6cefb772008-01-05 22:25:12 +00002807 // Copy over properties.
2808 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002809 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002810 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00002811 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2812 R->setType(i, Orig->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002813
Scott Michel327d0652008-03-05 17:49:05 +00002814 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002815 std::string ErrString;
2816 if (!R->canPatternMatch(ErrString, CDP)) {
2817 delete R;
2818 } else {
2819 bool AlreadyExists = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002820
Chris Lattner6cefb772008-01-05 22:25:12 +00002821 // Scan to see if this pattern has already been emitted. We can get
2822 // duplication due to things like commuting:
2823 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2824 // which are the same pattern. Ignore the dups.
2825 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002826 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002827 AlreadyExists = true;
2828 break;
2829 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002830
Chris Lattner6cefb772008-01-05 22:25:12 +00002831 if (AlreadyExists)
2832 delete R;
2833 else
2834 OutVariants.push_back(R);
2835 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002836
Scott Michel327d0652008-03-05 17:49:05 +00002837 // Increment indices to the next permutation by incrementing the
2838 // indicies from last index backward, e.g., generate the sequence
2839 // [0, 0], [0, 1], [1, 0], [1, 1].
2840 int IdxsIdx;
2841 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2842 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2843 Idxs[IdxsIdx] = 0;
2844 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002845 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002846 }
Scott Michel327d0652008-03-05 17:49:05 +00002847 NotDone = (IdxsIdx >= 0);
2848 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002849}
2850
2851/// CombineChildVariants - A helper function for binary operators.
2852///
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002853static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00002854 const std::vector<TreePatternNode*> &LHS,
2855 const std::vector<TreePatternNode*> &RHS,
2856 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002857 CodeGenDAGPatterns &CDP,
2858 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002859 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2860 ChildVariants.push_back(LHS);
2861 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002862 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002863}
Chris Lattner6cefb772008-01-05 22:25:12 +00002864
2865
2866static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2867 std::vector<TreePatternNode *> &Children) {
2868 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2869 Record *Operator = N->getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002870
Chris Lattner6cefb772008-01-05 22:25:12 +00002871 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002872 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002873 N->getTransformFn()) {
2874 Children.push_back(N);
2875 return;
2876 }
2877
2878 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2879 Children.push_back(N->getChild(0));
2880 else
2881 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2882
2883 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2884 Children.push_back(N->getChild(1));
2885 else
2886 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2887}
2888
2889/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2890/// the (potentially recursive) pattern by using algebraic laws.
2891///
2892static void GenerateVariantsOf(TreePatternNode *N,
2893 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002894 CodeGenDAGPatterns &CDP,
2895 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002896 // We cannot permute leaves.
2897 if (N->isLeaf()) {
2898 OutVariants.push_back(N);
2899 return;
2900 }
2901
2902 // Look up interesting info about the node.
2903 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2904
Jim Grosbachda4231f2009-03-26 16:17:51 +00002905 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002906 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002907 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002908 std::vector<TreePatternNode*> MaximalChildren;
2909 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2910
2911 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2912 // permutations.
2913 if (MaximalChildren.size() == 3) {
2914 // Find the variants of all of our maximal children.
2915 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002916 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2917 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2918 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002919
Chris Lattner6cefb772008-01-05 22:25:12 +00002920 // There are only two ways we can permute the tree:
2921 // (A op B) op C and A op (B op C)
2922 // Within these forms, we can also permute A/B/C.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002923
Chris Lattner6cefb772008-01-05 22:25:12 +00002924 // Generate legal pair permutations of A/B/C.
2925 std::vector<TreePatternNode*> ABVariants;
2926 std::vector<TreePatternNode*> BAVariants;
2927 std::vector<TreePatternNode*> ACVariants;
2928 std::vector<TreePatternNode*> CAVariants;
2929 std::vector<TreePatternNode*> BCVariants;
2930 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002931 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2932 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2933 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2934 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2935 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2936 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002937
2938 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002939 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2940 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2941 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2942 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2943 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2944 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002945
2946 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002947 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2948 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2949 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2950 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2951 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2952 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002953 return;
2954 }
2955 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002956
Chris Lattner6cefb772008-01-05 22:25:12 +00002957 // Compute permutations of all children.
2958 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2959 ChildVariants.resize(N->getNumChildren());
2960 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002961 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002962
2963 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002964 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002965
2966 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002967 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2968 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2969 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2970 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002971 // Don't count children which are actually register references.
2972 unsigned NC = 0;
2973 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2974 TreePatternNode *Child = N->getChild(i);
2975 if (Child->isLeaf())
2976 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2977 Record *RR = DI->getDef();
2978 if (RR->isSubClassOf("Register"))
2979 continue;
2980 }
2981 NC++;
2982 }
2983 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002984 if (isCommIntrinsic) {
2985 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2986 // operands are the commutative operands, and there might be more operands
2987 // after those.
2988 assert(NC >= 3 &&
2989 "Commutative intrinsic should have at least 3 childrean!");
2990 std::vector<std::vector<TreePatternNode*> > Variants;
2991 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2992 Variants.push_back(ChildVariants[2]);
2993 Variants.push_back(ChildVariants[1]);
2994 for (unsigned i = 3; i != NC; ++i)
2995 Variants.push_back(ChildVariants[i]);
2996 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2997 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002998 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002999 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003000 }
3001}
3002
3003
3004// GenerateVariants - Generate variants. For example, commutative patterns can
3005// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00003006void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00003007 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003008
Chris Lattner6cefb772008-01-05 22:25:12 +00003009 // Loop over all of the patterns we've collected, checking to see if we can
3010 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00003011 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00003012 // the .td file having to contain tons of variants of instructions.
3013 //
3014 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3015 // intentionally do not reconsider these. Any variants of added patterns have
3016 // already been added.
3017 //
3018 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00003019 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00003020 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00003021 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00003022 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00003023 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00003024 DEBUG(errs() << "\n");
Jim Grosbachbb168242010-10-08 18:13:57 +00003025 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3026 DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003027
3028 assert(!Variants.empty() && "Must create at least original variant!");
3029 Variants.erase(Variants.begin()); // Remove the original pattern.
3030
3031 if (Variants.empty()) // No variants for this pattern.
3032 continue;
3033
Chris Lattner569f1212009-08-23 04:44:11 +00003034 DEBUG(errs() << "FOUND VARIANTS OF: ";
3035 PatternsToMatch[i].getSrcPattern()->dump();
3036 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003037
3038 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3039 TreePatternNode *Variant = Variants[v];
3040
Chris Lattner569f1212009-08-23 04:44:11 +00003041 DEBUG(errs() << " VAR#" << v << ": ";
3042 Variant->dump();
3043 errs() << "\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003044
Chris Lattner6cefb772008-01-05 22:25:12 +00003045 // Scan to see if an instruction or explicit pattern already matches this.
3046 bool AlreadyExists = false;
3047 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00003048 // Skip if the top level predicates do not match.
3049 if (PatternsToMatch[i].getPredicates() !=
3050 PatternsToMatch[p].getPredicates())
3051 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00003052 // Check to see if this variant already exists.
Jim Grosbachbb168242010-10-08 18:13:57 +00003053 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3054 DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00003055 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003056 AlreadyExists = true;
3057 break;
3058 }
3059 }
3060 // If we already have it, ignore the variant.
3061 if (AlreadyExists) continue;
3062
3063 // Otherwise, add it to the list of patterns we have.
3064 PatternsToMatch.
Jim Grosbach997759a2010-12-07 23:05:49 +00003065 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3066 PatternsToMatch[i].getPredicates(),
Chris Lattner6cefb772008-01-05 22:25:12 +00003067 Variant, PatternsToMatch[i].getDstPattern(),
3068 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00003069 PatternsToMatch[i].getAddedComplexity(),
3070 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003071 }
3072
Chris Lattner569f1212009-08-23 04:44:11 +00003073 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003074 }
3075}
3076