blob: ba9a98d8dd12e0242d84307de3a6ef53490832fe [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());
59
60 if (!VTList.empty())
61 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
62 VTList[0] != MVT::fAny);
63
64 // Remove duplicates.
65 array_pod_sort(TypeVec.begin(), TypeVec.end());
66 TypeVec.erase(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());
Chris Lattner774ce292010-03-19 17:41:26 +000075 const std::vector<MVT::SimpleValueType> &LegalTypes =
76 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
77
78 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 " +
85 std::string(PredicateName) + " types found");
86 // 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());
92
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;
103}
104
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;
112}
113
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>";
Chris Lattner2cacec52010-03-15 06:00:16 +0000126
127 std::string Result;
128
129 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 }
137
138 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;
149
150 if (isCompletelyUnknown()) {
151 *this = InVT;
152 return true;
153 }
154
155 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
156
157 // 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);
166
167 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 }
172
173 // If the input has multiple scalar integers, this doesn't add any info.
174 if (!InCopy.isCompletelyUnknown())
175 return false;
176 }
177 break;
178 }
179
180 // 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);
185
186 // 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 }
194
195 return MadeChange;
196 }
197
198 // 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 }
210
211 if (InInVT) continue;
212 TypeVec.erase(TypeVec.begin()+i--);
213 MadeChange = true;
214 }
215
216 // If we removed all of our types, we have a type contradiction.
217 if (!TypeVec.empty())
218 return MadeChange;
219
220 // 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);
Chris Lattner2cacec52010-03-15 06:00:16 +0000235
236 // 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--);
240
241 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);
Chris Lattner2cacec52010-03-15 06:00:16 +0000257
258 // 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--);
262
263 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);
Chris Lattner2cacec52010-03-15 06:00:16 +0000279
280 // 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--);
284
285 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;
299
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 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000306
307 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;
320
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000321 if (isCompletelyUnknown())
322 MadeChange = FillWithPossibleTypes(TP);
323
324 if (Other.isCompletelyUnknown())
325 MadeChange = Other.FillWithPossibleTypes(TP);
326
327 // 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);
337
338 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
339 "Should have a type list now");
340
341 // 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);
346
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!");
Chris Lattner2cacec52010-03-15 06:00:16 +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];
Chris Lattner2cacec52010-03-15 06:00:16 +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() +"'!");
Chris Lattner2cacec52010-03-15 06:00:16 +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 }
Chris Lattner2cacec52010-03-15 06:00:16 +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];
Chris Lattner2cacec52010-03-15 06:00:16 +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()+"'!");
386
387 TVI = std::find(TypeVec.begin(), TypeVec.end(), Largest);
388 if (TVI != TypeVec.end()) {
389 TypeVec.erase(TVI);
390 MadeChange = true;
391 }
392
393 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();
409 return MadeChange |
410 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;
Chris Lattner2cacec52010-03-15 06:00:16 +0000417
Chris Lattner66fb9d22010-03-24 00:01:16 +0000418 MVT::SimpleValueType VT = VTOperand.getConcrete();
Chris Lattner2cacec52010-03-15 06:00:16 +0000419
Chris Lattner66fb9d22010-03-24 00:01:16 +0000420 TypeSet InputSet(*this);
421
422 // 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 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000430
431 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
437//===----------------------------------------------------------------------===//
438// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000439
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000440bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
441 return LHS->getID() < RHS->getID();
442}
Scott Michel327d0652008-03-05 17:49:05 +0000443
444/// Dependent variable map for CodeGenDAGPattern variant generation
445typedef std::map<std::string, int> DepVarMap;
446
447/// Const iterator shorthand for DepVarMap
448typedef DepVarMap::const_iterator DepVarMap_citer;
449
450namespace {
451void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
452 if (N->isLeaf()) {
453 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
454 DepMap[N->getName()]++;
455 }
456 } else {
457 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
458 FindDepVarsOf(N->getChild(i), DepMap);
459 }
460}
461
462//! Find dependent variables within child patterns
463/*!
464 */
465void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
466 DepVarMap depcounts;
467 FindDepVarsOf(N, depcounts);
468 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
469 if (i->second > 1) { // std::pair<std::string, int>
470 DepVars.insert(i->first);
471 }
472 }
473}
474
475//! Dump the dependent variable set:
476void DumpDepVars(MultipleUseVarSet &DepVars) {
477 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000478 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000479 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000480 DEBUG(errs() << "[ ");
Scott Michel327d0652008-03-05 17:49:05 +0000481 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
482 i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000483 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000484 }
Chris Lattner569f1212009-08-23 04:44:11 +0000485 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000486 }
487}
488}
489
Chris Lattner6cefb772008-01-05 22:25:12 +0000490//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000491// PatternToMatch implementation
492//
493
494/// getPredicateCheck - Return a single string containing all of this
495/// pattern's predicates concatenated with "&&" operators.
496///
497std::string PatternToMatch::getPredicateCheck() const {
498 std::string PredicateCheck;
499 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
500 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
501 Record *Def = Pred->getDef();
502 if (!Def->isSubClassOf("Predicate")) {
503#ifndef NDEBUG
504 Def->dump();
505#endif
506 assert(0 && "Unknown predicate type!");
507 }
508 if (!PredicateCheck.empty())
509 PredicateCheck += " && ";
510 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
511 }
512 }
513
514 return PredicateCheck;
515}
516
517//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000518// SDTypeConstraint implementation
519//
520
521SDTypeConstraint::SDTypeConstraint(Record *R) {
522 OperandNo = R->getValueAsInt("OperandNum");
523
524 if (R->isSubClassOf("SDTCisVT")) {
525 ConstraintType = SDTCisVT;
526 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
527 } else if (R->isSubClassOf("SDTCisPtrTy")) {
528 ConstraintType = SDTCisPtrTy;
529 } else if (R->isSubClassOf("SDTCisInt")) {
530 ConstraintType = SDTCisInt;
531 } else if (R->isSubClassOf("SDTCisFP")) {
532 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000533 } else if (R->isSubClassOf("SDTCisVec")) {
534 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000535 } else if (R->isSubClassOf("SDTCisSameAs")) {
536 ConstraintType = SDTCisSameAs;
537 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
538 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
539 ConstraintType = SDTCisVTSmallerThanOp;
540 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
541 R->getValueAsInt("OtherOperandNum");
542 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
543 ConstraintType = SDTCisOpSmallerThanOp;
544 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
545 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000546 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
547 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000548 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000549 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000550 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000551 exit(1);
552 }
553}
554
555/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000556/// N, and the result number in ResNo.
557static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
558 const SDNodeInfo &NodeInfo,
559 unsigned &ResNo) {
560 unsigned NumResults = NodeInfo.getNumResults();
561 if (OpNo < NumResults) {
562 ResNo = OpNo;
563 return N;
564 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000565
Chris Lattner2e68a022010-03-19 21:56:21 +0000566 OpNo -= NumResults;
567
568 if (OpNo >= N->getNumChildren()) {
569 errs() << "Invalid operand number in type constraint "
570 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000571 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000572 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000573 exit(1);
574 }
575
Chris Lattner2e68a022010-03-19 21:56:21 +0000576 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000577}
578
579/// ApplyTypeConstraint - Given a node in a pattern, apply this type
580/// constraint to the nodes operands. This returns true if it makes a
581/// change, false otherwise. If a type contradiction is found, throw an
582/// exception.
583bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
584 const SDNodeInfo &NodeInfo,
585 TreePattern &TP) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000586 // Check that the number of operands is sane. Negative operands -> varargs.
587 if (NodeInfo.getNumOperands() >= 0) {
588 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
589 TP.error(N->getOperator()->getName() + " node requires exactly " +
590 itostr(NodeInfo.getNumOperands()) + " operands!");
591 }
592
Chris Lattner2e68a022010-03-19 21:56:21 +0000593 unsigned ResNo = 0; // The result number being referenced.
594 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000595
596 switch (ConstraintType) {
597 default: assert(0 && "Unknown constraint type!");
598 case SDTCisVT:
599 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000600 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000601 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000602 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000603 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000604 case SDTCisInt:
605 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000606 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000607 case SDTCisFP:
608 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000609 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000610 case SDTCisVec:
611 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000612 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000613 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000614 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000615 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000616 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000617 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
618 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000619 }
620 case SDTCisVTSmallerThanOp: {
621 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
622 // have an integer type that is smaller than the VT.
623 if (!NodeToApply->isLeaf() ||
624 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
625 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
626 ->isSubClassOf("ValueType"))
627 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000628 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000629 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Chris Lattnercc878302010-03-24 00:06:46 +0000630
631 EEVT::TypeSet TypeListTmp(VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000632
Chris Lattner2e68a022010-03-19 21:56:21 +0000633 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000634 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000635 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
636 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000637
Chris Lattnercc878302010-03-24 00:06:46 +0000638 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000639 }
640 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000641 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000642 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000643 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
644 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000645 return NodeToApply->getExtType(ResNo).
646 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000647 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000648 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000649 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000650 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000651 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
652 VResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000653
Chris Lattner66fb9d22010-03-24 00:01:16 +0000654 // Filter vector types out of VecOperand that don't have the right element
655 // type.
656 return VecOperand->getExtType(VResNo).
657 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000658 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000659 }
660 return false;
661}
662
663//===----------------------------------------------------------------------===//
664// SDNodeInfo implementation
665//
666SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
667 EnumName = R->getValueAsString("Opcode");
668 SDClassName = R->getValueAsString("SDClass");
669 Record *TypeProfile = R->getValueAsDef("TypeProfile");
670 NumResults = TypeProfile->getValueAsInt("NumResults");
671 NumOperands = TypeProfile->getValueAsInt("NumOperands");
672
673 // Parse the properties.
674 Properties = 0;
675 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
676 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
677 if (PropList[i]->getName() == "SDNPCommutative") {
678 Properties |= 1 << SDNPCommutative;
679 } else if (PropList[i]->getName() == "SDNPAssociative") {
680 Properties |= 1 << SDNPAssociative;
681 } else if (PropList[i]->getName() == "SDNPHasChain") {
682 Properties |= 1 << SDNPHasChain;
683 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen874ae252009-06-02 03:12:52 +0000684 Properties |= 1 << SDNPOutFlag;
Chris Lattner6cefb772008-01-05 22:25:12 +0000685 } else if (PropList[i]->getName() == "SDNPInFlag") {
686 Properties |= 1 << SDNPInFlag;
687 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
688 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000689 } else if (PropList[i]->getName() == "SDNPMayStore") {
690 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000691 } else if (PropList[i]->getName() == "SDNPMayLoad") {
692 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000693 } else if (PropList[i]->getName() == "SDNPSideEffect") {
694 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000695 } else if (PropList[i]->getName() == "SDNPMemOperand") {
696 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000697 } else if (PropList[i]->getName() == "SDNPVariadic") {
698 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000699 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000700 errs() << "Unknown SD Node property '" << PropList[i]->getName()
701 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000702 exit(1);
703 }
704 }
705
706
707 // Parse the type constraints.
708 std::vector<Record*> ConstraintList =
709 TypeProfile->getValueAsListOfDefs("Constraints");
710 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
711}
712
Chris Lattner22579812010-02-28 00:22:30 +0000713/// getKnownType - If the type constraints on this node imply a fixed type
714/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000715/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +0000716MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +0000717 unsigned NumResults = getNumResults();
718 assert(NumResults <= 1 &&
719 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +0000720 assert(ResNo == 0 && "Only handles single result nodes so far");
Chris Lattner22579812010-02-28 00:22:30 +0000721
722 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
723 // Make sure that this applies to the correct node result.
724 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
725 continue;
726
727 switch (TypeConstraints[i].ConstraintType) {
728 default: break;
729 case SDTypeConstraint::SDTCisVT:
730 return TypeConstraints[i].x.SDTCisVT_Info.VT;
731 case SDTypeConstraint::SDTCisPtrTy:
732 return MVT::iPTR;
733 }
734 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000735 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000736}
737
Chris Lattner6cefb772008-01-05 22:25:12 +0000738//===----------------------------------------------------------------------===//
739// TreePatternNode implementation
740//
741
742TreePatternNode::~TreePatternNode() {
743#if 0 // FIXME: implement refcounted tree nodes!
744 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
745 delete getChild(i);
746#endif
747}
748
Chris Lattnerd7349192010-03-19 21:37:09 +0000749static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
750 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +0000751 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +0000752 return 0; // All return nothing.
753
Chris Lattner93dc92e2010-03-22 20:56:36 +0000754 if (Operator->isSubClassOf("Intrinsic"))
755 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Chris Lattner6cefb772008-01-05 22:25:12 +0000756
Chris Lattnerd7349192010-03-19 21:37:09 +0000757 if (Operator->isSubClassOf("SDNode"))
758 return CDP.getSDNodeInfo(Operator).getNumResults();
759
760 if (Operator->isSubClassOf("PatFrag")) {
761 // If we've already parsed this pattern fragment, get it. Otherwise, handle
762 // the forward reference case where one pattern fragment references another
763 // before it is processed.
764 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
765 return PFRec->getOnlyTree()->getNumTypes();
766
767 // Get the result tree.
768 DagInit *Tree = Operator->getValueAsDag("Fragment");
769 Record *Op = 0;
770 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
771 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
772 assert(Op && "Invalid Fragment");
773 return GetNumNodeResults(Op, CDP);
774 }
775
776 if (Operator->isSubClassOf("Instruction")) {
777 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +0000778
779 // FIXME: Should allow access to all the results here.
780 unsigned NumDefsToAdd = InstInfo.NumDefs ? 1 : 0;
Chris Lattnerd7349192010-03-19 21:37:09 +0000781
782 if (!InstInfo.ImplicitDefs.empty()) {
783 // Add on one implicit def if it has a resolvable type.
784 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
785 assert(FirstImplicitDef->isSubClassOf("Register"));
786 const std::vector<MVT::SimpleValueType> &RegVTs =
787 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
788 if (RegVTs.size() == 1)
Chris Lattner0be6fe72010-03-27 19:15:02 +0000789 return NumDefsToAdd+1;
Chris Lattnerd7349192010-03-19 21:37:09 +0000790 }
Chris Lattner0be6fe72010-03-27 19:15:02 +0000791 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +0000792 }
793
794 if (Operator->isSubClassOf("SDNodeXForm"))
795 return 1; // FIXME: Generalize SDNodeXForm
796
797 Operator->dump();
798 errs() << "Unhandled node in GetNumNodeResults\n";
799 exit(1);
800}
801
802void TreePatternNode::print(raw_ostream &OS) const {
803 if (isLeaf())
804 OS << *getLeafValue();
805 else
806 OS << '(' << getOperator()->getName();
807
808 for (unsigned i = 0, e = Types.size(); i != e; ++i)
809 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000810
811 if (!isLeaf()) {
812 if (getNumChildren() != 0) {
813 OS << " ";
814 getChild(0)->print(OS);
815 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
816 OS << ", ";
817 getChild(i)->print(OS);
818 }
819 }
820 OS << ")";
821 }
822
Dan Gohman0540e172008-10-15 06:17:21 +0000823 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
824 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000825 if (TransformFn)
826 OS << "<<X:" << TransformFn->getName() << ">>";
827 if (!getName().empty())
828 OS << ":$" << getName();
829
830}
831void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000832 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000833}
834
Scott Michel327d0652008-03-05 17:49:05 +0000835/// isIsomorphicTo - Return true if this node is recursively
836/// isomorphic to the specified node. For this comparison, the node's
837/// entire state is considered. The assigned name is ignored, since
838/// nodes with differing names are considered isomorphic. However, if
839/// the assigned name is present in the dependent variable set, then
840/// the assigned name is considered significant and the node is
841/// isomorphic if the names match.
842bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
843 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000844 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +0000845 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000846 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000847 getTransformFn() != N->getTransformFn())
848 return false;
849
850 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000851 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
852 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000853 return ((DI->getDef() == NDI->getDef())
854 && (DepVars.find(getName()) == DepVars.end()
855 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000856 }
857 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000858 return getLeafValue() == N->getLeafValue();
859 }
860
861 if (N->getOperator() != getOperator() ||
862 N->getNumChildren() != getNumChildren()) return false;
863 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000864 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000865 return false;
866 return true;
867}
868
869/// clone - Make a copy of this tree and all of its children.
870///
871TreePatternNode *TreePatternNode::clone() const {
872 TreePatternNode *New;
873 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +0000874 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000875 } else {
876 std::vector<TreePatternNode*> CChildren;
877 CChildren.reserve(Children.size());
878 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
879 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +0000880 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000881 }
882 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +0000883 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +0000884 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000885 New->setTransformFn(getTransformFn());
886 return New;
887}
888
Chris Lattner47661322010-02-14 22:22:58 +0000889/// RemoveAllTypes - Recursively strip all the types of this tree.
890void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +0000891 for (unsigned i = 0, e = Types.size(); i != e; ++i)
892 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +0000893 if (isLeaf()) return;
894 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
895 getChild(i)->RemoveAllTypes();
896}
897
898
Chris Lattner6cefb772008-01-05 22:25:12 +0000899/// SubstituteFormalArguments - Replace the formal arguments in this tree
900/// with actual values specified by ArgMap.
901void TreePatternNode::
902SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
903 if (isLeaf()) return;
904
905 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
906 TreePatternNode *Child = getChild(i);
907 if (Child->isLeaf()) {
908 Init *Val = Child->getLeafValue();
909 if (dynamic_cast<DefInit*>(Val) &&
910 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
911 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000912 TreePatternNode *NewChild = ArgMap[Child->getName()];
913 assert(NewChild && "Couldn't find formal argument!");
914 assert((Child->getPredicateFns().empty() ||
915 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
916 "Non-empty child predicate clobbered!");
917 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000918 }
919 } else {
920 getChild(i)->SubstituteFormalArguments(ArgMap);
921 }
922 }
923}
924
925
926/// InlinePatternFragments - If this pattern refers to any pattern
927/// fragments, inline them into place, giving us a pattern without any
928/// PatFrag references.
929TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
930 if (isLeaf()) return this; // nothing to do.
931 Record *Op = getOperator();
932
933 if (!Op->isSubClassOf("PatFrag")) {
934 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000935 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
936 TreePatternNode *Child = getChild(i);
937 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
938
939 assert((Child->getPredicateFns().empty() ||
940 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
941 "Non-empty child predicate clobbered!");
942
943 setChild(i, NewChild);
944 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000945 return this;
946 }
947
948 // Otherwise, we found a reference to a fragment. First, look up its
949 // TreePattern record.
950 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
951
952 // Verify that we are passing the right number of operands.
953 if (Frag->getNumArgs() != Children.size())
954 TP.error("'" + Op->getName() + "' fragment requires " +
955 utostr(Frag->getNumArgs()) + " operands!");
956
957 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
958
Dan Gohman0540e172008-10-15 06:17:21 +0000959 std::string Code = Op->getValueAsCode("Predicate");
960 if (!Code.empty())
961 FragTree->addPredicateFn("Predicate_"+Op->getName());
962
Chris Lattner6cefb772008-01-05 22:25:12 +0000963 // Resolve formal arguments to their actual value.
964 if (Frag->getNumArgs()) {
965 // Compute the map of formal to actual arguments.
966 std::map<std::string, TreePatternNode*> ArgMap;
967 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
968 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
969
970 FragTree->SubstituteFormalArguments(ArgMap);
971 }
972
973 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +0000974 for (unsigned i = 0, e = Types.size(); i != e; ++i)
975 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000976
977 // Transfer in the old predicates.
978 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
979 FragTree->addPredicateFn(getPredicateFns()[i]);
980
Chris Lattner6cefb772008-01-05 22:25:12 +0000981 // Get a new copy of this fragment to stitch into here.
982 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000983
984 // The fragment we inlined could have recursive inlining that is needed. See
985 // if there are any pattern fragments in it and inline them as needed.
986 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000987}
988
989/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000990/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +0000991/// references from the register file information, for example.
992///
Chris Lattnerd7349192010-03-19 21:37:09 +0000993static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
994 bool NotRegisters, TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000995 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +0000996 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +0000997 assert(ResNo == 0 && "Regclass ref only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +0000998 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000999 return EEVT::TypeSet(); // Unknown.
1000 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1001 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001002 }
1003
1004 if (R->isSubClassOf("PatFrag")) {
1005 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001006 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001007 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001008 }
1009
1010 if (R->isSubClassOf("Register")) {
1011 assert(ResNo == 0 && "Registers only produce one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001012 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001013 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001014 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001015 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001016 }
1017
1018 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1019 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001020 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001021 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001022 }
1023
1024 if (R->isSubClassOf("ComplexPattern")) {
1025 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001026 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001027 return EEVT::TypeSet(); // Unknown.
1028 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1029 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001030 }
1031 if (R->isSubClassOf("PointerLikeRegClass")) {
1032 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001033 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001034 }
1035
1036 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1037 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001038 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001039 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001040 }
1041
1042 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001043 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001044}
1045
Chris Lattnere67bde52008-01-06 05:36:50 +00001046
1047/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1048/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1049const CodeGenIntrinsic *TreePatternNode::
1050getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1051 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1052 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1053 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1054 return 0;
1055
1056 unsigned IID =
1057 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1058 return &CDP.getIntrinsicInfo(IID);
1059}
1060
Chris Lattner47661322010-02-14 22:22:58 +00001061/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1062/// return the ComplexPattern information, otherwise return null.
1063const ComplexPattern *
1064TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1065 if (!isLeaf()) return 0;
1066
1067 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1068 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1069 return &CGP.getComplexPattern(DI->getDef());
1070 return 0;
1071}
1072
1073/// NodeHasProperty - Return true if this node has the specified property.
1074bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001075 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001076 if (isLeaf()) {
1077 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1078 return CP->hasProperty(Property);
1079 return false;
1080 }
1081
1082 Record *Operator = getOperator();
1083 if (!Operator->isSubClassOf("SDNode")) return false;
1084
1085 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1086}
1087
1088
1089
1090
1091/// TreeHasProperty - Return true if any node in this tree has the specified
1092/// property.
1093bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001094 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001095 if (NodeHasProperty(Property, CGP))
1096 return true;
1097 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1098 if (getChild(i)->TreeHasProperty(Property, CGP))
1099 return true;
1100 return false;
1101}
1102
Evan Cheng6bd95672008-06-16 20:29:38 +00001103/// isCommutativeIntrinsic - Return true if the node corresponds to a
1104/// commutative intrinsic.
1105bool
1106TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1107 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1108 return Int->isCommutative;
1109 return false;
1110}
1111
Chris Lattnere67bde52008-01-06 05:36:50 +00001112
Bob Wilson6c01ca92009-01-05 17:23:09 +00001113/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001114/// this node and its children in the tree. This returns true if it makes a
1115/// change, false otherwise. If a type contradiction is found, throw an
1116/// exception.
1117bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001118 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001119 if (isLeaf()) {
1120 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1121 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001122 bool MadeChange = false;
1123 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1124 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1125 NotRegisters, TP), TP);
1126 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001127 }
1128
1129 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001130 assert(Types.size() == 1 && "Invalid IntInit");
Chris Lattner6cefb772008-01-05 22:25:12 +00001131
Chris Lattnerd7349192010-03-19 21:37:09 +00001132 // Int inits are always integers. :)
1133 bool MadeChange = Types[0].EnforceInteger(TP);
1134
1135 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001136 return MadeChange;
1137
Chris Lattnerd7349192010-03-19 21:37:09 +00001138 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001139 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1140 return MadeChange;
1141
1142 unsigned Size = EVT(VT).getSizeInBits();
1143 // Make sure that the value is representable for this type.
1144 if (Size >= 32) return MadeChange;
1145
1146 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1147 if (Val == II->getValue()) return MadeChange;
1148
1149 // If sign-extended doesn't fit, does it fit as unsigned?
1150 unsigned ValueMask;
1151 unsigned UnsignedVal;
1152 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1153 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001154
Chris Lattner2cacec52010-03-15 06:00:16 +00001155 if ((ValueMask & UnsignedVal) == UnsignedVal)
1156 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001157
Chris Lattner2cacec52010-03-15 06:00:16 +00001158 TP.error("Integer value '" + itostr(II->getValue())+
Chris Lattnerd7349192010-03-19 21:37:09 +00001159 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001160 return MadeChange;
1161 }
1162 return false;
1163 }
1164
1165 // special handling for set, which isn't really an SDNode.
1166 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001167 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1168 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001169 unsigned NC = getNumChildren();
Chris Lattnerd7349192010-03-19 21:37:09 +00001170
1171 TreePatternNode *SetVal = getChild(NC-1);
1172 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1173
Chris Lattner6cefb772008-01-05 22:25:12 +00001174 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001175 TreePatternNode *Child = getChild(i);
1176 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001177
1178 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001179 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1180 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001181 }
1182 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001183 }
1184
Chris Lattner310adf12010-03-27 02:53:27 +00001185 if (getOperator()->getName() == "implicit") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001186 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1187
Chris Lattner6cefb772008-01-05 22:25:12 +00001188 bool MadeChange = false;
1189 for (unsigned i = 0; i < getNumChildren(); ++i)
1190 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001191 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001192 }
1193
1194 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001195 bool MadeChange = false;
1196 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1197 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner2cacec52010-03-15 06:00:16 +00001198
Chris Lattnerd7349192010-03-19 21:37:09 +00001199 assert(getChild(0)->getNumTypes() == 1 &&
1200 getChild(1)->getNumTypes() == 1 && "Unhandled case");
1201
Chris Lattner2cacec52010-03-15 06:00:16 +00001202 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1203 // what type it gets, so if it didn't get a concrete type just give it the
1204 // first viable type from the reg class.
Chris Lattnerd7349192010-03-19 21:37:09 +00001205 if (!getChild(1)->hasTypeSet(0) &&
1206 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1207 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1208 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001209 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001210 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001211 }
1212
1213 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001214 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001215
Chris Lattner6cefb772008-01-05 22:25:12 +00001216 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001217 unsigned NumRetVTs = Int->IS.RetVTs.size();
1218 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Chris Lattnerd7349192010-03-19 21:37:09 +00001219
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001220 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001221 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001222
Chris Lattnerd7349192010-03-19 21:37:09 +00001223 if (getNumChildren() != NumParamVTs + 1)
Chris Lattnere67bde52008-01-06 05:36:50 +00001224 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001225 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001226 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001227
1228 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001229 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001230
Chris Lattnerd7349192010-03-19 21:37:09 +00001231 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1232 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1233
1234 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1235 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1236 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001237 }
1238 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001239 }
1240
1241 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001242 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1243
1244 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1245 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1246 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001247 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001248 }
1249
1250 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001251 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001252 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001253 CDP.getTargetInfo().getInstruction(getOperator());
Chris Lattner6c6ba362010-03-18 23:15:10 +00001254
Chris Lattner0be6fe72010-03-27 19:15:02 +00001255 bool MadeChange = false;
1256
1257 // Apply the result types to the node, these come from the things in the
1258 // (outs) list of the instruction.
1259 // FIXME: Cap at one result so far.
1260 unsigned NumResultsToAdd = InstInfo.NumDefs ? 1 : 0;
1261 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1262 Record *ResultNode = Inst.getResult(ResNo);
Chris Lattner6cefb772008-01-05 22:25:12 +00001263
Chris Lattnera938ac62009-07-29 20:43:05 +00001264 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001265 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001266 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001267 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001268 } else {
1269 assert(ResultNode->isSubClassOf("RegisterClass") &&
1270 "Operands should be register classes!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001271 const CodeGenRegisterClass &RC =
1272 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001273 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001274 }
Chris Lattner0be6fe72010-03-27 19:15:02 +00001275 }
1276
1277 // If the instruction has implicit defs, we apply the first one as a result.
1278 // FIXME: This sucks, it should apply all implicit defs.
1279 if (!InstInfo.ImplicitDefs.empty()) {
1280 unsigned ResNo = NumResultsToAdd;
1281
Chris Lattner6c6ba362010-03-18 23:15:10 +00001282 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
Chris Lattner92879532010-03-18 23:57:40 +00001283 assert(FirstImplicitDef->isSubClassOf("Register"));
Chris Lattner6c6ba362010-03-18 23:15:10 +00001284 const std::vector<MVT::SimpleValueType> &RegVTs =
1285 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
Chris Lattnerd7349192010-03-19 21:37:09 +00001286 if (RegVTs.size() == 1) // FIXME: Generalize.
Chris Lattner0be6fe72010-03-27 19:15:02 +00001287 MadeChange |= UpdateNodeType(ResNo, EEVT::TypeSet(RegVTs), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001288 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001289
1290 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1291 // be the same.
1292 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001293 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1294 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1295 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001296 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001297
1298 unsigned ChildNo = 0;
1299 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1300 Record *OperandNode = Inst.getOperand(i);
1301
1302 // If the instruction expects a predicate or optional def operand, we
1303 // codegen this by setting the operand to it's default value if it has a
1304 // non-empty DefaultOps field.
1305 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1306 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1307 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1308 continue;
1309
1310 // Verify that we didn't run out of provided operands.
1311 if (ChildNo >= getNumChildren())
1312 TP.error("Instruction '" + getOperator()->getName() +
1313 "' expects more operands than were provided.");
1314
Owen Anderson825b72b2009-08-11 20:47:22 +00001315 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001316 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001317 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Chris Lattnerd7349192010-03-19 21:37:09 +00001318
Chris Lattner6cefb772008-01-05 22:25:12 +00001319 if (OperandNode->isSubClassOf("RegisterClass")) {
1320 const CodeGenRegisterClass &RC =
1321 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001322 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001323 } else if (OperandNode->isSubClassOf("Operand")) {
1324 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattner0be6fe72010-03-27 19:15:02 +00001325 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001326 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001327 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001328 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001329 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001330 } else {
1331 assert(0 && "Unknown operand type!");
1332 abort();
1333 }
1334 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1335 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001336
Christopher Lamb02f69372008-03-10 04:16:09 +00001337 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001338 TP.error("Instruction '" + getOperator()->getName() +
1339 "' was provided too many operands!");
1340
1341 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001342 }
Chris Lattner6eb30122010-02-23 05:51:07 +00001343
1344 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1345
1346 // Node transforms always take one operand.
1347 if (getNumChildren() != 1)
1348 TP.error("Node transform '" + getOperator()->getName() +
1349 "' requires one operand!");
1350
Chris Lattner2cacec52010-03-15 06:00:16 +00001351 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1352
1353
Chris Lattner6eb30122010-02-23 05:51:07 +00001354 // If either the output or input of the xform does not have exact
1355 // type info. We assume they must be the same. Otherwise, it is perfectly
1356 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001357#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001358 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001359 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1360 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001361 return MadeChange;
1362 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001363#endif
1364 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001365}
1366
1367/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1368/// RHS of a commutative operation, not the on LHS.
1369static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1370 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1371 return true;
1372 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1373 return true;
1374 return false;
1375}
1376
1377
1378/// canPatternMatch - If it is impossible for this pattern to match on this
1379/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001380/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001381/// that can never possibly work), and to prevent the pattern permuter from
1382/// generating stuff that is useless.
1383bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001384 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001385 if (isLeaf()) return true;
1386
1387 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1388 if (!getChild(i)->canPatternMatch(Reason, CDP))
1389 return false;
1390
1391 // If this is an intrinsic, handle cases that would make it not match. For
1392 // example, if an operand is required to be an immediate.
1393 if (getOperator()->isSubClassOf("Intrinsic")) {
1394 // TODO:
1395 return true;
1396 }
1397
1398 // If this node is a commutative operator, check that the LHS isn't an
1399 // immediate.
1400 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001401 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1402 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001403 // Scan all of the operands of the node and make sure that only the last one
1404 // is a constant node, unless the RHS also is.
1405 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001406 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1407 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001408 if (OnlyOnRHSOfCommutative(getChild(i))) {
1409 Reason="Immediate value must be on the RHS of commutative operators!";
1410 return false;
1411 }
1412 }
1413 }
1414
1415 return true;
1416}
1417
1418//===----------------------------------------------------------------------===//
1419// TreePattern implementation
1420//
1421
1422TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001423 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001424 isInputPattern = isInput;
1425 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1426 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001427}
1428
1429TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001430 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001431 isInputPattern = isInput;
1432 Trees.push_back(ParseTreePattern(Pat));
1433}
1434
1435TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001436 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001437 isInputPattern = isInput;
1438 Trees.push_back(Pat);
1439}
1440
Chris Lattner6cefb772008-01-05 22:25:12 +00001441void TreePattern::error(const std::string &Msg) const {
1442 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001443 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001444}
1445
Chris Lattner2cacec52010-03-15 06:00:16 +00001446void TreePattern::ComputeNamedNodes() {
1447 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1448 ComputeNamedNodes(Trees[i]);
1449}
1450
1451void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1452 if (!N->getName().empty())
1453 NamedNodes[N->getName()].push_back(N);
1454
1455 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1456 ComputeNamedNodes(N->getChild(i));
1457}
1458
Chris Lattnerd7349192010-03-19 21:37:09 +00001459
Chris Lattner6cefb772008-01-05 22:25:12 +00001460TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1461 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1462 if (!OpDef) error("Pattern has unexpected operator type!");
1463 Record *Operator = OpDef->getDef();
1464
1465 if (Operator->isSubClassOf("ValueType")) {
1466 // If the operator is a ValueType, then this must be "type cast" of a leaf
1467 // node.
1468 if (Dag->getNumArgs() != 1)
1469 error("Type cast only takes one operand!");
1470
1471 Init *Arg = Dag->getArg(0);
1472 TreePatternNode *New;
1473 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1474 Record *R = DI->getDef();
1475 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001476 Dag->setArg(0, new DagInit(DI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001477 std::vector<std::pair<Init*, std::string> >()));
1478 return ParseTreePattern(Dag);
1479 }
Chris Lattner43e47542010-03-08 18:36:19 +00001480
1481 // Input argument?
1482 if (R->getName() == "node") {
1483 if (Dag->getArgName(0).empty())
1484 error("'node' argument requires a name to match with operand list");
1485 Args.push_back(Dag->getArgName(0));
1486 }
1487
Chris Lattnerd7349192010-03-19 21:37:09 +00001488 New = new TreePatternNode(DI, 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001489 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1490 New = ParseTreePattern(DI);
1491 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001492 New = new TreePatternNode(II, 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001493 if (!Dag->getArgName(0).empty())
1494 error("Constant int argument should not have a name!");
1495 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1496 // Turn this into an IntInit.
1497 Init *II = BI->convertInitializerTo(new IntRecTy());
1498 if (II == 0 || !dynamic_cast<IntInit*>(II))
1499 error("Bits value must be constants!");
1500
Chris Lattnerd7349192010-03-19 21:37:09 +00001501 New = new TreePatternNode(dynamic_cast<IntInit*>(II), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001502 if (!Dag->getArgName(0).empty())
1503 error("Constant int argument should not have a name!");
1504 } else {
1505 Arg->dump();
1506 error("Unknown leaf value for tree pattern!");
1507 return 0;
1508 }
1509
1510 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001511 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1512 New->UpdateNodeType(0, getValueType(Operator), *this);
Nate Begeman7cee8172009-03-19 05:21:56 +00001513 if (New->getNumChildren() == 0)
1514 New->setName(Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001515 return New;
1516 }
1517
1518 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001519 if (!Operator->isSubClassOf("PatFrag") &&
1520 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001521 !Operator->isSubClassOf("Instruction") &&
1522 !Operator->isSubClassOf("SDNodeXForm") &&
1523 !Operator->isSubClassOf("Intrinsic") &&
1524 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00001525 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00001526 error("Unrecognized node '" + Operator->getName() + "'!");
1527
1528 // Check to see if this is something that is illegal in an input pattern.
1529 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1530 Operator->isSubClassOf("SDNodeXForm")))
1531 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1532
1533 std::vector<TreePatternNode*> Children;
1534
1535 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1536 Init *Arg = Dag->getArg(i);
1537 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1538 Children.push_back(ParseTreePattern(DI));
1539 if (Children.back()->getName().empty())
1540 Children.back()->setName(Dag->getArgName(i));
1541 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1542 Record *R = DefI->getDef();
1543 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1544 // TreePatternNode if its own.
1545 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001546 Dag->setArg(i, new DagInit(DefI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001547 std::vector<std::pair<Init*, std::string> >()));
1548 --i; // Revisit this node...
1549 } else {
Chris Lattnerd7349192010-03-19 21:37:09 +00001550 TreePatternNode *Node = new TreePatternNode(DefI, 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001551 Node->setName(Dag->getArgName(i));
1552 Children.push_back(Node);
1553
1554 // Input argument?
1555 if (R->getName() == "node") {
1556 if (Dag->getArgName(i).empty())
1557 error("'node' argument requires a name to match with operand list");
1558 Args.push_back(Dag->getArgName(i));
1559 }
1560 }
1561 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001562 TreePatternNode *Node = new TreePatternNode(II, 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001563 if (!Dag->getArgName(i).empty())
1564 error("Constant int argument should not have a name!");
1565 Children.push_back(Node);
1566 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1567 // Turn this into an IntInit.
1568 Init *II = BI->convertInitializerTo(new IntRecTy());
1569 if (II == 0 || !dynamic_cast<IntInit*>(II))
1570 error("Bits value must be constants!");
1571
Chris Lattnerd7349192010-03-19 21:37:09 +00001572 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II),1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001573 if (!Dag->getArgName(i).empty())
1574 error("Constant int argument should not have a name!");
1575 Children.push_back(Node);
1576 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001577 errs() << '"';
Chris Lattner6cefb772008-01-05 22:25:12 +00001578 Arg->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001579 errs() << "\": ";
Chris Lattner6cefb772008-01-05 22:25:12 +00001580 error("Unknown leaf value for tree pattern!");
1581 }
1582 }
1583
1584 // If the operator is an intrinsic, then this is just syntactic sugar for for
1585 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1586 // convert the intrinsic name to a number.
1587 if (Operator->isSubClassOf("Intrinsic")) {
1588 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1589 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1590
1591 // If this intrinsic returns void, it must have side-effects and thus a
1592 // chain.
Chris Lattner93dc92e2010-03-22 20:56:36 +00001593 if (Int.IS.RetVTs.empty()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001594 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1595 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1596 // Has side-effects, requires chain.
1597 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1598 } else {
1599 // Otherwise, no chain.
1600 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1601 }
1602
Chris Lattnerd7349192010-03-19 21:37:09 +00001603 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001604 Children.insert(Children.begin(), IIDNode);
1605 }
1606
Chris Lattnerd7349192010-03-19 21:37:09 +00001607 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1608 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Nate Begeman7cee8172009-03-19 05:21:56 +00001609 Result->setName(Dag->getName());
1610 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001611}
1612
1613/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001614/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001615/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001616bool TreePattern::
1617InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1618 if (NamedNodes.empty())
1619 ComputeNamedNodes();
1620
Chris Lattner6cefb772008-01-05 22:25:12 +00001621 bool MadeChange = true;
1622 while (MadeChange) {
1623 MadeChange = false;
1624 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1625 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner2cacec52010-03-15 06:00:16 +00001626
1627 // If there are constraints on our named nodes, apply them.
1628 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1629 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1630 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1631
1632 // If we have input named node types, propagate their types to the named
1633 // values here.
1634 if (InNamedTypes) {
1635 // FIXME: Should be error?
1636 assert(InNamedTypes->count(I->getKey()) &&
1637 "Named node in output pattern but not input pattern?");
1638
1639 const SmallVectorImpl<TreePatternNode*> &InNodes =
1640 InNamedTypes->find(I->getKey())->second;
1641
1642 // The input types should be fully resolved by now.
1643 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1644 // If this node is a register class, and it is the root of the pattern
1645 // then we're mapping something onto an input register. We allow
1646 // changing the type of the input register in this case. This allows
1647 // us to match things like:
1648 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1649 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1650 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1651 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1652 continue;
1653 }
1654
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001655 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001656 InNodes[0]->getNumTypes() == 1 &&
1657 "FIXME: cannot name multiple result nodes yet");
1658 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1659 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001660 }
1661 }
1662
1663 // If there are multiple nodes with the same name, they must all have the
1664 // same type.
1665 if (I->second.size() > 1) {
1666 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001667 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001668 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001669 "FIXME: cannot name multiple result nodes yet");
1670
1671 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1672 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001673 }
1674 }
1675 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001676 }
1677
1678 bool HasUnresolvedTypes = false;
1679 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1680 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1681 return !HasUnresolvedTypes;
1682}
1683
Daniel Dunbar1a551802009-07-03 00:10:29 +00001684void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001685 OS << getRecord()->getName();
1686 if (!Args.empty()) {
1687 OS << "(" << Args[0];
1688 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1689 OS << ", " << Args[i];
1690 OS << ")";
1691 }
1692 OS << ": ";
1693
1694 if (Trees.size() > 1)
1695 OS << "[\n";
1696 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1697 OS << "\t";
1698 Trees[i]->print(OS);
1699 OS << "\n";
1700 }
1701
1702 if (Trees.size() > 1)
1703 OS << "]\n";
1704}
1705
Daniel Dunbar1a551802009-07-03 00:10:29 +00001706void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001707
1708//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001709// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001710//
1711
Chris Lattnerfe718932008-01-06 01:10:31 +00001712CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001713 Intrinsics = LoadIntrinsics(Records, false);
1714 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001715 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001716 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001717 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001718 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001719 ParseDefaultOperands();
1720 ParseInstructions();
1721 ParsePatterns();
1722
1723 // Generate variants. For example, commutative patterns can match
1724 // multiple ways. Add them to PatternsToMatch as well.
1725 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001726
1727 // Infer instruction flags. For example, we can detect loads,
1728 // stores, and side effects in many cases by examining an
1729 // instruction's pattern.
1730 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001731}
1732
Chris Lattnerfe718932008-01-06 01:10:31 +00001733CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001734 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001735 E = PatternFragments.end(); I != E; ++I)
1736 delete I->second;
1737}
1738
1739
Chris Lattnerfe718932008-01-06 01:10:31 +00001740Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001741 Record *N = Records.getDef(Name);
1742 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001743 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001744 exit(1);
1745 }
1746 return N;
1747}
1748
1749// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001750void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001751 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1752 while (!Nodes.empty()) {
1753 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1754 Nodes.pop_back();
1755 }
1756
Jim Grosbachda4231f2009-03-26 16:17:51 +00001757 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001758 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1759 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1760 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1761}
1762
1763/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1764/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001765void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001766 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1767 while (!Xforms.empty()) {
1768 Record *XFormNode = Xforms.back();
1769 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1770 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001771 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001772
1773 Xforms.pop_back();
1774 }
1775}
1776
Chris Lattnerfe718932008-01-06 01:10:31 +00001777void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001778 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1779 while (!AMs.empty()) {
1780 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1781 AMs.pop_back();
1782 }
1783}
1784
1785
1786/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1787/// file, building up the PatternFragments map. After we've collected them all,
1788/// inline fragments together as necessary, so that there are no references left
1789/// inside a pattern fragment to a pattern fragment.
1790///
Chris Lattnerfe718932008-01-06 01:10:31 +00001791void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001792 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1793
Chris Lattnerdc32f982008-01-05 22:43:57 +00001794 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001795 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1796 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1797 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1798 PatternFragments[Fragments[i]] = P;
1799
Chris Lattnerdc32f982008-01-05 22:43:57 +00001800 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001801 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001802 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001803
Chris Lattnerdc32f982008-01-05 22:43:57 +00001804 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001805 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1806
1807 // Parse the operands list.
1808 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1809 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1810 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001811 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001812 if (!OpsOp ||
1813 (OpsOp->getDef()->getName() != "ops" &&
1814 OpsOp->getDef()->getName() != "outs" &&
1815 OpsOp->getDef()->getName() != "ins"))
1816 P->error("Operands list should start with '(ops ... '!");
1817
1818 // Copy over the arguments.
1819 Args.clear();
1820 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1821 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1822 static_cast<DefInit*>(OpsList->getArg(j))->
1823 getDef()->getName() != "node")
1824 P->error("Operands list should all be 'node' values.");
1825 if (OpsList->getArgName(j).empty())
1826 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001827 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001828 P->error("'" + OpsList->getArgName(j) +
1829 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001830 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001831 Args.push_back(OpsList->getArgName(j));
1832 }
1833
Chris Lattnerdc32f982008-01-05 22:43:57 +00001834 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001835 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001836 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001837
Chris Lattnerdc32f982008-01-05 22:43:57 +00001838 // If there is a code init for this fragment, keep track of the fact that
1839 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001840 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001841 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001842 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001843
1844 // If there is a node transformation corresponding to this, keep track of
1845 // it.
1846 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1847 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1848 P->getOnlyTree()->setTransformFn(Transform);
1849 }
1850
Chris Lattner6cefb772008-01-05 22:25:12 +00001851 // Now that we've parsed all of the tree fragments, do a closure on them so
1852 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001853 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1854 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001855 ThePat->InlinePatternFragments();
1856
1857 // Infer as many types as possible. Don't worry about it if we don't infer
1858 // all of them, some may depend on the inputs of the pattern.
1859 try {
1860 ThePat->InferAllTypes();
1861 } catch (...) {
1862 // If this pattern fragment is not supported by this target (no types can
1863 // satisfy its constraints), just ignore it. If the bogus pattern is
1864 // actually used by instructions, the type consistency error will be
1865 // reported there.
1866 }
1867
1868 // If debugging, print out the pattern fragment result.
1869 DEBUG(ThePat->dump());
1870 }
1871}
1872
Chris Lattnerfe718932008-01-06 01:10:31 +00001873void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001874 std::vector<Record*> DefaultOps[2];
1875 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1876 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1877
1878 // Find some SDNode.
1879 assert(!SDNodes.empty() && "No SDNodes parsed?");
1880 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1881
1882 for (unsigned iter = 0; iter != 2; ++iter) {
1883 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1884 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1885
1886 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1887 // SomeSDnode so that we can parse this.
1888 std::vector<std::pair<Init*, std::string> > Ops;
1889 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1890 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1891 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001892 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001893
1894 // Create a TreePattern to parse this.
1895 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1896 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1897
1898 // Copy the operands over into a DAGDefaultOperand.
1899 DAGDefaultOperand DefaultOpInfo;
1900
1901 TreePatternNode *T = P.getTree(0);
1902 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1903 TreePatternNode *TPN = T->getChild(op);
1904 while (TPN->ApplyTypeConstraints(P, false))
1905 /* Resolve all types */;
1906
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001907 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001908 if (iter == 0)
1909 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001910 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00001911 else
1912 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001913 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001914 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001915 DefaultOpInfo.DefaultOps.push_back(TPN);
1916 }
1917
1918 // Insert it into the DefaultOperands map so we can find it later.
1919 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1920 }
1921 }
1922}
1923
1924/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1925/// instruction input. Return true if this is a real use.
1926static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1927 std::map<std::string, TreePatternNode*> &InstInputs,
1928 std::vector<Record*> &InstImpInputs) {
1929 // No name -> not interesting.
1930 if (Pat->getName().empty()) {
1931 if (Pat->isLeaf()) {
1932 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1933 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1934 I->error("Input " + DI->getDef()->getName() + " must be named!");
1935 else if (DI && DI->getDef()->isSubClassOf("Register"))
1936 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001937 }
1938 return false;
1939 }
1940
1941 Record *Rec;
1942 if (Pat->isLeaf()) {
1943 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1944 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1945 Rec = DI->getDef();
1946 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001947 Rec = Pat->getOperator();
1948 }
1949
1950 // SRCVALUE nodes are ignored.
1951 if (Rec->getName() == "srcvalue")
1952 return false;
1953
1954 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1955 if (!Slot) {
1956 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00001957 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00001958 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00001959 Record *SlotRec;
1960 if (Slot->isLeaf()) {
1961 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1962 } else {
1963 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1964 SlotRec = Slot->getOperator();
1965 }
1966
1967 // Ensure that the inputs agree if we've already seen this input.
1968 if (Rec != SlotRec)
1969 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00001970 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00001971 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00001972 return true;
1973}
1974
1975/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1976/// part of "I", the instruction), computing the set of inputs and outputs of
1977/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001978void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001979FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1980 std::map<std::string, TreePatternNode*> &InstInputs,
1981 std::map<std::string, TreePatternNode*>&InstResults,
1982 std::vector<Record*> &InstImpInputs,
1983 std::vector<Record*> &InstImpResults) {
1984 if (Pat->isLeaf()) {
1985 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1986 if (!isUse && Pat->getTransformFn())
1987 I->error("Cannot specify a transform function for a non-input value!");
1988 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001989 }
1990
1991 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001992 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1993 TreePatternNode *Dest = Pat->getChild(i);
1994 if (!Dest->isLeaf())
1995 I->error("implicitly defined value should be a register!");
1996
1997 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1998 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1999 I->error("implicitly defined value should be a register!");
2000 InstImpResults.push_back(Val->getDef());
2001 }
2002 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002003 }
2004
2005 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002006 // If this is not a set, verify that the children nodes are not void typed,
2007 // and recurse.
2008 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002009 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002010 I->error("Cannot have void nodes inside of patterns!");
2011 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2012 InstImpInputs, InstImpResults);
2013 }
2014
2015 // If this is a non-leaf node with no children, treat it basically as if
2016 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00002017 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002018
2019 if (!isUse && Pat->getTransformFn())
2020 I->error("Cannot specify a transform function for a non-input value!");
2021 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002022 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002023
2024 // Otherwise, this is a set, validate and collect instruction results.
2025 if (Pat->getNumChildren() == 0)
2026 I->error("set requires operands!");
2027
2028 if (Pat->getTransformFn())
2029 I->error("Cannot specify a transform function on a set node!");
2030
2031 // Check the set destinations.
2032 unsigned NumDests = Pat->getNumChildren()-1;
2033 for (unsigned i = 0; i != NumDests; ++i) {
2034 TreePatternNode *Dest = Pat->getChild(i);
2035 if (!Dest->isLeaf())
2036 I->error("set destination should be a register!");
2037
2038 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2039 if (!Val)
2040 I->error("set destination should be a register!");
2041
2042 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002043 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002044 if (Dest->getName().empty())
2045 I->error("set destination must have a name!");
2046 if (InstResults.count(Dest->getName()))
2047 I->error("cannot set '" + Dest->getName() +"' multiple times");
2048 InstResults[Dest->getName()] = Dest;
2049 } else if (Val->getDef()->isSubClassOf("Register")) {
2050 InstImpResults.push_back(Val->getDef());
2051 } else {
2052 I->error("set destination should be a register!");
2053 }
2054 }
2055
2056 // Verify and collect info from the computation.
2057 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2058 InstInputs, InstResults,
2059 InstImpInputs, InstImpResults);
2060}
2061
Dan Gohmanee4fa192008-04-03 00:02:49 +00002062//===----------------------------------------------------------------------===//
2063// Instruction Analysis
2064//===----------------------------------------------------------------------===//
2065
2066class InstAnalyzer {
2067 const CodeGenDAGPatterns &CDP;
2068 bool &mayStore;
2069 bool &mayLoad;
2070 bool &HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002071 bool &IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002072public:
2073 InstAnalyzer(const CodeGenDAGPatterns &cdp,
Chris Lattner1e506312010-03-19 05:34:15 +00002074 bool &maystore, bool &mayload, bool &hse, bool &isv)
2075 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
2076 IsVariadic(isv) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002077 }
2078
2079 /// Analyze - Analyze the specified instruction, returning true if the
2080 /// instruction had a pattern.
2081 bool Analyze(Record *InstRecord) {
2082 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2083 if (Pattern == 0) {
2084 HasSideEffects = 1;
2085 return false; // No pattern.
2086 }
2087
2088 // FIXME: Assume only the first tree is the pattern. The others are clobber
2089 // nodes.
2090 AnalyzeNode(Pattern->getTree(0));
2091 return true;
2092 }
2093
2094private:
2095 void AnalyzeNode(const TreePatternNode *N) {
2096 if (N->isLeaf()) {
2097 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2098 Record *LeafRec = DI->getDef();
2099 // Handle ComplexPattern leaves.
2100 if (LeafRec->isSubClassOf("ComplexPattern")) {
2101 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2102 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2103 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2104 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2105 }
2106 }
2107 return;
2108 }
2109
2110 // Analyze children.
2111 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2112 AnalyzeNode(N->getChild(i));
2113
2114 // Ignore set nodes, which are not SDNodes.
2115 if (N->getOperator()->getName() == "set")
2116 return;
2117
2118 // Get information about the SDNode for the operator.
2119 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2120
2121 // Notice properties of the node.
2122 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2123 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2124 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
Chris Lattner1e506312010-03-19 05:34:15 +00002125 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002126
2127 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2128 // If this is an intrinsic, analyze it.
2129 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2130 mayLoad = true;// These may load memory.
2131
2132 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2133 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2134
2135 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2136 // WriteMem intrinsics can have other strange effects.
2137 HasSideEffects = true;
2138 }
2139 }
2140
2141};
2142
2143static void InferFromPattern(const CodeGenInstruction &Inst,
2144 bool &MayStore, bool &MayLoad,
Chris Lattner1e506312010-03-19 05:34:15 +00002145 bool &HasSideEffects, bool &IsVariadic,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002146 const CodeGenDAGPatterns &CDP) {
Chris Lattner1e506312010-03-19 05:34:15 +00002147 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002148
2149 bool HadPattern =
Chris Lattner1e506312010-03-19 05:34:15 +00002150 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2151 .Analyze(Inst.TheDef);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002152
2153 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2154 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2155 // If we decided that this is a store from the pattern, then the .td file
2156 // entry is redundant.
2157 if (MayStore)
2158 fprintf(stderr,
2159 "Warning: mayStore flag explicitly set on instruction '%s'"
2160 " but flag already inferred from pattern.\n",
2161 Inst.TheDef->getName().c_str());
2162 MayStore = true;
2163 }
2164
2165 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2166 // If we decided that this is a load from the pattern, then the .td file
2167 // entry is redundant.
2168 if (MayLoad)
2169 fprintf(stderr,
2170 "Warning: mayLoad flag explicitly set on instruction '%s'"
2171 " but flag already inferred from pattern.\n",
2172 Inst.TheDef->getName().c_str());
2173 MayLoad = true;
2174 }
2175
2176 if (Inst.neverHasSideEffects) {
2177 if (HadPattern)
2178 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2179 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2180 HasSideEffects = false;
2181 }
2182
2183 if (Inst.hasSideEffects) {
2184 if (HasSideEffects)
2185 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2186 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2187 HasSideEffects = true;
2188 }
Chris Lattner1e506312010-03-19 05:34:15 +00002189
2190 if (Inst.isVariadic)
2191 IsVariadic = true; // Can warn if we want.
Dan Gohmanee4fa192008-04-03 00:02:49 +00002192}
2193
Chris Lattner6cefb772008-01-05 22:25:12 +00002194/// ParseInstructions - Parse all of the instructions, inlining and resolving
2195/// any fragments involved. This populates the Instructions list with fully
2196/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002197void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002198 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2199
2200 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2201 ListInit *LI = 0;
2202
2203 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2204 LI = Instrs[i]->getValueAsListInit("Pattern");
2205
2206 // If there is no pattern, only collect minimal information about the
2207 // instruction for its operand list. We have to assume that there is one
2208 // result, as we have no detailed info.
2209 if (!LI || LI->getSize() == 0) {
2210 std::vector<Record*> Results;
2211 std::vector<Record*> Operands;
2212
Chris Lattnerf30187a2010-03-19 00:07:20 +00002213 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002214
2215 if (InstInfo.OperandList.size() != 0) {
2216 if (InstInfo.NumDefs == 0) {
2217 // These produce no results
2218 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2219 Operands.push_back(InstInfo.OperandList[j].Rec);
2220 } else {
2221 // Assume the first operand is the result.
2222 Results.push_back(InstInfo.OperandList[0].Rec);
2223
2224 // The rest are inputs.
2225 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2226 Operands.push_back(InstInfo.OperandList[j].Rec);
2227 }
2228 }
2229
2230 // Create and insert the instruction.
2231 std::vector<Record*> ImpResults;
2232 std::vector<Record*> ImpOperands;
2233 Instructions.insert(std::make_pair(Instrs[i],
2234 DAGInstruction(0, Results, Operands, ImpResults,
2235 ImpOperands)));
2236 continue; // no pattern.
2237 }
2238
2239 // Parse the instruction.
2240 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2241 // Inline pattern fragments into it.
2242 I->InlinePatternFragments();
2243
2244 // Infer as many types as possible. If we cannot infer all of them, we can
2245 // never do anything with this instruction pattern: report it to the user.
2246 if (!I->InferAllTypes())
2247 I->error("Could not infer all types in pattern!");
2248
2249 // InstInputs - Keep track of all of the inputs of the instruction, along
2250 // with the record they are declared as.
2251 std::map<std::string, TreePatternNode*> InstInputs;
2252
2253 // InstResults - Keep track of all the virtual registers that are 'set'
2254 // in the instruction, including what reg class they are.
2255 std::map<std::string, TreePatternNode*> InstResults;
2256
2257 std::vector<Record*> InstImpInputs;
2258 std::vector<Record*> InstImpResults;
2259
2260 // Verify that the top-level forms in the instruction are of void type, and
2261 // fill in the InstResults map.
2262 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2263 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002264 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002265 I->error("Top-level forms in instruction pattern should have"
2266 " void types");
2267
2268 // Find inputs and outputs, and verify the structure of the uses/defs.
2269 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2270 InstImpInputs, InstImpResults);
2271 }
2272
2273 // Now that we have inputs and outputs of the pattern, inspect the operands
2274 // list for the instruction. This determines the order that operands are
2275 // added to the machine instruction the node corresponds to.
2276 unsigned NumResults = InstResults.size();
2277
2278 // Parse the operands list from the (ops) list, validating it.
2279 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002280 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002281
2282 // Check that all of the results occur first in the list.
2283 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002284 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002285 for (unsigned i = 0; i != NumResults; ++i) {
2286 if (i == CGI.OperandList.size())
2287 I->error("'" + InstResults.begin()->first +
2288 "' set but does not appear in operand list!");
2289 const std::string &OpName = CGI.OperandList[i].Name;
2290
2291 // Check that it exists in InstResults.
2292 TreePatternNode *RNode = InstResults[OpName];
2293 if (RNode == 0)
2294 I->error("Operand $" + OpName + " does not exist in operand list!");
2295
2296 if (i == 0)
2297 Res0Node = RNode;
2298 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2299 if (R == 0)
2300 I->error("Operand $" + OpName + " should be a set destination: all "
2301 "outputs must occur before inputs in operand list!");
2302
2303 if (CGI.OperandList[i].Rec != R)
2304 I->error("Operand $" + OpName + " class mismatch!");
2305
2306 // Remember the return type.
2307 Results.push_back(CGI.OperandList[i].Rec);
2308
2309 // Okay, this one checks out.
2310 InstResults.erase(OpName);
2311 }
2312
2313 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2314 // the copy while we're checking the inputs.
2315 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2316
2317 std::vector<TreePatternNode*> ResultNodeOperands;
2318 std::vector<Record*> Operands;
2319 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2320 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2321 const std::string &OpName = Op.Name;
2322 if (OpName.empty())
2323 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2324
2325 if (!InstInputsCheck.count(OpName)) {
2326 // If this is an predicate operand or optional def operand with an
2327 // DefaultOps set filled in, we can ignore this. When we codegen it,
2328 // we will do so as always executed.
2329 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2330 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2331 // Does it have a non-empty DefaultOps field? If so, ignore this
2332 // operand.
2333 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2334 continue;
2335 }
2336 I->error("Operand $" + OpName +
2337 " does not appear in the instruction pattern");
2338 }
2339 TreePatternNode *InVal = InstInputsCheck[OpName];
2340 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2341
2342 if (InVal->isLeaf() &&
2343 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2344 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2345 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2346 I->error("Operand $" + OpName + "'s register class disagrees"
2347 " between the operand and pattern");
2348 }
2349 Operands.push_back(Op.Rec);
2350
2351 // Construct the result for the dest-pattern operand list.
2352 TreePatternNode *OpNode = InVal->clone();
2353
2354 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002355 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00002356
2357 // Promote the xform function to be an explicit node if set.
2358 if (Record *Xform = OpNode->getTransformFn()) {
2359 OpNode->setTransformFn(0);
2360 std::vector<TreePatternNode*> Children;
2361 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002362 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002363 }
2364
2365 ResultNodeOperands.push_back(OpNode);
2366 }
2367
2368 if (!InstInputsCheck.empty())
2369 I->error("Input operand $" + InstInputsCheck.begin()->first +
2370 " occurs in pattern but not in operands list!");
2371
2372 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002373 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2374 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002375 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002376 for (unsigned i = 0; i != NumResults; ++i)
2377 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002378
2379 // Create and insert the instruction.
2380 // FIXME: InstImpResults and InstImpInputs should not be part of
2381 // DAGInstruction.
2382 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2383 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2384
2385 // Use a temporary tree pattern to infer all types and make sure that the
2386 // constructed result is correct. This depends on the instruction already
2387 // being inserted into the Instructions map.
2388 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002389 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002390
2391 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2392 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2393
2394 DEBUG(I->dump());
2395 }
2396
2397 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002398 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2399 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002400 E = Instructions.end(); II != E; ++II) {
2401 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002402 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002403 if (I == 0) continue; // No pattern.
2404
2405 // FIXME: Assume only the first tree is the pattern. The others are clobber
2406 // nodes.
2407 TreePatternNode *Pattern = I->getTree(0);
2408 TreePatternNode *SrcPattern;
2409 if (Pattern->getOperator()->getName() == "set") {
2410 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2411 } else{
2412 // Not a set (store or something?)
2413 SrcPattern = Pattern;
2414 }
2415
Chris Lattner6cefb772008-01-05 22:25:12 +00002416 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002417 AddPatternToMatch(I,
2418 PatternToMatch(Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002419 SrcPattern,
2420 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002421 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002422 Instr->getValueAsInt("AddedComplexity"),
2423 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002424 }
2425}
2426
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002427
2428typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2429
Chris Lattner967d54a2010-02-23 06:35:45 +00002430static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002431 std::map<std::string, NameRecord> &Names,
2432 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002433 if (!P->getName().empty()) {
2434 NameRecord &Rec = Names[P->getName()];
2435 // If this is the first instance of the name, remember the node.
2436 if (Rec.second++ == 0)
2437 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002438 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002439 PatternTop->error("repetition of value: $" + P->getName() +
2440 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002441 }
Chris Lattner967d54a2010-02-23 06:35:45 +00002442
2443 if (!P->isLeaf()) {
2444 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002445 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002446 }
2447}
2448
Chris Lattner25b6f912010-02-23 06:16:51 +00002449void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2450 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002451 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002452 std::string Reason;
2453 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002454 Pattern->error("Pattern can never match: " + Reason);
Chris Lattner25b6f912010-02-23 06:16:51 +00002455
Chris Lattner405f1252010-03-01 22:29:19 +00002456 // If the source pattern's root is a complex pattern, that complex pattern
2457 // must specify the nodes it can potentially match.
2458 if (const ComplexPattern *CP =
2459 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2460 if (CP->getRootNodes().empty())
2461 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2462 " could match");
2463
2464
Chris Lattner967d54a2010-02-23 06:35:45 +00002465 // Find all of the named values in the input and output, ensure they have the
2466 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002467 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002468 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2469 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002470
2471 // Scan all of the named values in the destination pattern, rejecting them if
2472 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002473 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002474 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002475 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002476 Pattern->error("Pattern has input without matching name in output: $" +
2477 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002478 }
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002479
2480 // Scan all of the named values in the source pattern, rejecting them if the
2481 // name isn't used in the dest, and isn't used to tie two values together.
2482 for (std::map<std::string, NameRecord>::iterator
2483 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2484 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2485 Pattern->error("Pattern has dead named input: $" + I->first);
2486
Chris Lattner25b6f912010-02-23 06:16:51 +00002487 PatternsToMatch.push_back(PTM);
2488}
2489
2490
Dan Gohmanee4fa192008-04-03 00:02:49 +00002491
2492void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002493 const std::vector<const CodeGenInstruction*> &Instructions =
2494 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002495 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2496 CodeGenInstruction &InstInfo =
2497 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002498 // Determine properties of the instruction from its pattern.
Chris Lattner1e506312010-03-19 05:34:15 +00002499 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2500 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2501 *this);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002502 InstInfo.mayStore = MayStore;
2503 InstInfo.mayLoad = MayLoad;
2504 InstInfo.hasSideEffects = HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002505 InstInfo.isVariadic = IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002506 }
2507}
2508
Chris Lattner2cacec52010-03-15 06:00:16 +00002509/// Given a pattern result with an unresolved type, see if we can find one
2510/// instruction with an unresolved result type. Force this result type to an
2511/// arbitrary element if it's possible types to converge results.
2512static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2513 if (N->isLeaf())
2514 return false;
2515
2516 // Analyze children.
2517 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2518 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2519 return true;
2520
2521 if (!N->getOperator()->isSubClassOf("Instruction"))
2522 return false;
2523
2524 // If this type is already concrete or completely unknown we can't do
2525 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00002526 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2527 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2528 continue;
Chris Lattner2cacec52010-03-15 06:00:16 +00002529
Chris Lattnerd7349192010-03-19 21:37:09 +00002530 // Otherwise, force its type to the first possibility (an arbitrary choice).
2531 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2532 return true;
2533 }
2534
2535 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00002536}
2537
Chris Lattnerfe718932008-01-06 01:10:31 +00002538void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002539 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2540
2541 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002542 Record *CurPattern = Patterns[i];
2543 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Chris Lattner310adf12010-03-27 02:53:27 +00002544 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002545
2546 // Inline pattern fragments into it.
2547 Pattern->InlinePatternFragments();
2548
Chris Lattnerd7349192010-03-19 21:37:09 +00002549 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00002550 if (LI->getSize() == 0) continue; // no pattern.
2551
2552 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00002553 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002554
2555 // Inline pattern fragments into it.
2556 Result->InlinePatternFragments();
2557
2558 if (Result->getNumTrees() != 1)
2559 Result->error("Cannot handle instructions producing instructions "
2560 "with temporaries yet!");
2561
2562 bool IterateInference;
2563 bool InferredAllPatternTypes, InferredAllResultTypes;
2564 do {
2565 // Infer as many types as possible. If we cannot infer all of them, we
2566 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002567 InferredAllPatternTypes =
2568 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002569
2570 // Infer as many types as possible. If we cannot infer all of them, we
2571 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002572 InferredAllResultTypes =
2573 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002574
Chris Lattner6c6ba362010-03-18 23:15:10 +00002575 IterateInference = false;
2576
Chris Lattner6cefb772008-01-05 22:25:12 +00002577 // Apply the type of the result to the source pattern. This helps us
2578 // resolve cases where the input type is known to be a pointer type (which
2579 // is considered resolved), but the result knows it needs to be 32- or
2580 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00002581 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2582 Pattern->getTree(0)->getNumTypes());
2583 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00002584 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002585 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002586 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002587 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002588 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002589
2590 // If our iteration has converged and the input pattern's types are fully
2591 // resolved but the result pattern is not fully resolved, we may have a
2592 // situation where we have two instructions in the result pattern and
2593 // the instructions require a common register class, but don't care about
2594 // what actual MVT is used. This is actually a bug in our modelling:
2595 // output patterns should have register classes, not MVTs.
2596 //
2597 // In any case, to handle this, we just go through and disambiguate some
2598 // arbitrary types to the result pattern's nodes.
2599 if (!IterateInference && InferredAllPatternTypes &&
2600 !InferredAllResultTypes)
2601 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2602 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002603 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002604
Chris Lattner6cefb772008-01-05 22:25:12 +00002605 // Verify that we inferred enough types that we can do something with the
2606 // pattern and result. If these fire the user has to add type casts.
2607 if (!InferredAllPatternTypes)
2608 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002609 if (!InferredAllResultTypes) {
2610 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002611 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002612 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002613
2614 // Validate that the input pattern is correct.
2615 std::map<std::string, TreePatternNode*> InstInputs;
2616 std::map<std::string, TreePatternNode*> InstResults;
2617 std::vector<Record*> InstImpInputs;
2618 std::vector<Record*> InstImpResults;
2619 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2620 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2621 InstInputs, InstResults,
2622 InstImpInputs, InstImpResults);
2623
2624 // Promote the xform function to be an explicit node if set.
2625 TreePatternNode *DstPattern = Result->getOnlyTree();
2626 std::vector<TreePatternNode*> ResultNodeOperands;
2627 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2628 TreePatternNode *OpNode = DstPattern->getChild(ii);
2629 if (Record *Xform = OpNode->getTransformFn()) {
2630 OpNode->setTransformFn(0);
2631 std::vector<TreePatternNode*> Children;
2632 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002633 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002634 }
2635 ResultNodeOperands.push_back(OpNode);
2636 }
2637 DstPattern = Result->getOnlyTree();
2638 if (!DstPattern->isLeaf())
2639 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00002640 ResultNodeOperands,
2641 DstPattern->getNumTypes());
2642
2643 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2644 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2645
Chris Lattner6cefb772008-01-05 22:25:12 +00002646 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2647 Temp.InferAllTypes();
2648
Chris Lattner6cefb772008-01-05 22:25:12 +00002649
Chris Lattner25b6f912010-02-23 06:16:51 +00002650 AddPatternToMatch(Pattern,
Chris Lattnerd7349192010-03-19 21:37:09 +00002651 PatternToMatch(CurPattern->getValueAsListInit("Predicates"),
2652 Pattern->getTree(0),
2653 Temp.getOnlyTree(), InstImpResults,
2654 CurPattern->getValueAsInt("AddedComplexity"),
2655 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002656 }
2657}
2658
2659/// CombineChildVariants - Given a bunch of permutations of each child of the
2660/// 'operator' node, put them together in all possible ways.
2661static void CombineChildVariants(TreePatternNode *Orig,
2662 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2663 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002664 CodeGenDAGPatterns &CDP,
2665 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002666 // Make sure that each operand has at least one variant to choose from.
2667 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2668 if (ChildVariants[i].empty())
2669 return;
2670
2671 // The end result is an all-pairs construction of the resultant pattern.
2672 std::vector<unsigned> Idxs;
2673 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002674 bool NotDone;
2675 do {
2676#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002677 DEBUG(if (!Idxs.empty()) {
2678 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2679 for (unsigned i = 0; i < Idxs.size(); ++i) {
2680 errs() << Idxs[i] << " ";
2681 }
2682 errs() << "]\n";
2683 });
Scott Michel327d0652008-03-05 17:49:05 +00002684#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002685 // Create the variant and add it to the output list.
2686 std::vector<TreePatternNode*> NewChildren;
2687 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2688 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00002689 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2690 Orig->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002691
2692 // Copy over properties.
2693 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002694 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002695 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00002696 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2697 R->setType(i, Orig->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002698
Scott Michel327d0652008-03-05 17:49:05 +00002699 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002700 std::string ErrString;
2701 if (!R->canPatternMatch(ErrString, CDP)) {
2702 delete R;
2703 } else {
2704 bool AlreadyExists = false;
2705
2706 // Scan to see if this pattern has already been emitted. We can get
2707 // duplication due to things like commuting:
2708 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2709 // which are the same pattern. Ignore the dups.
2710 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002711 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002712 AlreadyExists = true;
2713 break;
2714 }
2715
2716 if (AlreadyExists)
2717 delete R;
2718 else
2719 OutVariants.push_back(R);
2720 }
2721
Scott Michel327d0652008-03-05 17:49:05 +00002722 // Increment indices to the next permutation by incrementing the
2723 // indicies from last index backward, e.g., generate the sequence
2724 // [0, 0], [0, 1], [1, 0], [1, 1].
2725 int IdxsIdx;
2726 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2727 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2728 Idxs[IdxsIdx] = 0;
2729 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002730 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002731 }
Scott Michel327d0652008-03-05 17:49:05 +00002732 NotDone = (IdxsIdx >= 0);
2733 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002734}
2735
2736/// CombineChildVariants - A helper function for binary operators.
2737///
2738static void CombineChildVariants(TreePatternNode *Orig,
2739 const std::vector<TreePatternNode*> &LHS,
2740 const std::vector<TreePatternNode*> &RHS,
2741 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002742 CodeGenDAGPatterns &CDP,
2743 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002744 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2745 ChildVariants.push_back(LHS);
2746 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002747 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002748}
2749
2750
2751static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2752 std::vector<TreePatternNode *> &Children) {
2753 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2754 Record *Operator = N->getOperator();
2755
2756 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002757 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002758 N->getTransformFn()) {
2759 Children.push_back(N);
2760 return;
2761 }
2762
2763 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2764 Children.push_back(N->getChild(0));
2765 else
2766 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2767
2768 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2769 Children.push_back(N->getChild(1));
2770 else
2771 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2772}
2773
2774/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2775/// the (potentially recursive) pattern by using algebraic laws.
2776///
2777static void GenerateVariantsOf(TreePatternNode *N,
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 // We cannot permute leaves.
2782 if (N->isLeaf()) {
2783 OutVariants.push_back(N);
2784 return;
2785 }
2786
2787 // Look up interesting info about the node.
2788 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2789
Jim Grosbachda4231f2009-03-26 16:17:51 +00002790 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002791 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002792 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002793 std::vector<TreePatternNode*> MaximalChildren;
2794 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2795
2796 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2797 // permutations.
2798 if (MaximalChildren.size() == 3) {
2799 // Find the variants of all of our maximal children.
2800 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002801 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2802 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2803 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002804
2805 // There are only two ways we can permute the tree:
2806 // (A op B) op C and A op (B op C)
2807 // Within these forms, we can also permute A/B/C.
2808
2809 // Generate legal pair permutations of A/B/C.
2810 std::vector<TreePatternNode*> ABVariants;
2811 std::vector<TreePatternNode*> BAVariants;
2812 std::vector<TreePatternNode*> ACVariants;
2813 std::vector<TreePatternNode*> CAVariants;
2814 std::vector<TreePatternNode*> BCVariants;
2815 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002816 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2817 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2818 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2819 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2820 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2821 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002822
2823 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002824 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2825 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2826 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2827 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2828 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2829 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002830
2831 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002832 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2833 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2834 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2835 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2836 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2837 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002838 return;
2839 }
2840 }
2841
2842 // Compute permutations of all children.
2843 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2844 ChildVariants.resize(N->getNumChildren());
2845 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002846 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002847
2848 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002849 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002850
2851 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002852 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2853 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2854 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2855 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002856 // Don't count children which are actually register references.
2857 unsigned NC = 0;
2858 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2859 TreePatternNode *Child = N->getChild(i);
2860 if (Child->isLeaf())
2861 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2862 Record *RR = DI->getDef();
2863 if (RR->isSubClassOf("Register"))
2864 continue;
2865 }
2866 NC++;
2867 }
2868 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002869 if (isCommIntrinsic) {
2870 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2871 // operands are the commutative operands, and there might be more operands
2872 // after those.
2873 assert(NC >= 3 &&
2874 "Commutative intrinsic should have at least 3 childrean!");
2875 std::vector<std::vector<TreePatternNode*> > Variants;
2876 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2877 Variants.push_back(ChildVariants[2]);
2878 Variants.push_back(ChildVariants[1]);
2879 for (unsigned i = 3; i != NC; ++i)
2880 Variants.push_back(ChildVariants[i]);
2881 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2882 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002883 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002884 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002885 }
2886}
2887
2888
2889// GenerateVariants - Generate variants. For example, commutative patterns can
2890// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002891void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00002892 DEBUG(errs() << "Generating instruction variants.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002893
2894 // Loop over all of the patterns we've collected, checking to see if we can
2895 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002896 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002897 // the .td file having to contain tons of variants of instructions.
2898 //
2899 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2900 // intentionally do not reconsider these. Any variants of added patterns have
2901 // already been added.
2902 //
2903 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002904 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002905 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002906 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00002907 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00002908 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00002909 DEBUG(errs() << "\n");
Scott Michel327d0652008-03-05 17:49:05 +00002910 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002911
2912 assert(!Variants.empty() && "Must create at least original variant!");
2913 Variants.erase(Variants.begin()); // Remove the original pattern.
2914
2915 if (Variants.empty()) // No variants for this pattern.
2916 continue;
2917
Chris Lattner569f1212009-08-23 04:44:11 +00002918 DEBUG(errs() << "FOUND VARIANTS OF: ";
2919 PatternsToMatch[i].getSrcPattern()->dump();
2920 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002921
2922 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2923 TreePatternNode *Variant = Variants[v];
2924
Chris Lattner569f1212009-08-23 04:44:11 +00002925 DEBUG(errs() << " VAR#" << v << ": ";
2926 Variant->dump();
2927 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002928
2929 // Scan to see if an instruction or explicit pattern already matches this.
2930 bool AlreadyExists = false;
2931 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00002932 // Skip if the top level predicates do not match.
2933 if (PatternsToMatch[i].getPredicates() !=
2934 PatternsToMatch[p].getPredicates())
2935 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00002936 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002937 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00002938 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002939 AlreadyExists = true;
2940 break;
2941 }
2942 }
2943 // If we already have it, ignore the variant.
2944 if (AlreadyExists) continue;
2945
2946 // Otherwise, add it to the list of patterns we have.
2947 PatternsToMatch.
2948 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2949 Variant, PatternsToMatch[i].getDstPattern(),
2950 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002951 PatternsToMatch[i].getAddedComplexity(),
2952 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002953 }
2954
Chris Lattner569f1212009-08-23 04:44:11 +00002955 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002956 }
2957}
2958