Bug Summary

File:utils/TableGen/CodeGenDAGPatterns.cpp
Warning:line 3056, column 11
Called C++ object pointer is null

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp

1//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
2//
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//
10// This file implements the CodeGenDAGPatterns class, which is used to read and
11// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CodeGenDAGPatterns.h"
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/StringMap.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/ErrorHandling.h"
25#include "llvm/TableGen/Error.h"
26#include "llvm/TableGen/Record.h"
27#include <algorithm>
28#include <cstdio>
29#include <set>
30using namespace llvm;
31
32#define DEBUG_TYPE"dag-patterns" "dag-patterns"
33
34static inline bool isIntegerOrPtr(MVT VT) {
35 return VT.isInteger() || VT == MVT::iPTR;
36}
37static inline bool isFloatingPoint(MVT VT) {
38 return VT.isFloatingPoint();
39}
40static inline bool isVector(MVT VT) {
41 return VT.isVector();
42}
43static inline bool isScalar(MVT VT) {
44 return !VT.isVector();
45}
46
47template <typename Predicate>
48static bool berase_if(MachineValueTypeSet &S, Predicate P) {
49 bool Erased = false;
50 // It is ok to iterate over MachineValueTypeSet and remove elements from it
51 // at the same time.
52 for (MVT T : S) {
53 if (!P(T))
54 continue;
55 Erased = true;
56 S.erase(T);
57 }
58 return Erased;
59}
60
61// --- TypeSetByHwMode
62
63// This is a parameterized type-set class. For each mode there is a list
64// of types that are currently possible for a given tree node. Type
65// inference will apply to each mode separately.
66
67TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
68 for (const ValueTypeByHwMode &VVT : VTList)
69 insert(VVT);
70}
71
72bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
73 for (const auto &I : *this) {
74 if (I.second.size() > 1)
75 return false;
76 if (!AllowEmpty && I.second.empty())
77 return false;
78 }
79 return true;
80}
81
82ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
83 assert(isValueTypeByHwMode(true) &&(static_cast <bool> (isValueTypeByHwMode(true) &&
"The type set has multiple types for at least one HW mode") ?
void (0) : __assert_fail ("isValueTypeByHwMode(true) && \"The type set has multiple types for at least one HW mode\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 84, __extension__ __PRETTY_FUNCTION__))
84 "The type set has multiple types for at least one HW mode")(static_cast <bool> (isValueTypeByHwMode(true) &&
"The type set has multiple types for at least one HW mode") ?
void (0) : __assert_fail ("isValueTypeByHwMode(true) && \"The type set has multiple types for at least one HW mode\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 84, __extension__ __PRETTY_FUNCTION__))
;
85 ValueTypeByHwMode VVT;
86 for (const auto &I : *this) {
87 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
88 VVT.getOrCreateTypeForMode(I.first, T);
89 }
90 return VVT;
91}
92
93bool TypeSetByHwMode::isPossible() const {
94 for (const auto &I : *this)
95 if (!I.second.empty())
96 return true;
97 return false;
98}
99
100bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
101 bool Changed = false;
102 SmallDenseSet<unsigned, 4> Modes;
103 for (const auto &P : VVT) {
104 unsigned M = P.first;
105 Modes.insert(M);
106 // Make sure there exists a set for each specific mode from VVT.
107 Changed |= getOrCreate(M).insert(P.second).second;
108 }
109
110 // If VVT has a default mode, add the corresponding type to all
111 // modes in "this" that do not exist in VVT.
112 if (Modes.count(DefaultMode)) {
113 MVT DT = VVT.getType(DefaultMode);
114 for (auto &I : *this)
115 if (!Modes.count(I.first))
116 Changed |= I.second.insert(DT).second;
117 }
118 return Changed;
119}
120
121// Constrain the type set to be the intersection with VTS.
122bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
123 bool Changed = false;
124 if (hasDefault()) {
125 for (const auto &I : VTS) {
126 unsigned M = I.first;
127 if (M == DefaultMode || hasMode(M))
128 continue;
129 Map.insert({M, Map.at(DefaultMode)});
130 Changed = true;
131 }
132 }
133
134 for (auto &I : *this) {
135 unsigned M = I.first;
136 SetType &S = I.second;
137 if (VTS.hasMode(M) || VTS.hasDefault()) {
138 Changed |= intersect(I.second, VTS.get(M));
139 } else if (!S.empty()) {
140 S.clear();
141 Changed = true;
142 }
143 }
144 return Changed;
145}
146
147template <typename Predicate>
148bool TypeSetByHwMode::constrain(Predicate P) {
149 bool Changed = false;
150 for (auto &I : *this)
151 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
152 return Changed;
153}
154
155template <typename Predicate>
156bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
157 assert(empty())(static_cast <bool> (empty()) ? void (0) : __assert_fail
("empty()", "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 157, __extension__ __PRETTY_FUNCTION__))
;
158 for (const auto &I : VTS) {
159 SetType &S = getOrCreate(I.first);
160 for (auto J : I.second)
161 if (P(J))
162 S.insert(J);
163 }
164 return !empty();
165}
166
167void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
168 SmallVector<unsigned, 4> Modes;
169 Modes.reserve(Map.size());
170
171 for (const auto &I : *this)
172 Modes.push_back(I.first);
173 if (Modes.empty()) {
174 OS << "{}";
175 return;
176 }
177 array_pod_sort(Modes.begin(), Modes.end());
178
179 OS << '{';
180 for (unsigned M : Modes) {
181 OS << ' ' << getModeName(M) << ':';
182 writeToStream(get(M), OS);
183 }
184 OS << " }";
185}
186
187void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
188 SmallVector<MVT, 4> Types(S.begin(), S.end());
189 array_pod_sort(Types.begin(), Types.end());
190
191 OS << '[';
192 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
193 OS << ValueTypeByHwMode::getMVTName(Types[i]);
194 if (i != e-1)
195 OS << ' ';
196 }
197 OS << ']';
198}
199
200bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
201 bool HaveDefault = hasDefault();
202 if (HaveDefault != VTS.hasDefault())
203 return false;
204
205 if (isSimple()) {
206 if (VTS.isSimple())
207 return *begin() == *VTS.begin();
208 return false;
209 }
210
211 SmallDenseSet<unsigned, 4> Modes;
212 for (auto &I : *this)
213 Modes.insert(I.first);
214 for (const auto &I : VTS)
215 Modes.insert(I.first);
216
217 if (HaveDefault) {
218 // Both sets have default mode.
219 for (unsigned M : Modes) {
220 if (get(M) != VTS.get(M))
221 return false;
222 }
223 } else {
224 // Neither set has default mode.
225 for (unsigned M : Modes) {
226 // If there is no default mode, an empty set is equivalent to not having
227 // the corresponding mode.
228 bool NoModeThis = !hasMode(M) || get(M).empty();
229 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
230 if (NoModeThis != NoModeVTS)
231 return false;
232 if (!NoModeThis)
233 if (get(M) != VTS.get(M))
234 return false;
235 }
236 }
237
238 return true;
239}
240
241namespace llvm {
242 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
243 T.writeToStream(OS);
244 return OS;
245 }
246}
247
248LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__))
249void TypeSetByHwMode::dump() const {
250 dbgs() << *this << '\n';
251}
252
253bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
254 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
255 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
256
257 if (OutP == InP)
258 return berase_if(Out, Int);
259
260 // Compute the intersection of scalars separately to account for only
261 // one set containing iPTR.
262 // The itersection of iPTR with a set of integer scalar types that does not
263 // include iPTR will result in the most specific scalar type:
264 // - iPTR is more specific than any set with two elements or more
265 // - iPTR is less specific than any single integer scalar type.
266 // For example
267 // { iPTR } * { i32 } -> { i32 }
268 // { iPTR } * { i32 i64 } -> { iPTR }
269 // and
270 // { iPTR i32 } * { i32 } -> { i32 }
271 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
272 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
273
274 // Compute the difference between the two sets in such a way that the
275 // iPTR is in the set that is being subtracted. This is to see if there
276 // are any extra scalars in the set without iPTR that are not in the
277 // set containing iPTR. Then the iPTR could be considered a "wildcard"
278 // matching these scalars. If there is only one such scalar, it would
279 // replace the iPTR, if there are more, the iPTR would be retained.
280 SetType Diff;
281 if (InP) {
282 Diff = Out;
283 berase_if(Diff, [&In](MVT T) { return In.count(T); });
284 // Pre-remove these elements and rely only on InP/OutP to determine
285 // whether a change has been made.
286 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
287 } else {
288 Diff = In;
289 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
290 Out.erase(MVT::iPTR);
291 }
292
293 // The actual intersection.
294 bool Changed = berase_if(Out, Int);
295 unsigned NumD = Diff.size();
296 if (NumD == 0)
297 return Changed;
298
299 if (NumD == 1) {
300 Out.insert(*Diff.begin());
301 // This is a change only if Out was the one with iPTR (which is now
302 // being replaced).
303 Changed |= OutP;
304 } else {
305 // Multiple elements from Out are now replaced with iPTR.
306 Out.insert(MVT::iPTR);
307 Changed |= !OutP;
308 }
309 return Changed;
310}
311
312void TypeSetByHwMode::validate() const {
313#ifndef NDEBUG
314 if (empty())
315 return;
316 bool AllEmpty = true;
317 for (const auto &I : *this)
318 AllEmpty &= I.second.empty();
319 assert(!AllEmpty &&(static_cast <bool> (!AllEmpty && "type set is empty for each HW mode: type contradiction?"
) ? void (0) : __assert_fail ("!AllEmpty && \"type set is empty for each HW mode: type contradiction?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 320, __extension__ __PRETTY_FUNCTION__))
320 "type set is empty for each HW mode: type contradiction?")(static_cast <bool> (!AllEmpty && "type set is empty for each HW mode: type contradiction?"
) ? void (0) : __assert_fail ("!AllEmpty && \"type set is empty for each HW mode: type contradiction?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 320, __extension__ __PRETTY_FUNCTION__))
;
321#endif
322}
323
324// --- TypeInfer
325
326bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
327 const TypeSetByHwMode &In) {
328 ValidateOnExit _1(Out);
329 In.validate();
330 if (In.empty() || Out == In || TP.hasError())
331 return false;
332 if (Out.empty()) {
333 Out = In;
334 return true;
335 }
336
337 bool Changed = Out.constrain(In);
338 if (Changed && Out.empty())
339 TP.error("Type contradiction");
340
341 return Changed;
342}
343
344bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
345 ValidateOnExit _1(Out);
346 if (TP.hasError())
347 return false;
348 assert(!Out.empty() && "cannot pick from an empty set")(static_cast <bool> (!Out.empty() && "cannot pick from an empty set"
) ? void (0) : __assert_fail ("!Out.empty() && \"cannot pick from an empty set\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 348, __extension__ __PRETTY_FUNCTION__))
;
349
350 bool Changed = false;
351 for (auto &I : Out) {
352 TypeSetByHwMode::SetType &S = I.second;
353 if (S.size() <= 1)
354 continue;
355 MVT T = *S.begin(); // Pick the first element.
356 S.clear();
357 S.insert(T);
358 Changed = true;
359 }
360 return Changed;
361}
362
363bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
364 ValidateOnExit _1(Out);
365 if (TP.hasError())
366 return false;
367 if (!Out.empty())
368 return Out.constrain(isIntegerOrPtr);
369
370 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
371}
372
373bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
374 ValidateOnExit _1(Out);
375 if (TP.hasError())
376 return false;
377 if (!Out.empty())
378 return Out.constrain(isFloatingPoint);
379
380 return Out.assign_if(getLegalTypes(), isFloatingPoint);
381}
382
383bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
384 ValidateOnExit _1(Out);
385 if (TP.hasError())
386 return false;
387 if (!Out.empty())
388 return Out.constrain(isScalar);
389
390 return Out.assign_if(getLegalTypes(), isScalar);
391}
392
393bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
394 ValidateOnExit _1(Out);
395 if (TP.hasError())
396 return false;
397 if (!Out.empty())
398 return Out.constrain(isVector);
399
400 return Out.assign_if(getLegalTypes(), isVector);
401}
402
403bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
404 ValidateOnExit _1(Out);
405 if (TP.hasError() || !Out.empty())
406 return false;
407
408 Out = getLegalTypes();
409 return true;
410}
411
412template <typename Iter, typename Pred, typename Less>
413static Iter min_if(Iter B, Iter E, Pred P, Less L) {
414 if (B == E)
415 return E;
416 Iter Min = E;
417 for (Iter I = B; I != E; ++I) {
418 if (!P(*I))
419 continue;
420 if (Min == E || L(*I, *Min))
421 Min = I;
422 }
423 return Min;
424}
425
426template <typename Iter, typename Pred, typename Less>
427static Iter max_if(Iter B, Iter E, Pred P, Less L) {
428 if (B == E)
429 return E;
430 Iter Max = E;
431 for (Iter I = B; I != E; ++I) {
432 if (!P(*I))
433 continue;
434 if (Max == E || L(*Max, *I))
435 Max = I;
436 }
437 return Max;
438}
439
440/// Make sure that for each type in Small, there exists a larger type in Big.
441bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
442 TypeSetByHwMode &Big) {
443 ValidateOnExit _1(Small), _2(Big);
444 if (TP.hasError())
445 return false;
446 bool Changed = false;
447
448 if (Small.empty())
449 Changed |= EnforceAny(Small);
450 if (Big.empty())
451 Changed |= EnforceAny(Big);
452
453 assert(Small.hasDefault() && Big.hasDefault())(static_cast <bool> (Small.hasDefault() && Big.
hasDefault()) ? void (0) : __assert_fail ("Small.hasDefault() && Big.hasDefault()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 453, __extension__ __PRETTY_FUNCTION__))
;
454
455 std::vector<unsigned> Modes = union_modes(Small, Big);
456
457 // 1. Only allow integer or floating point types and make sure that
458 // both sides are both integer or both floating point.
459 // 2. Make sure that either both sides have vector types, or neither
460 // of them does.
461 for (unsigned M : Modes) {
462 TypeSetByHwMode::SetType &S = Small.get(M);
463 TypeSetByHwMode::SetType &B = Big.get(M);
464
465 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
466 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
467 Changed |= berase_if(S, NotInt) |
468 berase_if(B, NotInt);
469 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
470 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
471 Changed |= berase_if(S, NotFP) |
472 berase_if(B, NotFP);
473 } else if (S.empty() || B.empty()) {
474 Changed = !S.empty() || !B.empty();
475 S.clear();
476 B.clear();
477 } else {
478 TP.error("Incompatible types");
479 return Changed;
480 }
481
482 if (none_of(S, isVector) || none_of(B, isVector)) {
483 Changed |= berase_if(S, isVector) |
484 berase_if(B, isVector);
485 }
486 }
487
488 auto LT = [](MVT A, MVT B) -> bool {
489 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
490 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
491 A.getSizeInBits() < B.getSizeInBits());
492 };
493 auto LE = [](MVT A, MVT B) -> bool {
494 // This function is used when removing elements: when a vector is compared
495 // to a non-vector, it should return false (to avoid removal).
496 if (A.isVector() != B.isVector())
497 return false;
498
499 // Note on the < comparison below:
500 // X86 has patterns like
501 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
502 // where the truncated vector is given a type v16i8, while the source
503 // vector has type v4i32. They both have the same size in bits.
504 // The minimal type in the result is obviously v16i8, and when we remove
505 // all types from the source that are smaller-or-equal than v8i16, the
506 // only source type would also be removed (since it's equal in size).
507 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
508 A.getSizeInBits() < B.getSizeInBits();
509 };
510
511 for (unsigned M : Modes) {
512 TypeSetByHwMode::SetType &S = Small.get(M);
513 TypeSetByHwMode::SetType &B = Big.get(M);
514 // MinS = min scalar in Small, remove all scalars from Big that are
515 // smaller-or-equal than MinS.
516 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
517 if (MinS != S.end())
518 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
519
520 // MaxS = max scalar in Big, remove all scalars from Small that are
521 // larger than MaxS.
522 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
523 if (MaxS != B.end())
524 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
525
526 // MinV = min vector in Small, remove all vectors from Big that are
527 // smaller-or-equal than MinV.
528 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
529 if (MinV != S.end())
530 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
531
532 // MaxV = max vector in Big, remove all vectors from Small that are
533 // larger than MaxV.
534 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
535 if (MaxV != B.end())
536 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
537 }
538
539 return Changed;
540}
541
542/// 1. Ensure that for each type T in Vec, T is a vector type, and that
543/// for each type U in Elem, U is a scalar type.
544/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
545/// type T in Vec, such that U is the element type of T.
546bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
547 TypeSetByHwMode &Elem) {
548 ValidateOnExit _1(Vec), _2(Elem);
549 if (TP.hasError())
550 return false;
551 bool Changed = false;
552
553 if (Vec.empty())
554 Changed |= EnforceVector(Vec);
555 if (Elem.empty())
556 Changed |= EnforceScalar(Elem);
557
558 for (unsigned M : union_modes(Vec, Elem)) {
559 TypeSetByHwMode::SetType &V = Vec.get(M);
560 TypeSetByHwMode::SetType &E = Elem.get(M);
561
562 Changed |= berase_if(V, isScalar); // Scalar = !vector
563 Changed |= berase_if(E, isVector); // Vector = !scalar
564 assert(!V.empty() && !E.empty())(static_cast <bool> (!V.empty() && !E.empty()) ?
void (0) : __assert_fail ("!V.empty() && !E.empty()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 564, __extension__ __PRETTY_FUNCTION__))
;
565
566 SmallSet<MVT,4> VT, ST;
567 // Collect element types from the "vector" set.
568 for (MVT T : V)
569 VT.insert(T.getVectorElementType());
570 // Collect scalar types from the "element" set.
571 for (MVT T : E)
572 ST.insert(T);
573
574 // Remove from V all (vector) types whose element type is not in S.
575 Changed |= berase_if(V, [&ST](MVT T) -> bool {
576 return !ST.count(T.getVectorElementType());
577 });
578 // Remove from E all (scalar) types, for which there is no corresponding
579 // type in V.
580 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
581 }
582
583 return Changed;
584}
585
586bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
587 const ValueTypeByHwMode &VVT) {
588 TypeSetByHwMode Tmp(VVT);
589 ValidateOnExit _1(Vec), _2(Tmp);
590 return EnforceVectorEltTypeIs(Vec, Tmp);
591}
592
593/// Ensure that for each type T in Sub, T is a vector type, and there
594/// exists a type U in Vec such that U is a vector type with the same
595/// element type as T and at least as many elements as T.
596bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
597 TypeSetByHwMode &Sub) {
598 ValidateOnExit _1(Vec), _2(Sub);
599 if (TP.hasError())
600 return false;
601
602 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
603 auto IsSubVec = [](MVT B, MVT P) -> bool {
604 if (!B.isVector() || !P.isVector())
605 return false;
606 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
607 // but until there are obvious use-cases for this, keep the
608 // types separate.
609 if (B.isScalableVector() != P.isScalableVector())
610 return false;
611 if (B.getVectorElementType() != P.getVectorElementType())
612 return false;
613 return B.getVectorNumElements() < P.getVectorNumElements();
614 };
615
616 /// Return true if S has no element (vector type) that T is a sub-vector of,
617 /// i.e. has the same element type as T and more elements.
618 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
619 for (const auto &I : S)
620 if (IsSubVec(T, I))
621 return false;
622 return true;
623 };
624
625 /// Return true if S has no element (vector type) that T is a super-vector
626 /// of, i.e. has the same element type as T and fewer elements.
627 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
628 for (const auto &I : S)
629 if (IsSubVec(I, T))
630 return false;
631 return true;
632 };
633
634 bool Changed = false;
635
636 if (Vec.empty())
637 Changed |= EnforceVector(Vec);
638 if (Sub.empty())
639 Changed |= EnforceVector(Sub);
640
641 for (unsigned M : union_modes(Vec, Sub)) {
642 TypeSetByHwMode::SetType &S = Sub.get(M);
643 TypeSetByHwMode::SetType &V = Vec.get(M);
644
645 Changed |= berase_if(S, isScalar);
646
647 // Erase all types from S that are not sub-vectors of a type in V.
648 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
649
650 // Erase all types from V that are not super-vectors of a type in S.
651 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
652 }
653
654 return Changed;
655}
656
657/// 1. Ensure that V has a scalar type iff W has a scalar type.
658/// 2. Ensure that for each vector type T in V, there exists a vector
659/// type U in W, such that T and U have the same number of elements.
660/// 3. Ensure that for each vector type U in W, there exists a vector
661/// type T in V, such that T and U have the same number of elements
662/// (reverse of 2).
663bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
664 ValidateOnExit _1(V), _2(W);
665 if (TP.hasError())
666 return false;
667
668 bool Changed = false;
669 if (V.empty())
670 Changed |= EnforceAny(V);
671 if (W.empty())
672 Changed |= EnforceAny(W);
673
674 // An actual vector type cannot have 0 elements, so we can treat scalars
675 // as zero-length vectors. This way both vectors and scalars can be
676 // processed identically.
677 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
678 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
679 };
680
681 for (unsigned M : union_modes(V, W)) {
682 TypeSetByHwMode::SetType &VS = V.get(M);
683 TypeSetByHwMode::SetType &WS = W.get(M);
684
685 SmallSet<unsigned,2> VN, WN;
686 for (MVT T : VS)
687 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
688 for (MVT T : WS)
689 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
690
691 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
692 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
693 }
694 return Changed;
695}
696
697/// 1. Ensure that for each type T in A, there exists a type U in B,
698/// such that T and U have equal size in bits.
699/// 2. Ensure that for each type U in B, there exists a type T in A
700/// such that T and U have equal size in bits (reverse of 1).
701bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
702 ValidateOnExit _1(A), _2(B);
703 if (TP.hasError())
704 return false;
705 bool Changed = false;
706 if (A.empty())
707 Changed |= EnforceAny(A);
708 if (B.empty())
709 Changed |= EnforceAny(B);
710
711 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
712 return !Sizes.count(T.getSizeInBits());
713 };
714
715 for (unsigned M : union_modes(A, B)) {
716 TypeSetByHwMode::SetType &AS = A.get(M);
717 TypeSetByHwMode::SetType &BS = B.get(M);
718 SmallSet<unsigned,2> AN, BN;
719
720 for (MVT T : AS)
721 AN.insert(T.getSizeInBits());
722 for (MVT T : BS)
723 BN.insert(T.getSizeInBits());
724
725 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
726 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
727 }
728
729 return Changed;
730}
731
732void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
733 ValidateOnExit _1(VTS);
734 TypeSetByHwMode Legal = getLegalTypes();
735 bool HaveLegalDef = Legal.hasDefault();
736
737 for (auto &I : VTS) {
738 unsigned M = I.first;
739 if (!Legal.hasMode(M) && !HaveLegalDef) {
740 TP.error("Invalid mode " + Twine(M));
741 return;
742 }
743 expandOverloads(I.second, Legal.get(M));
744 }
745}
746
747void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
748 const TypeSetByHwMode::SetType &Legal) {
749 std::set<MVT> Ovs;
750 for (MVT T : Out) {
751 if (!T.isOverloaded())
752 continue;
753
754 Ovs.insert(T);
755 // MachineValueTypeSet allows iteration and erasing.
756 Out.erase(T);
757 }
758
759 for (MVT Ov : Ovs) {
760 switch (Ov.SimpleTy) {
761 case MVT::iPTRAny:
762 Out.insert(MVT::iPTR);
763 return;
764 case MVT::iAny:
765 for (MVT T : MVT::integer_valuetypes())
766 if (Legal.count(T))
767 Out.insert(T);
768 for (MVT T : MVT::integer_vector_valuetypes())
769 if (Legal.count(T))
770 Out.insert(T);
771 return;
772 case MVT::fAny:
773 for (MVT T : MVT::fp_valuetypes())
774 if (Legal.count(T))
775 Out.insert(T);
776 for (MVT T : MVT::fp_vector_valuetypes())
777 if (Legal.count(T))
778 Out.insert(T);
779 return;
780 case MVT::vAny:
781 for (MVT T : MVT::vector_valuetypes())
782 if (Legal.count(T))
783 Out.insert(T);
784 return;
785 case MVT::Any:
786 for (MVT T : MVT::all_valuetypes())
787 if (Legal.count(T))
788 Out.insert(T);
789 return;
790 default:
791 break;
792 }
793 }
794}
795
796TypeSetByHwMode TypeInfer::getLegalTypes() {
797 if (!LegalTypesCached) {
798 // Stuff all types from all modes into the default mode.
799 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
800 for (const auto &I : LTS)
801 LegalCache.insert(I.second);
802 LegalTypesCached = true;
803 }
804 TypeSetByHwMode VTS;
805 VTS.getOrCreate(DefaultMode) = LegalCache;
806 return VTS;
807}
808
809//===----------------------------------------------------------------------===//
810// TreePredicateFn Implementation
811//===----------------------------------------------------------------------===//
812
813/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
814TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
815 assert((static_cast <bool> ((!hasPredCode() || !hasImmCode()) &&
".td file corrupt: can't have a node predicate *and* an imm predicate"
) ? void (0) : __assert_fail ("(!hasPredCode() || !hasImmCode()) && \".td file corrupt: can't have a node predicate *and* an imm predicate\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 817, __extension__ __PRETTY_FUNCTION__))
816 (!hasPredCode() || !hasImmCode()) &&(static_cast <bool> ((!hasPredCode() || !hasImmCode()) &&
".td file corrupt: can't have a node predicate *and* an imm predicate"
) ? void (0) : __assert_fail ("(!hasPredCode() || !hasImmCode()) && \".td file corrupt: can't have a node predicate *and* an imm predicate\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 817, __extension__ __PRETTY_FUNCTION__))
817 ".td file corrupt: can't have a node predicate *and* an imm predicate")(static_cast <bool> ((!hasPredCode() || !hasImmCode()) &&
".td file corrupt: can't have a node predicate *and* an imm predicate"
) ? void (0) : __assert_fail ("(!hasPredCode() || !hasImmCode()) && \".td file corrupt: can't have a node predicate *and* an imm predicate\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 817, __extension__ __PRETTY_FUNCTION__))
;
818}
819
820bool TreePredicateFn::hasPredCode() const {
821 return isLoad() || isStore() || isAtomic() ||
822 !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
823}
824
825std::string TreePredicateFn::getPredCode() const {
826 std::string Code = "";
827
828 if (!isLoad() && !isStore() && !isAtomic()) {
829 Record *MemoryVT = getMemoryVT();
830
831 if (MemoryVT)
832 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
833 "MemoryVT requires IsLoad or IsStore");
834 }
835
836 if (!isLoad() && !isStore()) {
837 if (isUnindexed())
838 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
839 "IsUnindexed requires IsLoad or IsStore");
840
841 Record *ScalarMemoryVT = getScalarMemoryVT();
842
843 if (ScalarMemoryVT)
844 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
845 "ScalarMemoryVT requires IsLoad or IsStore");
846 }
847
848 if (isLoad() + isStore() + isAtomic() > 1)
849 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
850 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
851
852 if (isLoad()) {
853 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
854 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
855 getScalarMemoryVT() == nullptr)
856 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
857 "IsLoad cannot be used by itself");
858 } else {
859 if (isNonExtLoad())
860 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
861 "IsNonExtLoad requires IsLoad");
862 if (isAnyExtLoad())
863 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
864 "IsAnyExtLoad requires IsLoad");
865 if (isSignExtLoad())
866 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
867 "IsSignExtLoad requires IsLoad");
868 if (isZeroExtLoad())
869 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
870 "IsZeroExtLoad requires IsLoad");
871 }
872
873 if (isStore()) {
874 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
875 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
876 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
877 "IsStore cannot be used by itself");
878 } else {
879 if (isNonTruncStore())
880 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
881 "IsNonTruncStore requires IsStore");
882 if (isTruncStore())
883 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
884 "IsTruncStore requires IsStore");
885 }
886
887 if (isAtomic()) {
888 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
889 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
890 !isAtomicOrderingAcquireRelease() &&
891 !isAtomicOrderingSequentiallyConsistent())
892 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
893 "IsAtomic cannot be used by itself");
894 } else {
895 if (isAtomicOrderingMonotonic())
896 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
897 "IsAtomicOrderingMonotonic requires IsAtomic");
898 if (isAtomicOrderingAcquire())
899 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
900 "IsAtomicOrderingAcquire requires IsAtomic");
901 if (isAtomicOrderingRelease())
902 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
903 "IsAtomicOrderingRelease requires IsAtomic");
904 if (isAtomicOrderingAcquireRelease())
905 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
906 "IsAtomicOrderingAcquireRelease requires IsAtomic");
907 if (isAtomicOrderingSequentiallyConsistent())
908 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
909 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
910 }
911
912 if (isLoad() || isStore() || isAtomic()) {
913 StringRef SDNodeName =
914 isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
915
916 Record *MemoryVT = getMemoryVT();
917
918 if (MemoryVT)
919 Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
920 MemoryVT->getName() + ") return false;\n")
921 .str();
922 }
923
924 if (isAtomic() && isAtomicOrderingMonotonic())
925 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
926 "AtomicOrdering::Monotonic) return false;\n";
927 if (isAtomic() && isAtomicOrderingAcquire())
928 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
929 "AtomicOrdering::Acquire) return false;\n";
930 if (isAtomic() && isAtomicOrderingRelease())
931 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
932 "AtomicOrdering::Release) return false;\n";
933 if (isAtomic() && isAtomicOrderingAcquireRelease())
934 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
935 "AtomicOrdering::AcquireRelease) return false;\n";
936 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
937 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
938 "AtomicOrdering::SequentiallyConsistent) return false;\n";
939
940 if (isLoad() || isStore()) {
941 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
942
943 if (isUnindexed())
944 Code += ("if (cast<" + SDNodeName +
945 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
946 "return false;\n")
947 .str();
948
949 if (isLoad()) {
950 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
951 isZeroExtLoad()) > 1)
952 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
953 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
954 "IsZeroExtLoad are mutually exclusive");
955 if (isNonExtLoad())
956 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
957 "ISD::NON_EXTLOAD) return false;\n";
958 if (isAnyExtLoad())
959 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
960 "return false;\n";
961 if (isSignExtLoad())
962 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
963 "return false;\n";
964 if (isZeroExtLoad())
965 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
966 "return false;\n";
967 } else {
968 if ((isNonTruncStore() + isTruncStore()) > 1)
969 PrintFatalError(
970 getOrigPatFragRecord()->getRecord()->getLoc(),
971 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
972 if (isNonTruncStore())
973 Code +=
974 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
975 if (isTruncStore())
976 Code +=
977 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
978 }
979
980 Record *ScalarMemoryVT = getScalarMemoryVT();
981
982 if (ScalarMemoryVT)
983 Code += ("if (cast<" + SDNodeName +
984 ">(N)->getMemoryVT().getScalarType() != MVT::" +
985 ScalarMemoryVT->getName() + ") return false;\n")
986 .str();
987 }
988
989 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
990
991 Code += PredicateCode;
992
993 if (PredicateCode.empty() && !Code.empty())
994 Code += "return true;\n";
995
996 return Code;
997}
998
999bool TreePredicateFn::hasImmCode() const {
1000 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1001}
1002
1003std::string TreePredicateFn::getImmCode() const {
1004 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
1005}
1006
1007bool TreePredicateFn::immCodeUsesAPInt() const {
1008 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1009}
1010
1011bool TreePredicateFn::immCodeUsesAPFloat() const {
1012 bool Unset;
1013 // The return value will be false when IsAPFloat is unset.
1014 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1015 Unset);
1016}
1017
1018bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1019 bool Value) const {
1020 bool Unset;
1021 bool Result =
1022 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1023 if (Unset)
1024 return false;
1025 return Result == Value;
1026}
1027bool TreePredicateFn::isLoad() const {
1028 return isPredefinedPredicateEqualTo("IsLoad", true);
1029}
1030bool TreePredicateFn::isStore() const {
1031 return isPredefinedPredicateEqualTo("IsStore", true);
1032}
1033bool TreePredicateFn::isAtomic() const {
1034 return isPredefinedPredicateEqualTo("IsAtomic", true);
1035}
1036bool TreePredicateFn::isUnindexed() const {
1037 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1038}
1039bool TreePredicateFn::isNonExtLoad() const {
1040 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1041}
1042bool TreePredicateFn::isAnyExtLoad() const {
1043 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1044}
1045bool TreePredicateFn::isSignExtLoad() const {
1046 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1047}
1048bool TreePredicateFn::isZeroExtLoad() const {
1049 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1050}
1051bool TreePredicateFn::isNonTruncStore() const {
1052 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1053}
1054bool TreePredicateFn::isTruncStore() const {
1055 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1056}
1057bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1058 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1059}
1060bool TreePredicateFn::isAtomicOrderingAcquire() const {
1061 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1062}
1063bool TreePredicateFn::isAtomicOrderingRelease() const {
1064 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1065}
1066bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1067 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1068}
1069bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1070 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1071 true);
1072}
1073Record *TreePredicateFn::getMemoryVT() const {
1074 Record *R = getOrigPatFragRecord()->getRecord();
1075 if (R->isValueUnset("MemoryVT"))
1076 return nullptr;
1077 return R->getValueAsDef("MemoryVT");
1078}
1079Record *TreePredicateFn::getScalarMemoryVT() const {
1080 Record *R = getOrigPatFragRecord()->getRecord();
1081 if (R->isValueUnset("ScalarMemoryVT"))
1082 return nullptr;
1083 return R->getValueAsDef("ScalarMemoryVT");
1084}
1085
1086StringRef TreePredicateFn::getImmType() const {
1087 if (immCodeUsesAPInt())
1088 return "const APInt &";
1089 if (immCodeUsesAPFloat())
1090 return "const APFloat &";
1091 return "int64_t";
1092}
1093
1094StringRef TreePredicateFn::getImmTypeIdentifier() const {
1095 if (immCodeUsesAPInt())
1096 return "APInt";
1097 else if (immCodeUsesAPFloat())
1098 return "APFloat";
1099 return "I64";
1100}
1101
1102/// isAlwaysTrue - Return true if this is a noop predicate.
1103bool TreePredicateFn::isAlwaysTrue() const {
1104 return !hasPredCode() && !hasImmCode();
1105}
1106
1107/// Return the name to use in the generated code to reference this, this is
1108/// "Predicate_foo" if from a pattern fragment "foo".
1109std::string TreePredicateFn::getFnName() const {
1110 return "Predicate_" + PatFragRec->getRecord()->getName().str();
1111}
1112
1113/// getCodeToRunOnSDNode - Return the code for the function body that
1114/// evaluates this predicate. The argument is expected to be in "Node",
1115/// not N. This handles casting and conversion to a concrete node type as
1116/// appropriate.
1117std::string TreePredicateFn::getCodeToRunOnSDNode() const {
1118 // Handle immediate predicates first.
1119 std::string ImmCode = getImmCode();
1120 if (!ImmCode.empty()) {
1121 if (isLoad())
1122 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1123 "IsLoad cannot be used with ImmLeaf or its subclasses");
1124 if (isStore())
1125 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1126 "IsStore cannot be used with ImmLeaf or its subclasses");
1127 if (isUnindexed())
1128 PrintFatalError(
1129 getOrigPatFragRecord()->getRecord()->getLoc(),
1130 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1131 if (isNonExtLoad())
1132 PrintFatalError(
1133 getOrigPatFragRecord()->getRecord()->getLoc(),
1134 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1135 if (isAnyExtLoad())
1136 PrintFatalError(
1137 getOrigPatFragRecord()->getRecord()->getLoc(),
1138 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1139 if (isSignExtLoad())
1140 PrintFatalError(
1141 getOrigPatFragRecord()->getRecord()->getLoc(),
1142 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1143 if (isZeroExtLoad())
1144 PrintFatalError(
1145 getOrigPatFragRecord()->getRecord()->getLoc(),
1146 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1147 if (isNonTruncStore())
1148 PrintFatalError(
1149 getOrigPatFragRecord()->getRecord()->getLoc(),
1150 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1151 if (isTruncStore())
1152 PrintFatalError(
1153 getOrigPatFragRecord()->getRecord()->getLoc(),
1154 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1155 if (getMemoryVT())
1156 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1157 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1158 if (getScalarMemoryVT())
1159 PrintFatalError(
1160 getOrigPatFragRecord()->getRecord()->getLoc(),
1161 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1162
1163 std::string Result = (" " + getImmType() + " Imm = ").str();
1164 if (immCodeUsesAPFloat())
1165 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1166 else if (immCodeUsesAPInt())
1167 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1168 else
1169 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
1170 return Result + ImmCode;
1171 }
1172
1173 // Handle arbitrary node predicates.
1174 assert(hasPredCode() && "Don't have any predicate code!")(static_cast <bool> (hasPredCode() && "Don't have any predicate code!"
) ? void (0) : __assert_fail ("hasPredCode() && \"Don't have any predicate code!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1174, __extension__ __PRETTY_FUNCTION__))
;
1175 StringRef ClassName;
1176 if (PatFragRec->getOnlyTree()->isLeaf())
1177 ClassName = "SDNode";
1178 else {
1179 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1180 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1181 }
1182 std::string Result;
1183 if (ClassName == "SDNode")
1184 Result = " SDNode *N = Node;\n";
1185 else
1186 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
1187
1188 return Result + getPredCode();
1189}
1190
1191//===----------------------------------------------------------------------===//
1192// PatternToMatch implementation
1193//
1194
1195/// getPatternSize - Return the 'size' of this pattern. We want to match large
1196/// patterns before small ones. This is used to determine the size of a
1197/// pattern.
1198static unsigned getPatternSize(const TreePatternNode *P,
1199 const CodeGenDAGPatterns &CGP) {
1200 unsigned Size = 3; // The node itself.
1201 // If the root node is a ConstantSDNode, increases its size.
1202 // e.g. (set R32:$dst, 0).
1203 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
1204 Size += 2;
1205
1206 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
1207 Size += AM->getComplexity();
1208 // We don't want to count any children twice, so return early.
1209 return Size;
1210 }
1211
1212 // If this node has some predicate function that must match, it adds to the
1213 // complexity of this node.
1214 if (!P->getPredicateFns().empty())
1215 ++Size;
1216
1217 // Count children in the count if they are also nodes.
1218 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1219 const TreePatternNode *Child = P->getChild(i);
1220 if (!Child->isLeaf() && Child->getNumTypes()) {
1221 const TypeSetByHwMode &T0 = Child->getType(0);
1222 // At this point, all variable type sets should be simple, i.e. only
1223 // have a default mode.
1224 if (T0.getMachineValueType() != MVT::Other) {
1225 Size += getPatternSize(Child, CGP);
1226 continue;
1227 }
1228 }
1229 if (Child->isLeaf()) {
1230 if (isa<IntInit>(Child->getLeafValue()))
1231 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1232 else if (Child->getComplexPatternInfo(CGP))
1233 Size += getPatternSize(Child, CGP);
1234 else if (!Child->getPredicateFns().empty())
1235 ++Size;
1236 }
1237 }
1238
1239 return Size;
1240}
1241
1242/// Compute the complexity metric for the input pattern. This roughly
1243/// corresponds to the number of nodes that are covered.
1244int PatternToMatch::
1245getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1246 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
1247}
1248
1249/// getPredicateCheck - Return a single string containing all of this
1250/// pattern's predicates concatenated with "&&" operators.
1251///
1252std::string PatternToMatch::getPredicateCheck() const {
1253 SmallVector<const Predicate*,4> PredList;
1254 for (const Predicate &P : Predicates)
1255 PredList.push_back(&P);
1256 std::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
1257
1258 std::string Check;
1259 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1260 if (i != 0)
1261 Check += " && ";
1262 Check += '(' + PredList[i]->getCondString() + ')';
1263 }
1264 return Check;
1265}
1266
1267//===----------------------------------------------------------------------===//
1268// SDTypeConstraint implementation
1269//
1270
1271SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
1272 OperandNo = R->getValueAsInt("OperandNum");
1273
1274 if (R->isSubClassOf("SDTCisVT")) {
1275 ConstraintType = SDTCisVT;
1276 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1277 for (const auto &P : VVT)
1278 if (P.second == MVT::isVoid)
1279 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
1280 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1281 ConstraintType = SDTCisPtrTy;
1282 } else if (R->isSubClassOf("SDTCisInt")) {
1283 ConstraintType = SDTCisInt;
1284 } else if (R->isSubClassOf("SDTCisFP")) {
1285 ConstraintType = SDTCisFP;
1286 } else if (R->isSubClassOf("SDTCisVec")) {
1287 ConstraintType = SDTCisVec;
1288 } else if (R->isSubClassOf("SDTCisSameAs")) {
1289 ConstraintType = SDTCisSameAs;
1290 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1291 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1292 ConstraintType = SDTCisVTSmallerThanOp;
1293 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
1294 R->getValueAsInt("OtherOperandNum");
1295 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1296 ConstraintType = SDTCisOpSmallerThanOp;
1297 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
1298 R->getValueAsInt("BigOperandNum");
1299 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1300 ConstraintType = SDTCisEltOfVec;
1301 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
1302 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1303 ConstraintType = SDTCisSubVecOfVec;
1304 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1305 R->getValueAsInt("OtherOpNum");
1306 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1307 ConstraintType = SDTCVecEltisVT;
1308 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1309 for (const auto &P : VVT) {
1310 MVT T = P.second;
1311 if (T.isVector())
1312 PrintFatalError(R->getLoc(),
1313 "Cannot use vector type as SDTCVecEltisVT");
1314 if (!T.isInteger() && !T.isFloatingPoint())
1315 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1316 "as SDTCVecEltisVT");
1317 }
1318 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1319 ConstraintType = SDTCisSameNumEltsAs;
1320 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1321 R->getValueAsInt("OtherOperandNum");
1322 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1323 ConstraintType = SDTCisSameSizeAs;
1324 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1325 R->getValueAsInt("OtherOperandNum");
1326 } else {
1327 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
1328 }
1329}
1330
1331/// getOperandNum - Return the node corresponding to operand #OpNo in tree
1332/// N, and the result number in ResNo.
1333static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1334 const SDNodeInfo &NodeInfo,
1335 unsigned &ResNo) {
1336 unsigned NumResults = NodeInfo.getNumResults();
1337 if (OpNo < NumResults) {
1338 ResNo = OpNo;
1339 return N;
1340 }
1341
1342 OpNo -= NumResults;
1343
1344 if (OpNo >= N->getNumChildren()) {
1345 std::string S;
1346 raw_string_ostream OS(S);
1347 OS << "Invalid operand number in type constraint "
1348 << (OpNo+NumResults) << " ";
1349 N->print(OS);
1350 PrintFatalError(OS.str());
1351 }
1352
1353 return N->getChild(OpNo);
1354}
1355
1356/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1357/// constraint to the nodes operands. This returns true if it makes a
1358/// change, false otherwise. If a type contradiction is found, flag an error.
1359bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1360 const SDNodeInfo &NodeInfo,
1361 TreePattern &TP) const {
1362 if (TP.hasError())
1363 return false;
1364
1365 unsigned ResNo = 0; // The result number being referenced.
1366 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
1367 TypeInfer &TI = TP.getInfer();
1368
1369 switch (ConstraintType) {
1370 case SDTCisVT:
1371 // Operand must be a particular type.
1372 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
1373 case SDTCisPtrTy:
1374 // Operand must be same as target pointer type.
1375 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
1376 case SDTCisInt:
1377 // Require it to be one of the legal integer VTs.
1378 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
1379 case SDTCisFP:
1380 // Require it to be one of the legal fp VTs.
1381 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
1382 case SDTCisVec:
1383 // Require it to be one of the legal vector VTs.
1384 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
1385 case SDTCisSameAs: {
1386 unsigned OResNo = 0;
1387 TreePatternNode *OtherNode =
1388 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1389 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1390 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
1391 }
1392 case SDTCisVTSmallerThanOp: {
1393 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1394 // have an integer type that is smaller than the VT.
1395 if (!NodeToApply->isLeaf() ||
1396 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1397 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
1398 ->isSubClassOf("ValueType")) {
1399 TP.error(N->getOperator()->getName() + " expects a VT operand!");
1400 return false;
1401 }
1402 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1403 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1404 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1405 TypeSetByHwMode TypeListTmp(VVT);
1406
1407 unsigned OResNo = 0;
1408 TreePatternNode *OtherNode =
1409 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1410 OResNo);
1411
1412 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
1413 }
1414 case SDTCisOpSmallerThanOp: {
1415 unsigned BResNo = 0;
1416 TreePatternNode *BigOperand =
1417 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1418 BResNo);
1419 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1420 BigOperand->getExtType(BResNo));
1421 }
1422 case SDTCisEltOfVec: {
1423 unsigned VResNo = 0;
1424 TreePatternNode *VecOperand =
1425 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1426 VResNo);
1427 // Filter vector types out of VecOperand that don't have the right element
1428 // type.
1429 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1430 NodeToApply->getExtType(ResNo));
1431 }
1432 case SDTCisSubVecOfVec: {
1433 unsigned VResNo = 0;
1434 TreePatternNode *BigVecOperand =
1435 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1436 VResNo);
1437
1438 // Filter vector types out of BigVecOperand that don't have the
1439 // right subvector type.
1440 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1441 NodeToApply->getExtType(ResNo));
1442 }
1443 case SDTCVecEltisVT: {
1444 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
1445 }
1446 case SDTCisSameNumEltsAs: {
1447 unsigned OResNo = 0;
1448 TreePatternNode *OtherNode =
1449 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1450 N, NodeInfo, OResNo);
1451 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1452 NodeToApply->getExtType(ResNo));
1453 }
1454 case SDTCisSameSizeAs: {
1455 unsigned OResNo = 0;
1456 TreePatternNode *OtherNode =
1457 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1458 N, NodeInfo, OResNo);
1459 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1460 NodeToApply->getExtType(ResNo));
1461 }
1462 }
1463 llvm_unreachable("Invalid ConstraintType!")::llvm::llvm_unreachable_internal("Invalid ConstraintType!", "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1463)
;
1464}
1465
1466// Update the node type to match an instruction operand or result as specified
1467// in the ins or outs lists on the instruction definition. Return true if the
1468// type was actually changed.
1469bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1470 Record *Operand,
1471 TreePattern &TP) {
1472 // The 'unknown' operand indicates that types should be inferred from the
1473 // context.
1474 if (Operand->isSubClassOf("unknown_class"))
1475 return false;
1476
1477 // The Operand class specifies a type directly.
1478 if (Operand->isSubClassOf("Operand")) {
1479 Record *R = Operand->getValueAsDef("Type");
1480 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1481 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1482 }
1483
1484 // PointerLikeRegClass has a type that is determined at runtime.
1485 if (Operand->isSubClassOf("PointerLikeRegClass"))
1486 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1487
1488 // Both RegisterClass and RegisterOperand operands derive their types from a
1489 // register class def.
1490 Record *RC = nullptr;
1491 if (Operand->isSubClassOf("RegisterClass"))
1492 RC = Operand;
1493 else if (Operand->isSubClassOf("RegisterOperand"))
1494 RC = Operand->getValueAsDef("RegClass");
1495
1496 assert(RC && "Unknown operand type")(static_cast <bool> (RC && "Unknown operand type"
) ? void (0) : __assert_fail ("RC && \"Unknown operand type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1496, __extension__ __PRETTY_FUNCTION__))
;
1497 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1498 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1499}
1500
1501bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1502 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1503 if (!TP.getInfer().isConcrete(Types[i], true))
1504 return true;
1505 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1506 if (getChild(i)->ContainsUnresolvedType(TP))
1507 return true;
1508 return false;
1509}
1510
1511bool TreePatternNode::hasProperTypeByHwMode() const {
1512 for (const TypeSetByHwMode &S : Types)
1513 if (!S.isDefaultOnly())
1514 return true;
1515 for (TreePatternNode *C : Children)
1516 if (C->hasProperTypeByHwMode())
1517 return true;
1518 return false;
1519}
1520
1521bool TreePatternNode::hasPossibleType() const {
1522 for (const TypeSetByHwMode &S : Types)
1523 if (!S.isPossible())
1524 return false;
1525 for (TreePatternNode *C : Children)
1526 if (!C->hasPossibleType())
1527 return false;
1528 return true;
1529}
1530
1531bool TreePatternNode::setDefaultMode(unsigned Mode) {
1532 for (TypeSetByHwMode &S : Types) {
1533 S.makeSimple(Mode);
1534 // Check if the selected mode had a type conflict.
1535 if (S.get(DefaultMode).empty())
1536 return false;
1537 }
1538 for (TreePatternNode *C : Children)
1539 if (!C->setDefaultMode(Mode))
1540 return false;
1541 return true;
1542}
1543
1544//===----------------------------------------------------------------------===//
1545// SDNodeInfo implementation
1546//
1547SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
1548 EnumName = R->getValueAsString("Opcode");
1549 SDClassName = R->getValueAsString("SDClass");
1550 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1551 NumResults = TypeProfile->getValueAsInt("NumResults");
1552 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1553
1554 // Parse the properties.
1555 Properties = 0;
1556 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1557 if (Property->getName() == "SDNPCommutative") {
1558 Properties |= 1 << SDNPCommutative;
1559 } else if (Property->getName() == "SDNPAssociative") {
1560 Properties |= 1 << SDNPAssociative;
1561 } else if (Property->getName() == "SDNPHasChain") {
1562 Properties |= 1 << SDNPHasChain;
1563 } else if (Property->getName() == "SDNPOutGlue") {
1564 Properties |= 1 << SDNPOutGlue;
1565 } else if (Property->getName() == "SDNPInGlue") {
1566 Properties |= 1 << SDNPInGlue;
1567 } else if (Property->getName() == "SDNPOptInGlue") {
1568 Properties |= 1 << SDNPOptInGlue;
1569 } else if (Property->getName() == "SDNPMayStore") {
1570 Properties |= 1 << SDNPMayStore;
1571 } else if (Property->getName() == "SDNPMayLoad") {
1572 Properties |= 1 << SDNPMayLoad;
1573 } else if (Property->getName() == "SDNPSideEffect") {
1574 Properties |= 1 << SDNPSideEffect;
1575 } else if (Property->getName() == "SDNPMemOperand") {
1576 Properties |= 1 << SDNPMemOperand;
1577 } else if (Property->getName() == "SDNPVariadic") {
1578 Properties |= 1 << SDNPVariadic;
1579 } else {
1580 PrintFatalError("Unknown SD Node property '" +
1581 Property->getName() + "' on node '" +
1582 R->getName() + "'!");
1583 }
1584 }
1585
1586
1587 // Parse the type constraints.
1588 std::vector<Record*> ConstraintList =
1589 TypeProfile->getValueAsListOfDefs("Constraints");
1590 for (Record *R : ConstraintList)
1591 TypeConstraints.emplace_back(R, CGH);
1592}
1593
1594/// getKnownType - If the type constraints on this node imply a fixed type
1595/// (e.g. all stores return void, etc), then return it as an
1596/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1597MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1598 unsigned NumResults = getNumResults();
1599 assert(NumResults <= 1 &&(static_cast <bool> (NumResults <= 1 && "We only work with nodes with zero or one result so far!"
) ? void (0) : __assert_fail ("NumResults <= 1 && \"We only work with nodes with zero or one result so far!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1600, __extension__ __PRETTY_FUNCTION__))
1600 "We only work with nodes with zero or one result so far!")(static_cast <bool> (NumResults <= 1 && "We only work with nodes with zero or one result so far!"
) ? void (0) : __assert_fail ("NumResults <= 1 && \"We only work with nodes with zero or one result so far!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1600, __extension__ __PRETTY_FUNCTION__))
;
1601 assert(ResNo == 0 && "Only handles single result nodes so far")(static_cast <bool> (ResNo == 0 && "Only handles single result nodes so far"
) ? void (0) : __assert_fail ("ResNo == 0 && \"Only handles single result nodes so far\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1601, __extension__ __PRETTY_FUNCTION__))
;
1602
1603 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1604 // Make sure that this applies to the correct node result.
1605 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1606 continue;
1607
1608 switch (Constraint.ConstraintType) {
1609 default: break;
1610 case SDTypeConstraint::SDTCisVT:
1611 if (Constraint.VVT.isSimple())
1612 return Constraint.VVT.getSimple().SimpleTy;
1613 break;
1614 case SDTypeConstraint::SDTCisPtrTy:
1615 return MVT::iPTR;
1616 }
1617 }
1618 return MVT::Other;
1619}
1620
1621//===----------------------------------------------------------------------===//
1622// TreePatternNode implementation
1623//
1624
1625TreePatternNode::~TreePatternNode() {
1626#if 0 // FIXME: implement refcounted tree nodes!
1627 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1628 delete getChild(i);
1629#endif
1630}
1631
1632static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1633 if (Operator->getName() == "set" ||
1634 Operator->getName() == "implicit")
1635 return 0; // All return nothing.
1636
1637 if (Operator->isSubClassOf("Intrinsic"))
1638 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1639
1640 if (Operator->isSubClassOf("SDNode"))
1641 return CDP.getSDNodeInfo(Operator).getNumResults();
1642
1643 if (Operator->isSubClassOf("PatFrag")) {
1644 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1645 // the forward reference case where one pattern fragment references another
1646 // before it is processed.
1647 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1648 return PFRec->getOnlyTree()->getNumTypes();
1649
1650 // Get the result tree.
1651 DagInit *Tree = Operator->getValueAsDag("Fragment");
1652 Record *Op = nullptr;
1653 if (Tree)
1654 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1655 Op = DI->getDef();
1656 assert(Op && "Invalid Fragment")(static_cast <bool> (Op && "Invalid Fragment") ?
void (0) : __assert_fail ("Op && \"Invalid Fragment\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1656, __extension__ __PRETTY_FUNCTION__))
;
1657 return GetNumNodeResults(Op, CDP);
1658 }
1659
1660 if (Operator->isSubClassOf("Instruction")) {
1661 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1662
1663 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1664
1665 // Subtract any defaulted outputs.
1666 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1667 Record *OperandNode = InstInfo.Operands[i].Rec;
1668
1669 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1670 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1671 --NumDefsToAdd;
1672 }
1673
1674 // Add on one implicit def if it has a resolvable type.
1675 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1676 ++NumDefsToAdd;
1677 return NumDefsToAdd;
1678 }
1679
1680 if (Operator->isSubClassOf("SDNodeXForm"))
1681 return 1; // FIXME: Generalize SDNodeXForm
1682
1683 if (Operator->isSubClassOf("ValueType"))
1684 return 1; // A type-cast of one result.
1685
1686 if (Operator->isSubClassOf("ComplexPattern"))
1687 return 1;
1688
1689 errs() << *Operator;
1690 PrintFatalError("Unhandled node in GetNumNodeResults");
1691}
1692
1693void TreePatternNode::print(raw_ostream &OS) const {
1694 if (isLeaf())
1695 OS << *getLeafValue();
1696 else
1697 OS << '(' << getOperator()->getName();
1698
1699 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1700 OS << ':';
1701 getExtType(i).writeToStream(OS);
1702 }
1703
1704 if (!isLeaf()) {
1705 if (getNumChildren() != 0) {
1706 OS << " ";
1707 getChild(0)->print(OS);
1708 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1709 OS << ", ";
1710 getChild(i)->print(OS);
1711 }
1712 }
1713 OS << ")";
1714 }
1715
1716 for (const TreePredicateFn &Pred : PredicateFns)
1717 OS << "<<P:" << Pred.getFnName() << ">>";
1718 if (TransformFn)
1719 OS << "<<X:" << TransformFn->getName() << ">>";
1720 if (!getName().empty())
1721 OS << ":$" << getName();
1722
1723}
1724void TreePatternNode::dump() const {
1725 print(errs());
1726}
1727
1728/// isIsomorphicTo - Return true if this node is recursively
1729/// isomorphic to the specified node. For this comparison, the node's
1730/// entire state is considered. The assigned name is ignored, since
1731/// nodes with differing names are considered isomorphic. However, if
1732/// the assigned name is present in the dependent variable set, then
1733/// the assigned name is considered significant and the node is
1734/// isomorphic if the names match.
1735bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1736 const MultipleUseVarSet &DepVars) const {
1737 if (N == this) return true;
1738 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1739 getPredicateFns() != N->getPredicateFns() ||
1740 getTransformFn() != N->getTransformFn())
1741 return false;
1742
1743 if (isLeaf()) {
1744 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1745 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1746 return ((DI->getDef() == NDI->getDef())
1747 && (DepVars.find(getName()) == DepVars.end()
1748 || getName() == N->getName()));
1749 }
1750 }
1751 return getLeafValue() == N->getLeafValue();
1752 }
1753
1754 if (N->getOperator() != getOperator() ||
1755 N->getNumChildren() != getNumChildren()) return false;
1756 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1757 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1758 return false;
1759 return true;
1760}
1761
1762/// clone - Make a copy of this tree and all of its children.
1763///
1764TreePatternNode *TreePatternNode::clone() const {
1765 TreePatternNode *New;
1766 if (isLeaf()) {
1767 New = new TreePatternNode(getLeafValue(), getNumTypes());
1768 } else {
1769 std::vector<TreePatternNode*> CChildren;
1770 CChildren.reserve(Children.size());
1771 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1772 CChildren.push_back(getChild(i)->clone());
1773 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1774 }
1775 New->setName(getName());
1776 New->Types = Types;
1777 New->setPredicateFns(getPredicateFns());
1778 New->setTransformFn(getTransformFn());
1779 return New;
1780}
1781
1782/// RemoveAllTypes - Recursively strip all the types of this tree.
1783void TreePatternNode::RemoveAllTypes() {
1784 // Reset to unknown type.
1785 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
1786 if (isLeaf()) return;
1787 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1788 getChild(i)->RemoveAllTypes();
1789}
1790
1791
1792/// SubstituteFormalArguments - Replace the formal arguments in this tree
1793/// with actual values specified by ArgMap.
1794void TreePatternNode::
1795SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1796 if (isLeaf()) return;
1797
1798 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1799 TreePatternNode *Child = getChild(i);
1800 if (Child->isLeaf()) {
1801 Init *Val = Child->getLeafValue();
1802 // Note that, when substituting into an output pattern, Val might be an
1803 // UnsetInit.
1804 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1805 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1806 // We found a use of a formal argument, replace it with its value.
1807 TreePatternNode *NewChild = ArgMap[Child->getName()];
1808 assert(NewChild && "Couldn't find formal argument!")(static_cast <bool> (NewChild && "Couldn't find formal argument!"
) ? void (0) : __assert_fail ("NewChild && \"Couldn't find formal argument!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1808, __extension__ __PRETTY_FUNCTION__))
;
1809 assert((Child->getPredicateFns().empty() ||(static_cast <bool> ((Child->getPredicateFns().empty
() || NewChild->getPredicateFns() == Child->getPredicateFns
()) && "Non-empty child predicate clobbered!") ? void
(0) : __assert_fail ("(Child->getPredicateFns().empty() || NewChild->getPredicateFns() == Child->getPredicateFns()) && \"Non-empty child predicate clobbered!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1811, __extension__ __PRETTY_FUNCTION__))
1810 NewChild->getPredicateFns() == Child->getPredicateFns()) &&(static_cast <bool> ((Child->getPredicateFns().empty
() || NewChild->getPredicateFns() == Child->getPredicateFns
()) && "Non-empty child predicate clobbered!") ? void
(0) : __assert_fail ("(Child->getPredicateFns().empty() || NewChild->getPredicateFns() == Child->getPredicateFns()) && \"Non-empty child predicate clobbered!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1811, __extension__ __PRETTY_FUNCTION__))
1811 "Non-empty child predicate clobbered!")(static_cast <bool> ((Child->getPredicateFns().empty
() || NewChild->getPredicateFns() == Child->getPredicateFns
()) && "Non-empty child predicate clobbered!") ? void
(0) : __assert_fail ("(Child->getPredicateFns().empty() || NewChild->getPredicateFns() == Child->getPredicateFns()) && \"Non-empty child predicate clobbered!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1811, __extension__ __PRETTY_FUNCTION__))
;
1812 setChild(i, NewChild);
1813 }
1814 } else {
1815 getChild(i)->SubstituteFormalArguments(ArgMap);
1816 }
1817 }
1818}
1819
1820
1821/// InlinePatternFragments - If this pattern refers to any pattern
1822/// fragments, inline them into place, giving us a pattern without any
1823/// PatFrag references.
1824TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1825 if (TP.hasError())
1826 return nullptr;
1827
1828 if (isLeaf())
1829 return this; // nothing to do.
1830 Record *Op = getOperator();
1831
1832 if (!Op->isSubClassOf("PatFrag")) {
1833 // Just recursively inline children nodes.
1834 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1835 TreePatternNode *Child = getChild(i);
1836 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1837
1838 assert((Child->getPredicateFns().empty() ||(static_cast <bool> ((Child->getPredicateFns().empty
() || NewChild->getPredicateFns() == Child->getPredicateFns
()) && "Non-empty child predicate clobbered!") ? void
(0) : __assert_fail ("(Child->getPredicateFns().empty() || NewChild->getPredicateFns() == Child->getPredicateFns()) && \"Non-empty child predicate clobbered!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1840, __extension__ __PRETTY_FUNCTION__))
1839 NewChild->getPredicateFns() == Child->getPredicateFns()) &&(static_cast <bool> ((Child->getPredicateFns().empty
() || NewChild->getPredicateFns() == Child->getPredicateFns
()) && "Non-empty child predicate clobbered!") ? void
(0) : __assert_fail ("(Child->getPredicateFns().empty() || NewChild->getPredicateFns() == Child->getPredicateFns()) && \"Non-empty child predicate clobbered!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1840, __extension__ __PRETTY_FUNCTION__))
1840 "Non-empty child predicate clobbered!")(static_cast <bool> ((Child->getPredicateFns().empty
() || NewChild->getPredicateFns() == Child->getPredicateFns
()) && "Non-empty child predicate clobbered!") ? void
(0) : __assert_fail ("(Child->getPredicateFns().empty() || NewChild->getPredicateFns() == Child->getPredicateFns()) && \"Non-empty child predicate clobbered!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1840, __extension__ __PRETTY_FUNCTION__))
;
1841
1842 setChild(i, NewChild);
1843 }
1844 return this;
1845 }
1846
1847 // Otherwise, we found a reference to a fragment. First, look up its
1848 // TreePattern record.
1849 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1850
1851 // Verify that we are passing the right number of operands.
1852 if (Frag->getNumArgs() != Children.size()) {
1853 TP.error("'" + Op->getName() + "' fragment requires " +
1854 utostr(Frag->getNumArgs()) + " operands!");
1855 return nullptr;
1856 }
1857
1858 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1859
1860 TreePredicateFn PredFn(Frag);
1861 if (!PredFn.isAlwaysTrue())
1862 FragTree->addPredicateFn(PredFn);
1863
1864 // Resolve formal arguments to their actual value.
1865 if (Frag->getNumArgs()) {
1866 // Compute the map of formal to actual arguments.
1867 std::map<std::string, TreePatternNode*> ArgMap;
1868 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1869 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1870
1871 FragTree->SubstituteFormalArguments(ArgMap);
1872 }
1873
1874 FragTree->setName(getName());
1875 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1876 FragTree->UpdateNodeType(i, getExtType(i), TP);
1877
1878 // Transfer in the old predicates.
1879 for (const TreePredicateFn &Pred : getPredicateFns())
1880 FragTree->addPredicateFn(Pred);
1881
1882 // Get a new copy of this fragment to stitch into here.
1883 //delete this; // FIXME: implement refcounting!
1884
1885 // The fragment we inlined could have recursive inlining that is needed. See
1886 // if there are any pattern fragments in it and inline them as needed.
1887 return FragTree->InlinePatternFragments(TP);
1888}
1889
1890/// getImplicitType - Check to see if the specified record has an implicit
1891/// type which should be applied to it. This will infer the type of register
1892/// references from the register file information, for example.
1893///
1894/// When Unnamed is set, return the type of a DAG operand with no name, such as
1895/// the F8RC register class argument in:
1896///
1897/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1898///
1899/// When Unnamed is false, return the type of a named DAG operand such as the
1900/// GPR:$src operand above.
1901///
1902static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1903 bool NotRegisters,
1904 bool Unnamed,
1905 TreePattern &TP) {
1906 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1907
1908 // Check to see if this is a register operand.
1909 if (R->isSubClassOf("RegisterOperand")) {
1910 assert(ResNo == 0 && "Regoperand ref only has one result!")(static_cast <bool> (ResNo == 0 && "Regoperand ref only has one result!"
) ? void (0) : __assert_fail ("ResNo == 0 && \"Regoperand ref only has one result!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1910, __extension__ __PRETTY_FUNCTION__))
;
1911 if (NotRegisters)
1912 return TypeSetByHwMode(); // Unknown.
1913 Record *RegClass = R->getValueAsDef("RegClass");
1914 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1915 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
1916 }
1917
1918 // Check to see if this is a register or a register class.
1919 if (R->isSubClassOf("RegisterClass")) {
1920 assert(ResNo == 0 && "Regclass ref only has one result!")(static_cast <bool> (ResNo == 0 && "Regclass ref only has one result!"
) ? void (0) : __assert_fail ("ResNo == 0 && \"Regclass ref only has one result!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1920, __extension__ __PRETTY_FUNCTION__))
;
1921 // An unnamed register class represents itself as an i32 immediate, for
1922 // example on a COPY_TO_REGCLASS instruction.
1923 if (Unnamed)
1924 return TypeSetByHwMode(MVT::i32);
1925
1926 // In a named operand, the register class provides the possible set of
1927 // types.
1928 if (NotRegisters)
1929 return TypeSetByHwMode(); // Unknown.
1930 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1931 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
1932 }
1933
1934 if (R->isSubClassOf("PatFrag")) {
1935 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?")(static_cast <bool> (ResNo == 0 && "FIXME: PatFrag with multiple results?"
) ? void (0) : __assert_fail ("ResNo == 0 && \"FIXME: PatFrag with multiple results?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1935, __extension__ __PRETTY_FUNCTION__))
;
1936 // Pattern fragment types will be resolved when they are inlined.
1937 return TypeSetByHwMode(); // Unknown.
1938 }
1939
1940 if (R->isSubClassOf("Register")) {
1941 assert(ResNo == 0 && "Registers only produce one result!")(static_cast <bool> (ResNo == 0 && "Registers only produce one result!"
) ? void (0) : __assert_fail ("ResNo == 0 && \"Registers only produce one result!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1941, __extension__ __PRETTY_FUNCTION__))
;
1942 if (NotRegisters)
1943 return TypeSetByHwMode(); // Unknown.
1944 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1945 return TypeSetByHwMode(T.getRegisterVTs(R));
1946 }
1947
1948 if (R->isSubClassOf("SubRegIndex")) {
1949 assert(ResNo == 0 && "SubRegisterIndices only produce one result!")(static_cast <bool> (ResNo == 0 && "SubRegisterIndices only produce one result!"
) ? void (0) : __assert_fail ("ResNo == 0 && \"SubRegisterIndices only produce one result!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1949, __extension__ __PRETTY_FUNCTION__))
;
1950 return TypeSetByHwMode(MVT::i32);
1951 }
1952
1953 if (R->isSubClassOf("ValueType")) {
1954 assert(ResNo == 0 && "This node only has one result!")(static_cast <bool> (ResNo == 0 && "This node only has one result!"
) ? void (0) : __assert_fail ("ResNo == 0 && \"This node only has one result!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1954, __extension__ __PRETTY_FUNCTION__))
;
1955 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1956 //
1957 // (sext_inreg GPR:$src, i16)
1958 // ~~~
1959 if (Unnamed)
1960 return TypeSetByHwMode(MVT::Other);
1961 // With a name, the ValueType simply provides the type of the named
1962 // variable.
1963 //
1964 // (sext_inreg i32:$src, i16)
1965 // ~~~~~~~~
1966 if (NotRegisters)
1967 return TypeSetByHwMode(); // Unknown.
1968 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1969 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
1970 }
1971
1972 if (R->isSubClassOf("CondCode")) {
1973 assert(ResNo == 0 && "This node only has one result!")(static_cast <bool> (ResNo == 0 && "This node only has one result!"
) ? void (0) : __assert_fail ("ResNo == 0 && \"This node only has one result!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1973, __extension__ __PRETTY_FUNCTION__))
;
1974 // Using a CondCodeSDNode.
1975 return TypeSetByHwMode(MVT::Other);
1976 }
1977
1978 if (R->isSubClassOf("ComplexPattern")) {
1979 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?")(static_cast <bool> (ResNo == 0 && "FIXME: ComplexPattern with multiple results?"
) ? void (0) : __assert_fail ("ResNo == 0 && \"FIXME: ComplexPattern with multiple results?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1979, __extension__ __PRETTY_FUNCTION__))
;
1980 if (NotRegisters)
1981 return TypeSetByHwMode(); // Unknown.
1982 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
1983 }
1984 if (R->isSubClassOf("PointerLikeRegClass")) {
1985 assert(ResNo == 0 && "Regclass can only have one result!")(static_cast <bool> (ResNo == 0 && "Regclass can only have one result!"
) ? void (0) : __assert_fail ("ResNo == 0 && \"Regclass can only have one result!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 1985, __extension__ __PRETTY_FUNCTION__))
;
1986 TypeSetByHwMode VTS(MVT::iPTR);
1987 TP.getInfer().expandOverloads(VTS);
1988 return VTS;
1989 }
1990
1991 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1992 R->getName() == "zero_reg") {
1993 // Placeholder.
1994 return TypeSetByHwMode(); // Unknown.
1995 }
1996
1997 if (R->isSubClassOf("Operand")) {
1998 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1999 Record *T = R->getValueAsDef("Type");
2000 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2001 }
2002
2003 TP.error("Unknown node flavor used in pattern: " + R->getName());
2004 return TypeSetByHwMode(MVT::Other);
2005}
2006
2007
2008/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2009/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2010const CodeGenIntrinsic *TreePatternNode::
2011getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2012 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2013 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2014 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
2015 return nullptr;
2016
2017 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
2018 return &CDP.getIntrinsicInfo(IID);
2019}
2020
2021/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2022/// return the ComplexPattern information, otherwise return null.
2023const ComplexPattern *
2024TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
2025 Record *Rec;
2026 if (isLeaf()) {
2027 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2028 if (!DI)
2029 return nullptr;
2030 Rec = DI->getDef();
2031 } else
2032 Rec = getOperator();
2033
2034 if (!Rec->isSubClassOf("ComplexPattern"))
2035 return nullptr;
2036 return &CGP.getComplexPattern(Rec);
2037}
2038
2039unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2040 // A ComplexPattern specifically declares how many results it fills in.
2041 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2042 return CP->getNumOperands();
2043
2044 // If MIOperandInfo is specified, that gives the count.
2045 if (isLeaf()) {
2046 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2047 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2048 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2049 if (MIOps->getNumArgs())
2050 return MIOps->getNumArgs();
2051 }
2052 }
2053
2054 // Otherwise there is just one result.
2055 return 1;
2056}
2057
2058/// NodeHasProperty - Return true if this node has the specified property.
2059bool TreePatternNode::NodeHasProperty(SDNP Property,
2060 const CodeGenDAGPatterns &CGP) const {
2061 if (isLeaf()) {
2062 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2063 return CP->hasProperty(Property);
2064 return false;
2065 }
2066
2067 Record *Operator = getOperator();
2068 if (!Operator->isSubClassOf("SDNode")) return false;
2069
2070 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2071}
2072
2073
2074
2075
2076/// TreeHasProperty - Return true if any node in this tree has the specified
2077/// property.
2078bool TreePatternNode::TreeHasProperty(SDNP Property,
2079 const CodeGenDAGPatterns &CGP) const {
2080 if (NodeHasProperty(Property, CGP))
2081 return true;
2082 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2083 if (getChild(i)->TreeHasProperty(Property, CGP))
2084 return true;
2085 return false;
2086}
2087
2088/// isCommutativeIntrinsic - Return true if the node corresponds to a
2089/// commutative intrinsic.
2090bool
2091TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2092 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2093 return Int->isCommutative;
2094 return false;
2095}
2096
2097static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2098 if (!N->isLeaf())
2099 return N->getOperator()->isSubClassOf(Class);
2100
2101 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
2102 if (DI && DI->getDef()->isSubClassOf(Class))
2103 return true;
2104
2105 return false;
2106}
2107
2108static void emitTooManyOperandsError(TreePattern &TP,
2109 StringRef InstName,
2110 unsigned Expected,
2111 unsigned Actual) {
2112 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2113 " operands but expected only " + Twine(Expected) + "!");
2114}
2115
2116static void emitTooFewOperandsError(TreePattern &TP,
2117 StringRef InstName,
2118 unsigned Actual) {
2119 TP.error("Instruction '" + InstName +
2120 "' expects more than the provided " + Twine(Actual) + " operands!");
2121}
2122
2123/// ApplyTypeConstraints - Apply all of the type constraints relevant to
2124/// this node and its children in the tree. This returns true if it makes a
2125/// change, false otherwise. If a type contradiction is found, flag an error.
2126bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
2127 if (TP.hasError())
2128 return false;
2129
2130 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2131 if (isLeaf()) {
2132 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
2133 // If it's a regclass or something else known, include the type.
2134 bool MadeChange = false;
2135 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2136 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
2137 NotRegisters,
2138 !hasName(), TP), TP);
2139 return MadeChange;
2140 }
2141
2142 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
2143 assert(Types.size() == 1 && "Invalid IntInit")(static_cast <bool> (Types.size() == 1 && "Invalid IntInit"
) ? void (0) : __assert_fail ("Types.size() == 1 && \"Invalid IntInit\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2143, __extension__ __PRETTY_FUNCTION__))
;
2144
2145 // Int inits are always integers. :)
2146 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
2147
2148 if (!TP.getInfer().isConcrete(Types[0], false))
2149 return MadeChange;
2150
2151 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2152 for (auto &P : VVT) {
2153 MVT::SimpleValueType VT = P.second.SimpleTy;
2154 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2155 continue;
2156 unsigned Size = MVT(VT).getSizeInBits();
2157 // Make sure that the value is representable for this type.
2158 if (Size >= 32)
2159 continue;
2160 // Check that the value doesn't use more bits than we have. It must
2161 // either be a sign- or zero-extended equivalent of the original.
2162 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2163 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2164 SignBitAndAbove == 1)
2165 continue;
2166
2167 TP.error("Integer value '" + itostr(II->getValue()) +
2168 "' is out of range for type '" + getEnumName(VT) + "'!");
2169 break;
2170 }
2171 return MadeChange;
2172 }
2173
2174 return false;
2175 }
2176
2177 // special handling for set, which isn't really an SDNode.
2178 if (getOperator()->getName() == "set") {
2179 assert(getNumTypes() == 0 && "Set doesn't produce a value")(static_cast <bool> (getNumTypes() == 0 && "Set doesn't produce a value"
) ? void (0) : __assert_fail ("getNumTypes() == 0 && \"Set doesn't produce a value\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2179, __extension__ __PRETTY_FUNCTION__))
;
2180 assert(getNumChildren() >= 2 && "Missing RHS of a set?")(static_cast <bool> (getNumChildren() >= 2 &&
"Missing RHS of a set?") ? void (0) : __assert_fail ("getNumChildren() >= 2 && \"Missing RHS of a set?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2180, __extension__ __PRETTY_FUNCTION__))
;
2181 unsigned NC = getNumChildren();
2182
2183 TreePatternNode *SetVal = getChild(NC-1);
2184 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
2185
2186 for (unsigned i = 0; i < NC-1; ++i) {
2187 TreePatternNode *Child = getChild(i);
2188 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
2189
2190 // Types of operands must match.
2191 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
2192 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
2193 }
2194 return MadeChange;
2195 }
2196
2197 if (getOperator()->getName() == "implicit") {
2198 assert(getNumTypes() == 0 && "Node doesn't produce a value")(static_cast <bool> (getNumTypes() == 0 && "Node doesn't produce a value"
) ? void (0) : __assert_fail ("getNumTypes() == 0 && \"Node doesn't produce a value\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2198, __extension__ __PRETTY_FUNCTION__))
;
2199
2200 bool MadeChange = false;
2201 for (unsigned i = 0; i < getNumChildren(); ++i)
2202 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2203 return MadeChange;
2204 }
2205
2206 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
2207 bool MadeChange = false;
2208
2209 // Apply the result type to the node.
2210 unsigned NumRetVTs = Int->IS.RetVTs.size();
2211 unsigned NumParamVTs = Int->IS.ParamVTs.size();
2212
2213 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
2214 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
2215
2216 if (getNumChildren() != NumParamVTs + 1) {
2217 TP.error("Intrinsic '" + Int->Name + "' expects " +
2218 utostr(NumParamVTs) + " operands, not " +
2219 utostr(getNumChildren() - 1) + " operands!");
2220 return false;
2221 }
2222
2223 // Apply type info to the intrinsic ID.
2224 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
2225
2226 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
2227 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
2228
2229 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
2230 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case")(static_cast <bool> (getChild(i+1)->getNumTypes() ==
1 && "Unhandled case") ? void (0) : __assert_fail ("getChild(i+1)->getNumTypes() == 1 && \"Unhandled case\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2230, __extension__ __PRETTY_FUNCTION__))
;
2231 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
2232 }
2233 return MadeChange;
2234 }
2235
2236 if (getOperator()->isSubClassOf("SDNode")) {
2237 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
2238
2239 // Check that the number of operands is sane. Negative operands -> varargs.
2240 if (NI.getNumOperands() >= 0 &&
2241 getNumChildren() != (unsigned)NI.getNumOperands()) {
2242 TP.error(getOperator()->getName() + " node requires exactly " +
2243 itostr(NI.getNumOperands()) + " operands!");
2244 return false;
2245 }
2246
2247 bool MadeChange = false;
2248 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2249 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2250 MadeChange |= NI.ApplyTypeConstraints(this, TP);
2251 return MadeChange;
2252 }
2253
2254 if (getOperator()->isSubClassOf("Instruction")) {
2255 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
2256 CodeGenInstruction &InstInfo =
2257 CDP.getTargetInfo().getInstruction(getOperator());
2258
2259 bool MadeChange = false;
2260
2261 // Apply the result types to the node, these come from the things in the
2262 // (outs) list of the instruction.
2263 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2264 Inst.getNumResults());
2265 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2266 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
2267
2268 // If the instruction has implicit defs, we apply the first one as a result.
2269 // FIXME: This sucks, it should apply all implicit defs.
2270 if (!InstInfo.ImplicitDefs.empty()) {
2271 unsigned ResNo = NumResultsToAdd;
2272
2273 // FIXME: Generalize to multiple possible types and multiple possible
2274 // ImplicitDefs.
2275 MVT::SimpleValueType VT =
2276 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
2277
2278 if (VT != MVT::Other)
2279 MadeChange |= UpdateNodeType(ResNo, VT, TP);
2280 }
2281
2282 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2283 // be the same.
2284 if (getOperator()->getName() == "INSERT_SUBREG") {
2285 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled")(static_cast <bool> (getChild(0)->getNumTypes() == 1
&& "FIXME: Unhandled") ? void (0) : __assert_fail ("getChild(0)->getNumTypes() == 1 && \"FIXME: Unhandled\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2285, __extension__ __PRETTY_FUNCTION__))
;
2286 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2287 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
2288 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2289 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2290 // variadic.
2291
2292 unsigned NChild = getNumChildren();
2293 if (NChild < 3) {
2294 TP.error("REG_SEQUENCE requires at least 3 operands!");
2295 return false;
2296 }
2297
2298 if (NChild % 2 == 0) {
2299 TP.error("REG_SEQUENCE requires an odd number of operands!");
2300 return false;
2301 }
2302
2303 if (!isOperandClass(getChild(0), "RegisterClass")) {
2304 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2305 return false;
2306 }
2307
2308 for (unsigned I = 1; I < NChild; I += 2) {
2309 TreePatternNode *SubIdxChild = getChild(I + 1);
2310 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2311 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2312 itostr(I + 1) + "!");
2313 return false;
2314 }
2315 }
2316 }
2317
2318 unsigned ChildNo = 0;
2319 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2320 Record *OperandNode = Inst.getOperand(i);
2321
2322 // If the instruction expects a predicate or optional def operand, we
2323 // codegen this by setting the operand to it's default value if it has a
2324 // non-empty DefaultOps field.
2325 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
2326 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2327 continue;
2328
2329 // Verify that we didn't run out of provided operands.
2330 if (ChildNo >= getNumChildren()) {
2331 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
2332 return false;
2333 }
2334
2335 TreePatternNode *Child = getChild(ChildNo++);
2336 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
2337
2338 // If the operand has sub-operands, they may be provided by distinct
2339 // child patterns, so attempt to match each sub-operand separately.
2340 if (OperandNode->isSubClassOf("Operand")) {
2341 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2342 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2343 // But don't do that if the whole operand is being provided by
2344 // a single ComplexPattern-related Operand.
2345
2346 if (Child->getNumMIResults(CDP) < NumArgs) {
2347 // Match first sub-operand against the child we already have.
2348 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2349 MadeChange |=
2350 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2351
2352 // And the remaining sub-operands against subsequent children.
2353 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2354 if (ChildNo >= getNumChildren()) {
2355 emitTooFewOperandsError(TP, getOperator()->getName(),
2356 getNumChildren());
2357 return false;
2358 }
2359 Child = getChild(ChildNo++);
2360
2361 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2362 MadeChange |=
2363 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2364 }
2365 continue;
2366 }
2367 }
2368 }
2369
2370 // If we didn't match by pieces above, attempt to match the whole
2371 // operand now.
2372 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
2373 }
2374
2375 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
2376 emitTooManyOperandsError(TP, getOperator()->getName(),
2377 ChildNo, getNumChildren());
2378 return false;
2379 }
2380
2381 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2382 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2383 return MadeChange;
2384 }
2385
2386 if (getOperator()->isSubClassOf("ComplexPattern")) {
2387 bool MadeChange = false;
2388
2389 for (unsigned i = 0; i < getNumChildren(); ++i)
2390 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2391
2392 return MadeChange;
2393 }
2394
2395 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!")(static_cast <bool> (getOperator()->isSubClassOf("SDNodeXForm"
) && "Unknown node type!") ? void (0) : __assert_fail
("getOperator()->isSubClassOf(\"SDNodeXForm\") && \"Unknown node type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2395, __extension__ __PRETTY_FUNCTION__))
;
2396
2397 // Node transforms always take one operand.
2398 if (getNumChildren() != 1) {
2399 TP.error("Node transform '" + getOperator()->getName() +
2400 "' requires one operand!");
2401 return false;
2402 }
2403
2404 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
2405 return MadeChange;
2406}
2407
2408/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2409/// RHS of a commutative operation, not the on LHS.
2410static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2411 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2412 return true;
2413 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
2414 return true;
2415 return false;
2416}
2417
2418
2419/// canPatternMatch - If it is impossible for this pattern to match on this
2420/// target, fill in Reason and return false. Otherwise, return true. This is
2421/// used as a sanity check for .td files (to prevent people from writing stuff
2422/// that can never possibly work), and to prevent the pattern permuter from
2423/// generating stuff that is useless.
2424bool TreePatternNode::canPatternMatch(std::string &Reason,
2425 const CodeGenDAGPatterns &CDP) {
2426 if (isLeaf()) return true;
2427
2428 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2429 if (!getChild(i)->canPatternMatch(Reason, CDP))
2430 return false;
2431
2432 // If this is an intrinsic, handle cases that would make it not match. For
2433 // example, if an operand is required to be an immediate.
2434 if (getOperator()->isSubClassOf("Intrinsic")) {
2435 // TODO:
2436 return true;
2437 }
2438
2439 if (getOperator()->isSubClassOf("ComplexPattern"))
2440 return true;
2441
2442 // If this node is a commutative operator, check that the LHS isn't an
2443 // immediate.
2444 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
2445 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2446 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2447 // Scan all of the operands of the node and make sure that only the last one
2448 // is a constant node, unless the RHS also is.
2449 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2450 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2451 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
2452 if (OnlyOnRHSOfCommutative(getChild(i))) {
2453 Reason="Immediate value must be on the RHS of commutative operators!";
2454 return false;
2455 }
2456 }
2457 }
2458
2459 return true;
2460}
2461
2462//===----------------------------------------------------------------------===//
2463// TreePattern implementation
2464//
2465
2466TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2467 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2468 isInputPattern(isInput), HasError(false),
2469 Infer(*this) {
2470 for (Init *I : RawPat->getValues())
2471 Trees.push_back(ParseTreePattern(I, ""));
2472}
2473
2474TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2475 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2476 isInputPattern(isInput), HasError(false),
2477 Infer(*this) {
2478 Trees.push_back(ParseTreePattern(Pat, ""));
2479}
2480
2481TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
2482 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2483 isInputPattern(isInput), HasError(false),
2484 Infer(*this) {
2485 Trees.push_back(Pat);
2486}
2487
2488void TreePattern::error(const Twine &Msg) {
2489 if (HasError)
2490 return;
2491 dump();
2492 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2493 HasError = true;
2494}
2495
2496void TreePattern::ComputeNamedNodes() {
2497 for (TreePatternNode *Tree : Trees)
2498 ComputeNamedNodes(Tree);
2499}
2500
2501void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2502 if (!N->getName().empty())
2503 NamedNodes[N->getName()].push_back(N);
2504
2505 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2506 ComputeNamedNodes(N->getChild(i));
2507}
2508
2509
2510TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2511 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2512 Record *R = DI->getDef();
2513
2514 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2515 // TreePatternNode of its own. For example:
2516 /// (foo GPR, imm) -> (foo GPR, (imm))
2517 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2518 return ParseTreePattern(
2519 DagInit::get(DI, nullptr,
2520 std::vector<std::pair<Init*, StringInit*> >()),
2521 OpName);
2522
2523 // Input argument?
2524 TreePatternNode *Res = new TreePatternNode(DI, 1);
2525 if (R->getName() == "node" && !OpName.empty()) {
2526 if (OpName.empty())
2527 error("'node' argument requires a name to match with operand list");
2528 Args.push_back(OpName);
2529 }
2530
2531 Res->setName(OpName);
2532 return Res;
2533 }
2534
2535 // ?:$name or just $name.
2536 if (isa<UnsetInit>(TheInit)) {
2537 if (OpName.empty())
2538 error("'?' argument requires a name to match with operand list");
2539 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2540 Args.push_back(OpName);
2541 Res->setName(OpName);
2542 return Res;
2543 }
2544
2545 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2546 if (!OpName.empty())
2547 error("Constant int argument should not have a name!");
2548 return new TreePatternNode(II, 1);
2549 }
2550
2551 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2552 // Turn this into an IntInit.
2553 Init *II = BI->convertInitializerTo(IntRecTy::get());
2554 if (!II || !isa<IntInit>(II))
2555 error("Bits value must be constants!");
2556 return ParseTreePattern(II, OpName);
2557 }
2558
2559 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2560 if (!Dag) {
2561 TheInit->print(errs());
2562 error("Pattern has unexpected init kind!");
2563 }
2564 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2565 if (!OpDef) error("Pattern has unexpected operator type!");
2566 Record *Operator = OpDef->getDef();
2567
2568 if (Operator->isSubClassOf("ValueType")) {
2569 // If the operator is a ValueType, then this must be "type cast" of a leaf
2570 // node.
2571 if (Dag->getNumArgs() != 1)
2572 error("Type cast only takes one operand!");
2573
2574 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2575 Dag->getArgNameStr(0));
2576
2577 // Apply the type cast.
2578 assert(New->getNumTypes() == 1 && "FIXME: Unhandled")(static_cast <bool> (New->getNumTypes() == 1 &&
"FIXME: Unhandled") ? void (0) : __assert_fail ("New->getNumTypes() == 1 && \"FIXME: Unhandled\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2578, __extension__ __PRETTY_FUNCTION__))
;
2579 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2580 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
2581
2582 if (!OpName.empty())
2583 error("ValueType cast should not have a name!");
2584 return New;
2585 }
2586
2587 // Verify that this is something that makes sense for an operator.
2588 if (!Operator->isSubClassOf("PatFrag") &&
2589 !Operator->isSubClassOf("SDNode") &&
2590 !Operator->isSubClassOf("Instruction") &&
2591 !Operator->isSubClassOf("SDNodeXForm") &&
2592 !Operator->isSubClassOf("Intrinsic") &&
2593 !Operator->isSubClassOf("ComplexPattern") &&
2594 Operator->getName() != "set" &&
2595 Operator->getName() != "implicit")
2596 error("Unrecognized node '" + Operator->getName() + "'!");
2597
2598 // Check to see if this is something that is illegal in an input pattern.
2599 if (isInputPattern) {
2600 if (Operator->isSubClassOf("Instruction") ||
2601 Operator->isSubClassOf("SDNodeXForm"))
2602 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2603 } else {
2604 if (Operator->isSubClassOf("Intrinsic"))
2605 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2606
2607 if (Operator->isSubClassOf("SDNode") &&
2608 Operator->getName() != "imm" &&
2609 Operator->getName() != "fpimm" &&
2610 Operator->getName() != "tglobaltlsaddr" &&
2611 Operator->getName() != "tconstpool" &&
2612 Operator->getName() != "tjumptable" &&
2613 Operator->getName() != "tframeindex" &&
2614 Operator->getName() != "texternalsym" &&
2615 Operator->getName() != "tblockaddress" &&
2616 Operator->getName() != "tglobaladdr" &&
2617 Operator->getName() != "bb" &&
2618 Operator->getName() != "vt" &&
2619 Operator->getName() != "mcsym")
2620 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2621 }
2622
2623 std::vector<TreePatternNode*> Children;
2624
2625 // Parse all the operands.
2626 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2627 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
2628
2629 // If the operator is an intrinsic, then this is just syntactic sugar for for
2630 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2631 // convert the intrinsic name to a number.
2632 if (Operator->isSubClassOf("Intrinsic")) {
2633 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2634 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2635
2636 // If this intrinsic returns void, it must have side-effects and thus a
2637 // chain.
2638 if (Int.IS.RetVTs.empty())
2639 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2640 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2641 // Has side-effects, requires chain.
2642 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2643 else // Otherwise, no chain.
2644 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2645
2646 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2647 Children.insert(Children.begin(), IIDNode);
2648 }
2649
2650 if (Operator->isSubClassOf("ComplexPattern")) {
2651 for (unsigned i = 0; i < Children.size(); ++i) {
2652 TreePatternNode *Child = Children[i];
2653
2654 if (Child->getName().empty())
2655 error("All arguments to a ComplexPattern must be named");
2656
2657 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2658 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2659 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2660 auto OperandId = std::make_pair(Operator, i);
2661 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2662 if (PrevOp != ComplexPatternOperands.end()) {
2663 if (PrevOp->getValue() != OperandId)
2664 error("All ComplexPattern operands must appear consistently: "
2665 "in the same order in just one ComplexPattern instance.");
2666 } else
2667 ComplexPatternOperands[Child->getName()] = OperandId;
2668 }
2669 }
2670
2671 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2672 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2673 Result->setName(OpName);
2674
2675 if (Dag->getName()) {
2676 assert(Result->getName().empty())(static_cast <bool> (Result->getName().empty()) ? void
(0) : __assert_fail ("Result->getName().empty()", "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2676, __extension__ __PRETTY_FUNCTION__))
;
2677 Result->setName(Dag->getNameStr());
2678 }
2679 return Result;
2680}
2681
2682/// SimplifyTree - See if we can simplify this tree to eliminate something that
2683/// will never match in favor of something obvious that will. This is here
2684/// strictly as a convenience to target authors because it allows them to write
2685/// more type generic things and have useless type casts fold away.
2686///
2687/// This returns true if any change is made.
2688static bool SimplifyTree(TreePatternNode *&N) {
2689 if (N->isLeaf())
2690 return false;
2691
2692 // If we have a bitconvert with a resolved type and if the source and
2693 // destination types are the same, then the bitconvert is useless, remove it.
2694 if (N->getOperator()->getName() == "bitconvert" &&
2695 N->getExtType(0).isValueTypeByHwMode(false) &&
2696 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2697 N->getName().empty()) {
2698 N = N->getChild(0);
2699 SimplifyTree(N);
2700 return true;
2701 }
2702
2703 // Walk all children.
2704 bool MadeChange = false;
2705 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2706 TreePatternNode *Child = N->getChild(i);
2707 MadeChange |= SimplifyTree(Child);
2708 N->setChild(i, Child);
2709 }
2710 return MadeChange;
2711}
2712
2713
2714
2715/// InferAllTypes - Infer/propagate as many types throughout the expression
2716/// patterns as possible. Return true if all types are inferred, false
2717/// otherwise. Flags an error if a type contradiction is found.
2718bool TreePattern::
2719InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2720 if (NamedNodes.empty())
2721 ComputeNamedNodes();
2722
2723 bool MadeChange = true;
2724 while (MadeChange) {
2725 MadeChange = false;
2726 for (TreePatternNode *&Tree : Trees) {
2727 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2728 MadeChange |= SimplifyTree(Tree);
2729 }
2730
2731 // If there are constraints on our named nodes, apply them.
2732 for (auto &Entry : NamedNodes) {
2733 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2734
2735 // If we have input named node types, propagate their types to the named
2736 // values here.
2737 if (InNamedTypes) {
2738 if (!InNamedTypes->count(Entry.getKey())) {
2739 error("Node '" + std::string(Entry.getKey()) +
2740 "' in output pattern but not input pattern");
2741 return true;
2742 }
2743
2744 const SmallVectorImpl<TreePatternNode*> &InNodes =
2745 InNamedTypes->find(Entry.getKey())->second;
2746
2747 // The input types should be fully resolved by now.
2748 for (TreePatternNode *Node : Nodes) {
2749 // If this node is a register class, and it is the root of the pattern
2750 // then we're mapping something onto an input register. We allow
2751 // changing the type of the input register in this case. This allows
2752 // us to match things like:
2753 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2754 if (Node == Trees[0] && Node->isLeaf()) {
2755 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2756 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2757 DI->getDef()->isSubClassOf("RegisterOperand")))
2758 continue;
2759 }
2760
2761 assert(Node->getNumTypes() == 1 &&(static_cast <bool> (Node->getNumTypes() == 1 &&
InNodes[0]->getNumTypes() == 1 && "FIXME: cannot name multiple result nodes yet"
) ? void (0) : __assert_fail ("Node->getNumTypes() == 1 && InNodes[0]->getNumTypes() == 1 && \"FIXME: cannot name multiple result nodes yet\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2763, __extension__ __PRETTY_FUNCTION__))
2762 InNodes[0]->getNumTypes() == 1 &&(static_cast <bool> (Node->getNumTypes() == 1 &&
InNodes[0]->getNumTypes() == 1 && "FIXME: cannot name multiple result nodes yet"
) ? void (0) : __assert_fail ("Node->getNumTypes() == 1 && InNodes[0]->getNumTypes() == 1 && \"FIXME: cannot name multiple result nodes yet\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2763, __extension__ __PRETTY_FUNCTION__))
2763 "FIXME: cannot name multiple result nodes yet")(static_cast <bool> (Node->getNumTypes() == 1 &&
InNodes[0]->getNumTypes() == 1 && "FIXME: cannot name multiple result nodes yet"
) ? void (0) : __assert_fail ("Node->getNumTypes() == 1 && InNodes[0]->getNumTypes() == 1 && \"FIXME: cannot name multiple result nodes yet\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2763, __extension__ __PRETTY_FUNCTION__))
;
2764 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2765 *this);
2766 }
2767 }
2768
2769 // If there are multiple nodes with the same name, they must all have the
2770 // same type.
2771 if (Entry.second.size() > 1) {
2772 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2773 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2774 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&(static_cast <bool> (N1->getNumTypes() == 1 &&
N2->getNumTypes() == 1 && "FIXME: cannot name multiple result nodes yet"
) ? void (0) : __assert_fail ("N1->getNumTypes() == 1 && N2->getNumTypes() == 1 && \"FIXME: cannot name multiple result nodes yet\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2775, __extension__ __PRETTY_FUNCTION__))
2775 "FIXME: cannot name multiple result nodes yet")(static_cast <bool> (N1->getNumTypes() == 1 &&
N2->getNumTypes() == 1 && "FIXME: cannot name multiple result nodes yet"
) ? void (0) : __assert_fail ("N1->getNumTypes() == 1 && N2->getNumTypes() == 1 && \"FIXME: cannot name multiple result nodes yet\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2775, __extension__ __PRETTY_FUNCTION__))
;
2776
2777 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2778 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2779 }
2780 }
2781 }
2782 }
2783
2784 bool HasUnresolvedTypes = false;
2785 for (const TreePatternNode *Tree : Trees)
2786 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
2787 return !HasUnresolvedTypes;
2788}
2789
2790void TreePattern::print(raw_ostream &OS) const {
2791 OS << getRecord()->getName();
2792 if (!Args.empty()) {
2793 OS << "(" << Args[0];
2794 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2795 OS << ", " << Args[i];
2796 OS << ")";
2797 }
2798 OS << ": ";
2799
2800 if (Trees.size() > 1)
2801 OS << "[\n";
2802 for (const TreePatternNode *Tree : Trees) {
2803 OS << "\t";
2804 Tree->print(OS);
2805 OS << "\n";
2806 }
2807
2808 if (Trees.size() > 1)
2809 OS << "]\n";
2810}
2811
2812void TreePattern::dump() const { print(errs()); }
2813
2814//===----------------------------------------------------------------------===//
2815// CodeGenDAGPatterns implementation
2816//
2817
2818CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
2819 PatternRewriterFn PatternRewriter)
2820 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
2821 PatternRewriter(PatternRewriter) {
2822
2823 Intrinsics = CodeGenIntrinsicTable(Records, false);
2824 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
2825 ParseNodeInfo();
2826 ParseNodeTransforms();
2827 ParseComplexPatterns();
2828 ParsePatternFragments();
2829 ParseDefaultOperands();
2830 ParseInstructions();
2831 ParsePatternFragments(/*OutFrags*/true);
2832 ParsePatterns();
2833
2834 // Break patterns with parameterized types into a series of patterns,
2835 // where each one has a fixed type and is predicated on the conditions
2836 // of the associated HW mode.
2837 ExpandHwModeBasedTypes();
2838
2839 // Generate variants. For example, commutative patterns can match
2840 // multiple ways. Add them to PatternsToMatch as well.
2841 GenerateVariants();
2842
2843 // Infer instruction flags. For example, we can detect loads,
2844 // stores, and side effects in many cases by examining an
2845 // instruction's pattern.
2846 InferInstructionFlags();
2847
2848 // Verify that instruction flags match the patterns.
2849 VerifyInstructionFlags();
2850}
2851
2852Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2853 Record *N = Records.getDef(Name);
2854 if (!N || !N->isSubClassOf("SDNode"))
2855 PrintFatalError("Error getting SDNode '" + Name + "'!");
2856
2857 return N;
2858}
2859
2860// Parse all of the SDNode definitions for the target, populating SDNodes.
2861void CodeGenDAGPatterns::ParseNodeInfo() {
2862 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2863 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2864
2865 while (!Nodes.empty()) {
2866 Record *R = Nodes.back();
2867 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
2868 Nodes.pop_back();
2869 }
2870
2871 // Get the builtin intrinsic nodes.
2872 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2873 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2874 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2875}
2876
2877/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2878/// map, and emit them to the file as functions.
2879void CodeGenDAGPatterns::ParseNodeTransforms() {
2880 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2881 while (!Xforms.empty()) {
2882 Record *XFormNode = Xforms.back();
2883 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2884 StringRef Code = XFormNode->getValueAsString("XFormFunction");
2885 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2886
2887 Xforms.pop_back();
2888 }
2889}
2890
2891void CodeGenDAGPatterns::ParseComplexPatterns() {
2892 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2893 while (!AMs.empty()) {
2894 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2895 AMs.pop_back();
2896 }
2897}
2898
2899
2900/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2901/// file, building up the PatternFragments map. After we've collected them all,
2902/// inline fragments together as necessary, so that there are no references left
2903/// inside a pattern fragment to a pattern fragment.
2904///
2905void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2906 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2907
2908 // First step, parse all of the fragments.
2909 for (Record *Frag : Fragments) {
2910 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2911 continue;
2912
2913 DagInit *Tree = Frag->getValueAsDag("Fragment");
2914 TreePattern *P =
2915 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2916 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2917 *this)).get();
2918
2919 // Validate the argument list, converting it to set, to discard duplicates.
2920 std::vector<std::string> &Args = P->getArgList();
2921 // Copy the args so we can take StringRefs to them.
2922 auto ArgsCopy = Args;
2923 SmallDenseSet<StringRef, 4> OperandsSet;
2924 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
2925
2926 if (OperandsSet.count(""))
2927 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2928
2929 // Parse the operands list.
2930 DagInit *OpsList = Frag->getValueAsDag("Operands");
2931 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2932 // Special cases: ops == outs == ins. Different names are used to
2933 // improve readability.
2934 if (!OpsOp ||
2935 (OpsOp->getDef()->getName() != "ops" &&
2936 OpsOp->getDef()->getName() != "outs" &&
2937 OpsOp->getDef()->getName() != "ins"))
2938 P->error("Operands list should start with '(ops ... '!");
2939
2940 // Copy over the arguments.
2941 Args.clear();
2942 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2943 if (!isa<DefInit>(OpsList->getArg(j)) ||
2944 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2945 P->error("Operands list should all be 'node' values.");
2946 if (!OpsList->getArgName(j))
2947 P->error("Operands list should have names for each operand!");
2948 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2949 if (!OperandsSet.count(ArgNameStr))
2950 P->error("'" + ArgNameStr +
2951 "' does not occur in pattern or was multiply specified!");
2952 OperandsSet.erase(ArgNameStr);
2953 Args.push_back(ArgNameStr);
2954 }
2955
2956 if (!OperandsSet.empty())
2957 P->error("Operands list does not contain an entry for operand '" +
2958 *OperandsSet.begin() + "'!");
2959
2960 // If there is a code init for this fragment, keep track of the fact that
2961 // this fragment uses it.
2962 TreePredicateFn PredFn(P);
2963 if (!PredFn.isAlwaysTrue())
2964 P->getOnlyTree()->addPredicateFn(PredFn);
2965
2966 // If there is a node transformation corresponding to this, keep track of
2967 // it.
2968 Record *Transform = Frag->getValueAsDef("OperandTransform");
2969 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2970 P->getOnlyTree()->setTransformFn(Transform);
2971 }
2972
2973 // Now that we've parsed all of the tree fragments, do a closure on them so
2974 // that there are not references to PatFrags left inside of them.
2975 for (Record *Frag : Fragments) {
2976 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2977 continue;
2978
2979 TreePattern &ThePat = *PatternFragments[Frag];
2980 ThePat.InlinePatternFragments();
2981
2982 // Infer as many types as possible. Don't worry about it if we don't infer
2983 // all of them, some may depend on the inputs of the pattern.
2984 ThePat.InferAllTypes();
2985 ThePat.resetError();
2986
2987 // If debugging, print out the pattern fragment result.
2988 DEBUG(ThePat.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { ThePat.dump(); } } while (false)
;
2989 }
2990}
2991
2992void CodeGenDAGPatterns::ParseDefaultOperands() {
2993 std::vector<Record*> DefaultOps;
2994 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2995
2996 // Find some SDNode.
2997 assert(!SDNodes.empty() && "No SDNodes parsed?")(static_cast <bool> (!SDNodes.empty() && "No SDNodes parsed?"
) ? void (0) : __assert_fail ("!SDNodes.empty() && \"No SDNodes parsed?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 2997, __extension__ __PRETTY_FUNCTION__))
;
2998 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2999
3000 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3001 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
3002
3003 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3004 // SomeSDnode so that we can parse this.
3005 std::vector<std::pair<Init*, StringInit*> > Ops;
3006 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3007 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3008 DefaultInfo->getArgName(op)));
3009 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
3010
3011 // Create a TreePattern to parse this.
3012 TreePattern P(DefaultOps[i], DI, false, *this);
3013 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!")(static_cast <bool> (P.getNumTrees() == 1 && "This ctor can only produce one tree!"
) ? void (0) : __assert_fail ("P.getNumTrees() == 1 && \"This ctor can only produce one tree!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 3013, __extension__ __PRETTY_FUNCTION__))
;
3014
3015 // Copy the operands over into a DAGDefaultOperand.
3016 DAGDefaultOperand DefaultOpInfo;
3017
3018 TreePatternNode *T = P.getTree(0);
3019 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
3020 TreePatternNode *TPN = T->getChild(op);
3021 while (TPN->ApplyTypeConstraints(P, false))
3022 /* Resolve all types */;
3023
3024 if (TPN->ContainsUnresolvedType(P)) {
3025 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3026 DefaultOps[i]->getName() +
3027 "' doesn't have a concrete type!");
3028 }
3029 DefaultOpInfo.DefaultOps.push_back(TPN);
3030 }
3031
3032 // Insert it into the DefaultOperands map so we can find it later.
3033 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
3034 }
3035}
3036
3037/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3038/// instruction input. Return true if this is a real use.
3039static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
3040 std::map<std::string, TreePatternNode*> &InstInputs) {
3041 // No name -> not interesting.
3042 if (Pat->getName().empty()) {
1
Assuming the condition is false
2
Taking false branch
3043 if (Pat->isLeaf()) {
3044 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3045 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3046 DI->getDef()->isSubClassOf("RegisterOperand")))
3047 I->error("Input " + DI->getDef()->getName() + " must be named!");
3048 }
3049 return false;
3050 }
3051
3052 Record *Rec;
3053 if (Pat->isLeaf()) {
3
Taking true branch
3054 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
4
Calling 'dyn_cast'
48
Returning from 'dyn_cast'
49
'DI' initialized here
3055 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
50
Assuming 'DI' is null
51
Taking true branch
3056 Rec = DI->getDef();
52
Called C++ object pointer is null
3057 } else {
3058 Rec = Pat->getOperator();
3059 }
3060
3061 // SRCVALUE nodes are ignored.
3062 if (Rec->getName() == "srcvalue")
3063 return false;
3064
3065 TreePatternNode *&Slot = InstInputs[Pat->getName()];
3066 if (!Slot) {
3067 Slot = Pat;
3068 return true;
3069 }
3070 Record *SlotRec;
3071 if (Slot->isLeaf()) {
3072 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
3073 } else {
3074 assert(Slot->getNumChildren() == 0 && "can't be a use with children!")(static_cast <bool> (Slot->getNumChildren() == 0 &&
"can't be a use with children!") ? void (0) : __assert_fail (
"Slot->getNumChildren() == 0 && \"can't be a use with children!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 3074, __extension__ __PRETTY_FUNCTION__))
;
3075 SlotRec = Slot->getOperator();
3076 }
3077
3078 // Ensure that the inputs agree if we've already seen this input.
3079 if (Rec != SlotRec)
3080 I->error("All $" + Pat->getName() + " inputs must agree with each other");
3081 if (Slot->getExtTypes() != Pat->getExtTypes())
3082 I->error("All $" + Pat->getName() + " inputs must agree with each other");
3083 return true;
3084}
3085
3086/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3087/// part of "I", the instruction), computing the set of inputs and outputs of
3088/// the pattern. Report errors if we see anything naughty.
3089void CodeGenDAGPatterns::
3090FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
3091 std::map<std::string, TreePatternNode*> &InstInputs,
3092 std::map<std::string, TreePatternNode*>&InstResults,
3093 std::vector<Record*> &InstImpResults) {
3094 if (Pat->isLeaf()) {
3095 bool isUse = HandleUse(I, Pat, InstInputs);
3096 if (!isUse && Pat->getTransformFn())
3097 I->error("Cannot specify a transform function for a non-input value!");
3098 return;
3099 }
3100
3101 if (Pat->getOperator()->getName() == "implicit") {
3102 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3103 TreePatternNode *Dest = Pat->getChild(i);
3104 if (!Dest->isLeaf())
3105 I->error("implicitly defined value should be a register!");
3106
3107 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3108 if (!Val || !Val->getDef()->isSubClassOf("Register"))
3109 I->error("implicitly defined value should be a register!");
3110 InstImpResults.push_back(Val->getDef());
3111 }
3112 return;
3113 }
3114
3115 if (Pat->getOperator()->getName() != "set") {
3116 // If this is not a set, verify that the children nodes are not void typed,
3117 // and recurse.
3118 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3119 if (Pat->getChild(i)->getNumTypes() == 0)
3120 I->error("Cannot have void nodes inside of patterns!");
3121 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
3122 InstImpResults);
3123 }
3124
3125 // If this is a non-leaf node with no children, treat it basically as if
3126 // it were a leaf. This handles nodes like (imm).
3127 bool isUse = HandleUse(I, Pat, InstInputs);
3128
3129 if (!isUse && Pat->getTransformFn())
3130 I->error("Cannot specify a transform function for a non-input value!");
3131 return;
3132 }
3133
3134 // Otherwise, this is a set, validate and collect instruction results.
3135 if (Pat->getNumChildren() == 0)
3136 I->error("set requires operands!");
3137
3138 if (Pat->getTransformFn())
3139 I->error("Cannot specify a transform function on a set node!");
3140
3141 // Check the set destinations.
3142 unsigned NumDests = Pat->getNumChildren()-1;
3143 for (unsigned i = 0; i != NumDests; ++i) {
3144 TreePatternNode *Dest = Pat->getChild(i);
3145 if (!Dest->isLeaf())
3146 I->error("set destination should be a register!");
3147
3148 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3149 if (!Val) {
3150 I->error("set destination should be a register!");
3151 continue;
3152 }
3153
3154 if (Val->getDef()->isSubClassOf("RegisterClass") ||
3155 Val->getDef()->isSubClassOf("ValueType") ||
3156 Val->getDef()->isSubClassOf("RegisterOperand") ||
3157 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
3158 if (Dest->getName().empty())
3159 I->error("set destination must have a name!");
3160 if (InstResults.count(Dest->getName()))
3161 I->error("cannot set '" + Dest->getName() +"' multiple times");
3162 InstResults[Dest->getName()] = Dest;
3163 } else if (Val->getDef()->isSubClassOf("Register")) {
3164 InstImpResults.push_back(Val->getDef());
3165 } else {
3166 I->error("set destination should be a register!");
3167 }
3168 }
3169
3170 // Verify and collect info from the computation.
3171 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
3172 InstInputs, InstResults, InstImpResults);
3173}
3174
3175//===----------------------------------------------------------------------===//
3176// Instruction Analysis
3177//===----------------------------------------------------------------------===//
3178
3179class InstAnalyzer {
3180 const CodeGenDAGPatterns &CDP;
3181public:
3182 bool hasSideEffects;
3183 bool mayStore;
3184 bool mayLoad;
3185 bool isBitcast;
3186 bool isVariadic;
3187
3188 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3189 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
3190 isBitcast(false), isVariadic(false) {}
3191
3192 void Analyze(const TreePattern *Pat) {
3193 // Assume only the first tree is the pattern. The others are clobber nodes.
3194 AnalyzeNode(Pat->getTree(0));
3195 }
3196
3197 void Analyze(const PatternToMatch &Pat) {
3198 AnalyzeNode(Pat.getSrcPattern());
3199 }
3200
3201private:
3202 bool IsNodeBitcast(const TreePatternNode *N) const {
3203 if (hasSideEffects || mayLoad || mayStore || isVariadic)
3204 return false;
3205
3206 if (N->getNumChildren() != 2)
3207 return false;
3208
3209 const TreePatternNode *N0 = N->getChild(0);
3210 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
3211 return false;
3212
3213 const TreePatternNode *N1 = N->getChild(1);
3214 if (N1->isLeaf())
3215 return false;
3216 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
3217 return false;
3218
3219 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
3220 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3221 return false;
3222 return OpInfo.getEnumName() == "ISD::BITCAST";
3223 }
3224
3225public:
3226 void AnalyzeNode(const TreePatternNode *N) {
3227 if (N->isLeaf()) {
3228 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
3229 Record *LeafRec = DI->getDef();
3230 // Handle ComplexPattern leaves.
3231 if (LeafRec->isSubClassOf("ComplexPattern")) {
3232 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3233 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3234 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
3235 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
3236 }
3237 }
3238 return;
3239 }
3240
3241 // Analyze children.
3242 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3243 AnalyzeNode(N->getChild(i));
3244
3245 // Ignore set nodes, which are not SDNodes.
3246 if (N->getOperator()->getName() == "set") {
3247 isBitcast = IsNodeBitcast(N);
3248 return;
3249 }
3250
3251 // Notice properties of the node.
3252 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3253 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3254 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3255 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
3256
3257 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
3258 // If this is an intrinsic, analyze it.
3259 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
3260 mayLoad = true;// These may load memory.
3261
3262 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
3263 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3264
3265 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3266 IntInfo->hasSideEffects)
3267 // ReadWriteMem intrinsics can have other strange effects.
3268 hasSideEffects = true;
3269 }
3270 }
3271
3272};
3273
3274static bool InferFromPattern(CodeGenInstruction &InstInfo,
3275 const InstAnalyzer &PatInfo,
3276 Record *PatDef) {
3277 bool Error = false;
3278
3279 // Remember where InstInfo got its flags.
3280 if (InstInfo.hasUndefFlags())
3281 InstInfo.InferredFrom = PatDef;
3282
3283 // Check explicitly set flags for consistency.
3284 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3285 !InstInfo.hasSideEffects_Unset) {
3286 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3287 // the pattern has no side effects. That could be useful for div/rem
3288 // instructions that may trap.
3289 if (!InstInfo.hasSideEffects) {
3290 Error = true;
3291 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3292 Twine(InstInfo.hasSideEffects));
3293 }
3294 }
3295
3296 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3297 Error = true;
3298 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3299 Twine(InstInfo.mayStore));
3300 }
3301
3302 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3303 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3304 // Some targets translate immediates to loads.
3305 if (!InstInfo.mayLoad) {
3306 Error = true;
3307 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3308 Twine(InstInfo.mayLoad));
3309 }
3310 }
3311
3312 // Transfer inferred flags.
3313 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3314 InstInfo.mayStore |= PatInfo.mayStore;
3315 InstInfo.mayLoad |= PatInfo.mayLoad;
3316
3317 // These flags are silently added without any verification.
3318 InstInfo.isBitcast |= PatInfo.isBitcast;
3319
3320 // Don't infer isVariadic. This flag means something different on SDNodes and
3321 // instructions. For example, a CALL SDNode is variadic because it has the
3322 // call arguments as operands, but a CALL instruction is not variadic - it
3323 // has argument registers as implicit, not explicit uses.
3324
3325 return Error;
3326}
3327
3328/// hasNullFragReference - Return true if the DAG has any reference to the
3329/// null_frag operator.
3330static bool hasNullFragReference(DagInit *DI) {
3331 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
3332 if (!OpDef) return false;
3333 Record *Operator = OpDef->getDef();
3334
3335 // If this is the null fragment, return true.
3336 if (Operator->getName() == "null_frag") return true;
3337 // If any of the arguments reference the null fragment, return true.
3338 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
3339 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
3340 if (Arg && hasNullFragReference(Arg))
3341 return true;
3342 }
3343
3344 return false;
3345}
3346
3347/// hasNullFragReference - Return true if any DAG in the list references
3348/// the null_frag operator.
3349static bool hasNullFragReference(ListInit *LI) {
3350 for (Init *I : LI->getValues()) {
3351 DagInit *DI = dyn_cast<DagInit>(I);
3352 assert(DI && "non-dag in an instruction Pattern list?!")(static_cast <bool> (DI && "non-dag in an instruction Pattern list?!"
) ? void (0) : __assert_fail ("DI && \"non-dag in an instruction Pattern list?!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 3352, __extension__ __PRETTY_FUNCTION__))
;
3353 if (hasNullFragReference(DI))
3354 return true;
3355 }
3356 return false;
3357}
3358
3359/// Get all the instructions in a tree.
3360static void
3361getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3362 if (Tree->isLeaf())
3363 return;
3364 if (Tree->getOperator()->isSubClassOf("Instruction"))
3365 Instrs.push_back(Tree->getOperator());
3366 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3367 getInstructionsInTree(Tree->getChild(i), Instrs);
3368}
3369
3370/// Check the class of a pattern leaf node against the instruction operand it
3371/// represents.
3372static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3373 Record *Leaf) {
3374 if (OI.Rec == Leaf)
3375 return true;
3376
3377 // Allow direct value types to be used in instruction set patterns.
3378 // The type will be checked later.
3379 if (Leaf->isSubClassOf("ValueType"))
3380 return true;
3381
3382 // Patterns can also be ComplexPattern instances.
3383 if (Leaf->isSubClassOf("ComplexPattern"))
3384 return true;
3385
3386 return false;
3387}
3388
3389const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
3390 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
3391
3392 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!")(static_cast <bool> (!DAGInsts.count(CGI.TheDef) &&
"Instruction already parsed!") ? void (0) : __assert_fail ("!DAGInsts.count(CGI.TheDef) && \"Instruction already parsed!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 3392, __extension__ __PRETTY_FUNCTION__))
;
3393
3394 // Parse the instruction.
3395 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
3396 // Inline pattern fragments into it.
3397 I->InlinePatternFragments();
3398
3399 // Infer as many types as possible. If we cannot infer all of them, we can
3400 // never do anything with this instruction pattern: report it to the user.
3401 if (!I->InferAllTypes())
3402 I->error("Could not infer all types in pattern!");
3403
3404 // InstInputs - Keep track of all of the inputs of the instruction, along
3405 // with the record they are declared as.
3406 std::map<std::string, TreePatternNode*> InstInputs;
3407
3408 // InstResults - Keep track of all the virtual registers that are 'set'
3409 // in the instruction, including what reg class they are.
3410 std::map<std::string, TreePatternNode*> InstResults;
3411
3412 std::vector<Record*> InstImpResults;
3413
3414 // Verify that the top-level forms in the instruction are of void type, and
3415 // fill in the InstResults map.
3416 SmallString<32> TypesString;
3417 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
3418 TypesString.clear();
3419 TreePatternNode *Pat = I->getTree(j);
3420 if (Pat->getNumTypes() != 0) {
3421 raw_svector_ostream OS(TypesString);
3422 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3423 if (k > 0)
3424 OS << ", ";
3425 Pat->getExtType(k).writeToStream(OS);
3426 }
3427 I->error("Top-level forms in instruction pattern should have"
3428 " void types, has types " +
3429 OS.str());
3430 }
3431
3432 // Find inputs and outputs, and verify the structure of the uses/defs.
3433 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3434 InstImpResults);
3435 }
3436
3437 // Now that we have inputs and outputs of the pattern, inspect the operands
3438 // list for the instruction. This determines the order that operands are
3439 // added to the machine instruction the node corresponds to.
3440 unsigned NumResults = InstResults.size();
3441
3442 // Parse the operands list from the (ops) list, validating it.
3443 assert(I->getArgList().empty() && "Args list should still be empty here!")(static_cast <bool> (I->getArgList().empty() &&
"Args list should still be empty here!") ? void (0) : __assert_fail
("I->getArgList().empty() && \"Args list should still be empty here!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 3443, __extension__ __PRETTY_FUNCTION__))
;
3444
3445 // Check that all of the results occur first in the list.
3446 std::vector<Record*> Results;
3447 SmallVector<TreePatternNode *, 2> ResNodes;
3448 for (unsigned i = 0; i != NumResults; ++i) {
3449 if (i == CGI.Operands.size())
3450 I->error("'" + InstResults.begin()->first +
3451 "' set but does not appear in operand list!");
3452 const std::string &OpName = CGI.Operands[i].Name;
3453
3454 // Check that it exists in InstResults.
3455 TreePatternNode *RNode = InstResults[OpName];
3456 if (!RNode)
3457 I->error("Operand $" + OpName + " does not exist in operand list!");
3458
3459 ResNodes.push_back(RNode);
3460
3461 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3462 if (!R)
3463 I->error("Operand $" + OpName + " should be a set destination: all "
3464 "outputs must occur before inputs in operand list!");
3465
3466 if (!checkOperandClass(CGI.Operands[i], R))
3467 I->error("Operand $" + OpName + " class mismatch!");
3468
3469 // Remember the return type.
3470 Results.push_back(CGI.Operands[i].Rec);
3471
3472 // Okay, this one checks out.
3473 InstResults.erase(OpName);
3474 }
3475
3476 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3477 // the copy while we're checking the inputs.
3478 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3479
3480 std::vector<TreePatternNode*> ResultNodeOperands;
3481 std::vector<Record*> Operands;
3482 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3483 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3484 const std::string &OpName = Op.Name;
3485 if (OpName.empty())
3486 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3487
3488 if (!InstInputsCheck.count(OpName)) {
3489 // If this is an operand with a DefaultOps set filled in, we can ignore
3490 // this. When we codegen it, we will do so as always executed.
3491 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3492 // Does it have a non-empty DefaultOps field? If so, ignore this
3493 // operand.
3494 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3495 continue;
3496 }
3497 I->error("Operand $" + OpName +
3498 " does not appear in the instruction pattern");
3499 }
3500 TreePatternNode *InVal = InstInputsCheck[OpName];
3501 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3502
3503 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3504 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3505 if (!checkOperandClass(Op, InRec))
3506 I->error("Operand $" + OpName + "'s register class disagrees"
3507 " between the operand and pattern");
3508 }
3509 Operands.push_back(Op.Rec);
3510
3511 // Construct the result for the dest-pattern operand list.
3512 TreePatternNode *OpNode = InVal->clone();
3513
3514 // No predicate is useful on the result.
3515 OpNode->clearPredicateFns();
3516
3517 // Promote the xform function to be an explicit node if set.
3518 if (Record *Xform = OpNode->getTransformFn()) {
3519 OpNode->setTransformFn(nullptr);
3520 std::vector<TreePatternNode*> Children;
3521 Children.push_back(OpNode);
3522 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3523 }
3524
3525 ResultNodeOperands.push_back(OpNode);
3526 }
3527
3528 if (!InstInputsCheck.empty())
3529 I->error("Input operand $" + InstInputsCheck.begin()->first +
3530 " occurs in pattern but not in operands list!");
3531
3532 TreePatternNode *ResultPattern =
3533 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3534 GetNumNodeResults(I->getRecord(), *this));
3535 // Copy fully inferred output node types to instruction result pattern.
3536 for (unsigned i = 0; i != NumResults; ++i) {
3537 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled")(static_cast <bool> (ResNodes[i]->getNumTypes() == 1
&& "FIXME: Unhandled") ? void (0) : __assert_fail ("ResNodes[i]->getNumTypes() == 1 && \"FIXME: Unhandled\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 3537, __extension__ __PRETTY_FUNCTION__))
;
3538 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3539 }
3540
3541 // Create and insert the instruction.
3542 // FIXME: InstImpResults should not be part of DAGInstruction.
3543 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3544 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3545
3546 // Use a temporary tree pattern to infer all types and make sure that the
3547 // constructed result is correct. This depends on the instruction already
3548 // being inserted into the DAGInsts map.
3549 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3550 Temp.InferAllTypes(&I->getNamedNodesMap());
3551
3552 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3553 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3554
3555 return TheInsertedInst;
3556}
3557
3558/// ParseInstructions - Parse all of the instructions, inlining and resolving
3559/// any fragments involved. This populates the Instructions list with fully
3560/// resolved instructions.
3561void CodeGenDAGPatterns::ParseInstructions() {
3562 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3563
3564 for (Record *Instr : Instrs) {
3565 ListInit *LI = nullptr;
3566
3567 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3568 LI = Instr->getValueAsListInit("Pattern");
3569
3570 // If there is no pattern, only collect minimal information about the
3571 // instruction for its operand list. We have to assume that there is one
3572 // result, as we have no detailed info. A pattern which references the
3573 // null_frag operator is as-if no pattern were specified. Normally this
3574 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3575 // null_frag.
3576 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3577 std::vector<Record*> Results;
3578 std::vector<Record*> Operands;
3579
3580 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3581
3582 if (InstInfo.Operands.size() != 0) {
3583 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3584 Results.push_back(InstInfo.Operands[j].Rec);
3585
3586 // The rest are inputs.
3587 for (unsigned j = InstInfo.Operands.NumDefs,
3588 e = InstInfo.Operands.size(); j < e; ++j)
3589 Operands.push_back(InstInfo.Operands[j].Rec);
3590 }
3591
3592 // Create and insert the instruction.
3593 std::vector<Record*> ImpResults;
3594 Instructions.insert(std::make_pair(Instr,
3595 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3596 continue; // no pattern.
3597 }
3598
3599 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3600 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3601
3602 (void)DI;
3603 DEBUG(DI.getPattern()->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { DI.getPattern()->dump(); } } while (false
)
;
3604 }
3605
3606 // If we can, convert the instructions to be patterns that are matched!
3607 for (auto &Entry : Instructions) {
3608 DAGInstruction &TheInst = Entry.second;
3609 TreePattern *I = TheInst.getPattern();
3610 if (!I) continue; // No pattern.
3611
3612 if (PatternRewriter)
3613 PatternRewriter(I);
3614 // FIXME: Assume only the first tree is the pattern. The others are clobber
3615 // nodes.
3616 TreePatternNode *Pattern = I->getTree(0);
3617 TreePatternNode *SrcPattern;
3618 if (Pattern->getOperator()->getName() == "set") {
3619 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3620 } else{
3621 // Not a set (store or something?)
3622 SrcPattern = Pattern;
3623 }
3624
3625 Record *Instr = Entry.first;
3626 ListInit *Preds = Instr->getValueAsListInit("Predicates");
3627 int Complexity = Instr->getValueAsInt("AddedComplexity");
3628 AddPatternToMatch(
3629 I,
3630 PatternToMatch(Instr, makePredList(Preds), SrcPattern,
3631 TheInst.getResultPattern(), TheInst.getImpResults(),
3632 Complexity, Instr->getID()));
3633 }
3634}
3635
3636
3637typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3638
3639static void FindNames(const TreePatternNode *P,
3640 std::map<std::string, NameRecord> &Names,
3641 TreePattern *PatternTop) {
3642 if (!P->getName().empty()) {
3643 NameRecord &Rec = Names[P->getName()];
3644 // If this is the first instance of the name, remember the node.
3645 if (Rec.second++ == 0)
3646 Rec.first = P;
3647 else if (Rec.first->getExtTypes() != P->getExtTypes())
3648 PatternTop->error("repetition of value: $" + P->getName() +
3649 " where different uses have different types!");
3650 }
3651
3652 if (!P->isLeaf()) {
3653 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3654 FindNames(P->getChild(i), Names, PatternTop);
3655 }
3656}
3657
3658std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3659 std::vector<Predicate> Preds;
3660 for (Init *I : L->getValues()) {
3661 if (DefInit *Pred = dyn_cast<DefInit>(I))
3662 Preds.push_back(Pred->getDef());
3663 else
3664 llvm_unreachable("Non-def on the list")::llvm::llvm_unreachable_internal("Non-def on the list", "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 3664)
;
3665 }
3666
3667 // Sort so that different orders get canonicalized to the same string.
3668 std::sort(Preds.begin(), Preds.end());
3669 return Preds;
3670}
3671
3672void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3673 PatternToMatch &&PTM) {
3674 // Do some sanity checking on the pattern we're about to match.
3675 std::string Reason;
3676 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3677 PrintWarning(Pattern->getRecord()->getLoc(),
3678 Twine("Pattern can never match: ") + Reason);
3679 return;
3680 }
3681
3682 // If the source pattern's root is a complex pattern, that complex pattern
3683 // must specify the nodes it can potentially match.
3684 if (const ComplexPattern *CP =
3685 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3686 if (CP->getRootNodes().empty())
3687 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3688 " could match");
3689
3690
3691 // Find all of the named values in the input and output, ensure they have the
3692 // same type.
3693 std::map<std::string, NameRecord> SrcNames, DstNames;
3694 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3695 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3696
3697 // Scan all of the named values in the destination pattern, rejecting them if
3698 // they don't exist in the input pattern.
3699 for (const auto &Entry : DstNames) {
3700 if (SrcNames[Entry.first].first == nullptr)
3701 Pattern->error("Pattern has input without matching name in output: $" +
3702 Entry.first);
3703 }
3704
3705 // Scan all of the named values in the source pattern, rejecting them if the
3706 // name isn't used in the dest, and isn't used to tie two values together.
3707 for (const auto &Entry : SrcNames)
3708 if (DstNames[Entry.first].first == nullptr &&
3709 SrcNames[Entry.first].second == 1)
3710 Pattern->error("Pattern has dead named input: $" + Entry.first);
3711
3712 PatternsToMatch.push_back(std::move(PTM));
3713}
3714
3715void CodeGenDAGPatterns::InferInstructionFlags() {
3716 ArrayRef<const CodeGenInstruction*> Instructions =
3717 Target.getInstructionsByEnumValue();
3718
3719 // First try to infer flags from the primary instruction pattern, if any.
3720 SmallVector<CodeGenInstruction*, 8> Revisit;
3721 unsigned Errors = 0;
3722 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3723 CodeGenInstruction &InstInfo =
3724 const_cast<CodeGenInstruction &>(*Instructions[i]);
3725
3726 // Get the primary instruction pattern.
3727 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3728 if (!Pattern) {
3729 if (InstInfo.hasUndefFlags())
3730 Revisit.push_back(&InstInfo);
3731 continue;
3732 }
3733 InstAnalyzer PatInfo(*this);
3734 PatInfo.Analyze(Pattern);
3735 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3736 }
3737
3738 // Second, look for single-instruction patterns defined outside the
3739 // instruction.
3740 for (const PatternToMatch &PTM : ptms()) {
3741 // We can only infer from single-instruction patterns, otherwise we won't
3742 // know which instruction should get the flags.
3743 SmallVector<Record*, 8> PatInstrs;
3744 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3745 if (PatInstrs.size() != 1)
3746 continue;
3747
3748 // Get the single instruction.
3749 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3750
3751 // Only infer properties from the first pattern. We'll verify the others.
3752 if (InstInfo.InferredFrom)
3753 continue;
3754
3755 InstAnalyzer PatInfo(*this);
3756 PatInfo.Analyze(PTM);
3757 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3758 }
3759
3760 if (Errors)
3761 PrintFatalError("pattern conflicts");
3762
3763 // Revisit instructions with undefined flags and no pattern.
3764 if (Target.guessInstructionProperties()) {
3765 for (CodeGenInstruction *InstInfo : Revisit) {
3766 if (InstInfo->InferredFrom)
3767 continue;
3768 // The mayLoad and mayStore flags default to false.
3769 // Conservatively assume hasSideEffects if it wasn't explicit.
3770 if (InstInfo->hasSideEffects_Unset)
3771 InstInfo->hasSideEffects = true;
3772 }
3773 return;
3774 }
3775
3776 // Complain about any flags that are still undefined.
3777 for (CodeGenInstruction *InstInfo : Revisit) {
3778 if (InstInfo->InferredFrom)
3779 continue;
3780 if (InstInfo->hasSideEffects_Unset)
3781 PrintError(InstInfo->TheDef->getLoc(),
3782 "Can't infer hasSideEffects from patterns");
3783 if (InstInfo->mayStore_Unset)
3784 PrintError(InstInfo->TheDef->getLoc(),
3785 "Can't infer mayStore from patterns");
3786 if (InstInfo->mayLoad_Unset)
3787 PrintError(InstInfo->TheDef->getLoc(),
3788 "Can't infer mayLoad from patterns");
3789 }
3790}
3791
3792
3793/// Verify instruction flags against pattern node properties.
3794void CodeGenDAGPatterns::VerifyInstructionFlags() {
3795 unsigned Errors = 0;
3796 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3797 const PatternToMatch &PTM = *I;
3798 SmallVector<Record*, 8> Instrs;
3799 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3800 if (Instrs.empty())
3801 continue;
3802
3803 // Count the number of instructions with each flag set.
3804 unsigned NumSideEffects = 0;
3805 unsigned NumStores = 0;
3806 unsigned NumLoads = 0;
3807 for (const Record *Instr : Instrs) {
3808 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3809 NumSideEffects += InstInfo.hasSideEffects;
3810 NumStores += InstInfo.mayStore;
3811 NumLoads += InstInfo.mayLoad;
3812 }
3813
3814 // Analyze the source pattern.
3815 InstAnalyzer PatInfo(*this);
3816 PatInfo.Analyze(PTM);
3817
3818 // Collect error messages.
3819 SmallVector<std::string, 4> Msgs;
3820
3821 // Check for missing flags in the output.
3822 // Permit extra flags for now at least.
3823 if (PatInfo.hasSideEffects && !NumSideEffects)
3824 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3825
3826 // Don't verify store flags on instructions with side effects. At least for
3827 // intrinsics, side effects implies mayStore.
3828 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3829 Msgs.push_back("pattern may store, but mayStore isn't set");
3830
3831 // Similarly, mayStore implies mayLoad on intrinsics.
3832 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3833 Msgs.push_back("pattern may load, but mayLoad isn't set");
3834
3835 // Print error messages.
3836 if (Msgs.empty())
3837 continue;
3838 ++Errors;
3839
3840 for (const std::string &Msg : Msgs)
3841 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3842 (Instrs.size() == 1 ?
3843 "instruction" : "output instructions"));
3844 // Provide the location of the relevant instruction definitions.
3845 for (const Record *Instr : Instrs) {
3846 if (Instr != PTM.getSrcRecord())
3847 PrintError(Instr->getLoc(), "defined here");
3848 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3849 if (InstInfo.InferredFrom &&
3850 InstInfo.InferredFrom != InstInfo.TheDef &&
3851 InstInfo.InferredFrom != PTM.getSrcRecord())
3852 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3853 }
3854 }
3855 if (Errors)
3856 PrintFatalError("Errors in DAG patterns");
3857}
3858
3859/// Given a pattern result with an unresolved type, see if we can find one
3860/// instruction with an unresolved result type. Force this result type to an
3861/// arbitrary element if it's possible types to converge results.
3862static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3863 if (N->isLeaf())
3864 return false;
3865
3866 // Analyze children.
3867 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3868 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3869 return true;
3870
3871 if (!N->getOperator()->isSubClassOf("Instruction"))
3872 return false;
3873
3874 // If this type is already concrete or completely unknown we can't do
3875 // anything.
3876 TypeInfer &TI = TP.getInfer();
3877 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3878 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
3879 continue;
3880
3881 // Otherwise, force its type to an arbitrary choice.
3882 if (TI.forceArbitrary(N->getExtType(i)))
3883 return true;
3884 }
3885
3886 return false;
3887}
3888
3889void CodeGenDAGPatterns::ParsePatterns() {
3890 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3891
3892 for (Record *CurPattern : Patterns) {
3893 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3894
3895 // If the pattern references the null_frag, there's nothing to do.
3896 if (hasNullFragReference(Tree))
3897 continue;
3898
3899 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3900
3901 // Inline pattern fragments into it.
3902 Pattern->InlinePatternFragments();
3903
3904 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3905 if (LI->empty()) continue; // no pattern.
3906
3907 // Parse the instruction.
3908 TreePattern Result(CurPattern, LI, false, *this);
3909
3910 // Inline pattern fragments into it.
3911 Result.InlinePatternFragments();
3912
3913 if (Result.getNumTrees() != 1)
3914 Result.error("Cannot handle instructions producing instructions "
3915 "with temporaries yet!");
3916
3917 bool IterateInference;
3918 bool InferredAllPatternTypes, InferredAllResultTypes;
3919 do {
3920 // Infer as many types as possible. If we cannot infer all of them, we
3921 // can never do anything with this pattern: report it to the user.
3922 InferredAllPatternTypes =
3923 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3924
3925 // Infer as many types as possible. If we cannot infer all of them, we
3926 // can never do anything with this pattern: report it to the user.
3927 InferredAllResultTypes =
3928 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3929
3930 IterateInference = false;
3931
3932 // Apply the type of the result to the source pattern. This helps us
3933 // resolve cases where the input type is known to be a pointer type (which
3934 // is considered resolved), but the result knows it needs to be 32- or
3935 // 64-bits. Infer the other way for good measure.
3936 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3937 Pattern->getTree(0)->getNumTypes());
3938 i != e; ++i) {
3939 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3940 i, Result.getTree(0)->getExtType(i), Result);
3941 IterateInference |= Result.getTree(0)->UpdateNodeType(
3942 i, Pattern->getTree(0)->getExtType(i), Result);
3943 }
3944
3945 // If our iteration has converged and the input pattern's types are fully
3946 // resolved but the result pattern is not fully resolved, we may have a
3947 // situation where we have two instructions in the result pattern and
3948 // the instructions require a common register class, but don't care about
3949 // what actual MVT is used. This is actually a bug in our modelling:
3950 // output patterns should have register classes, not MVTs.
3951 //
3952 // In any case, to handle this, we just go through and disambiguate some
3953 // arbitrary types to the result pattern's nodes.
3954 if (!IterateInference && InferredAllPatternTypes &&
3955 !InferredAllResultTypes)
3956 IterateInference =
3957 ForceArbitraryInstResultType(Result.getTree(0), Result);
3958 } while (IterateInference);
3959
3960 // Verify that we inferred enough types that we can do something with the
3961 // pattern and result. If these fire the user has to add type casts.
3962 if (!InferredAllPatternTypes)
3963 Pattern->error("Could not infer all types in pattern!");
3964 if (!InferredAllResultTypes) {
3965 Pattern->dump();
3966 Result.error("Could not infer all types in pattern result!");
3967 }
3968
3969 // Validate that the input pattern is correct.
3970 std::map<std::string, TreePatternNode*> InstInputs;
3971 std::map<std::string, TreePatternNode*> InstResults;
3972 std::vector<Record*> InstImpResults;
3973 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3974 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3975 InstInputs, InstResults,
3976 InstImpResults);
3977
3978 // Promote the xform function to be an explicit node if set.
3979 TreePatternNode *DstPattern = Result.getOnlyTree();
3980 std::vector<TreePatternNode*> ResultNodeOperands;
3981 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3982 TreePatternNode *OpNode = DstPattern->getChild(ii);
3983 if (Record *Xform = OpNode->getTransformFn()) {
3984 OpNode->setTransformFn(nullptr);
3985 std::vector<TreePatternNode*> Children;
3986 Children.push_back(OpNode);
3987 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3988 }
3989 ResultNodeOperands.push_back(OpNode);
3990 }
3991 DstPattern = Result.getOnlyTree();
3992 if (!DstPattern->isLeaf())
3993 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3994 ResultNodeOperands,
3995 DstPattern->getNumTypes());
3996
3997 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3998 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3999
4000 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
4001 Temp.InferAllTypes();
4002
4003 // A pattern may end up with an "impossible" type, i.e. a situation
4004 // where all types have been eliminated for some node in this pattern.
4005 // This could occur for intrinsics that only make sense for a specific
4006 // value type, and use a specific register class. If, for some mode,
4007 // that register class does not accept that type, the type inference
4008 // will lead to a contradiction, which is not an error however, but
4009 // a sign that this pattern will simply never match.
4010 if (Pattern->getTree(0)->hasPossibleType() &&
4011 Temp.getOnlyTree()->hasPossibleType()) {
4012 ListInit *Preds = CurPattern->getValueAsListInit("Predicates");
4013 int Complexity = CurPattern->getValueAsInt("AddedComplexity");
4014 if (PatternRewriter)
4015 PatternRewriter(Pattern);
4016 AddPatternToMatch(
4017 Pattern,
4018 PatternToMatch(
4019 CurPattern, makePredList(Preds), Pattern->getTree(0),
4020 Temp.getOnlyTree(), std::move(InstImpResults), Complexity,
4021 CurPattern->getID()));
4022 }
4023 }
4024}
4025
4026static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
4027 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4028 for (const auto &I : VTS)
4029 Modes.insert(I.first);
4030
4031 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4032 collectModes(Modes, N->getChild(i));
4033}
4034
4035void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4036 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4037 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4038 std::vector<PatternToMatch> Copy = PatternsToMatch;
4039 PatternsToMatch.clear();
4040
4041 auto AppendPattern = [this,&ModeChecks](PatternToMatch &P, unsigned Mode) {
4042 TreePatternNode *NewSrc = P.SrcPattern->clone();
4043 TreePatternNode *NewDst = P.DstPattern->clone();
4044 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
4045 delete NewSrc;
4046 delete NewDst;
4047 return;
4048 }
4049
4050 std::vector<Predicate> Preds = P.Predicates;
4051 const std::vector<Predicate> &MC = ModeChecks[Mode];
4052 Preds.insert(Preds.end(), MC.begin(), MC.end());
4053 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, NewSrc, NewDst,
4054 P.getDstRegs(), P.getAddedComplexity(),
4055 Record::getNewUID(), Mode);
4056 };
4057
4058 for (PatternToMatch &P : Copy) {
4059 TreePatternNode *SrcP = nullptr, *DstP = nullptr;
4060 if (P.SrcPattern->hasProperTypeByHwMode())
4061 SrcP = P.SrcPattern;
4062 if (P.DstPattern->hasProperTypeByHwMode())
4063 DstP = P.DstPattern;
4064 if (!SrcP && !DstP) {
4065 PatternsToMatch.push_back(P);
4066 continue;
4067 }
4068
4069 std::set<unsigned> Modes;
4070 if (SrcP)
4071 collectModes(Modes, SrcP);
4072 if (DstP)
4073 collectModes(Modes, DstP);
4074
4075 // The predicate for the default mode needs to be constructed for each
4076 // pattern separately.
4077 // Since not all modes must be present in each pattern, if a mode m is
4078 // absent, then there is no point in constructing a check for m. If such
4079 // a check was created, it would be equivalent to checking the default
4080 // mode, except not all modes' predicates would be a part of the checking
4081 // code. The subsequently generated check for the default mode would then
4082 // have the exact same patterns, but a different predicate code. To avoid
4083 // duplicated patterns with different predicate checks, construct the
4084 // default check as a negation of all predicates that are actually present
4085 // in the source/destination patterns.
4086 std::vector<Predicate> DefaultPred;
4087
4088 for (unsigned M : Modes) {
4089 if (M == DefaultMode)
4090 continue;
4091 if (ModeChecks.find(M) != ModeChecks.end())
4092 continue;
4093
4094 // Fill the map entry for this mode.
4095 const HwMode &HM = CGH.getMode(M);
4096 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4097
4098 // Add negations of the HM's predicates to the default predicate.
4099 DefaultPred.emplace_back(Predicate(HM.Features, false));
4100 }
4101
4102 for (unsigned M : Modes) {
4103 if (M == DefaultMode)
4104 continue;
4105 AppendPattern(P, M);
4106 }
4107
4108 bool HasDefault = Modes.count(DefaultMode);
4109 if (HasDefault)
4110 AppendPattern(P, DefaultMode);
4111 }
4112}
4113
4114/// Dependent variable map for CodeGenDAGPattern variant generation
4115typedef StringMap<int> DepVarMap;
4116
4117static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4118 if (N->isLeaf()) {
4119 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4120 DepMap[N->getName()]++;
4121 } else {
4122 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4123 FindDepVarsOf(N->getChild(i), DepMap);
4124 }
4125}
4126
4127/// Find dependent variables within child patterns
4128static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
4129 DepVarMap depcounts;
4130 FindDepVarsOf(N, depcounts);
4131 for (const auto &Pair : depcounts) {
4132 if (Pair.getValue() > 1)
4133 DepVars.insert(Pair.getKey());
4134 }
4135}
4136
4137#ifndef NDEBUG
4138/// Dump the dependent variable set:
4139static void DumpDepVars(MultipleUseVarSet &DepVars) {
4140 if (DepVars.empty()) {
4141 DEBUG(errs() << "<empty set>")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << "<empty set>"; } } while
(false)
;
4142 } else {
4143 DEBUG(errs() << "[ ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << "[ "; } } while (false)
;
4144 for (const auto &DepVar : DepVars) {
4145 DEBUG(errs() << DepVar.getKey() << " ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << DepVar.getKey() << " "
; } } while (false)
;
4146 }
4147 DEBUG(errs() << "]")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << "]"; } } while (false)
;
4148 }
4149}
4150#endif
4151
4152
4153/// CombineChildVariants - Given a bunch of permutations of each child of the
4154/// 'operator' node, put them together in all possible ways.
4155static void CombineChildVariants(TreePatternNode *Orig,
4156 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
4157 std::vector<TreePatternNode*> &OutVariants,
4158 CodeGenDAGPatterns &CDP,
4159 const MultipleUseVarSet &DepVars) {
4160 // Make sure that each operand has at least one variant to choose from.
4161 for (const auto &Variants : ChildVariants)
4162 if (Variants.empty())
4163 return;
4164
4165 // The end result is an all-pairs construction of the resultant pattern.
4166 std::vector<unsigned> Idxs;
4167 Idxs.resize(ChildVariants.size());
4168 bool NotDone;
4169 do {
4170#ifndef NDEBUG
4171 DEBUG(if (!Idxs.empty()) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { if (!Idxs.empty()) { errs() << Orig
->getOperator()->getName() << ": Idxs = [ "; for (
unsigned Idx : Idxs) { errs() << Idx << " "; } errs
() << "]\n"; }; } } while (false)
4172 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { if (!Idxs.empty()) { errs() << Orig
->getOperator()->getName() << ": Idxs = [ "; for (
unsigned Idx : Idxs) { errs() << Idx << " "; } errs
() << "]\n"; }; } } while (false)
4173 for (unsigned Idx : Idxs) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { if (!Idxs.empty()) { errs() << Orig
->getOperator()->getName() << ": Idxs = [ "; for (
unsigned Idx : Idxs) { errs() << Idx << " "; } errs
() << "]\n"; }; } } while (false)
4174 errs() << Idx << " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { if (!Idxs.empty()) { errs() << Orig
->getOperator()->getName() << ": Idxs = [ "; for (
unsigned Idx : Idxs) { errs() << Idx << " "; } errs
() << "]\n"; }; } } while (false)
4175 }do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { if (!Idxs.empty()) { errs() << Orig
->getOperator()->getName() << ": Idxs = [ "; for (
unsigned Idx : Idxs) { errs() << Idx << " "; } errs
() << "]\n"; }; } } while (false)
4176 errs() << "]\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { if (!Idxs.empty()) { errs() << Orig
->getOperator()->getName() << ": Idxs = [ "; for (
unsigned Idx : Idxs) { errs() << Idx << " "; } errs
() << "]\n"; }; } } while (false)
4177 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { if (!Idxs.empty()) { errs() << Orig
->getOperator()->getName() << ": Idxs = [ "; for (
unsigned Idx : Idxs) { errs() << Idx << " "; } errs
() << "]\n"; }; } } while (false)
;
4178#endif
4179 // Create the variant and add it to the output list.
4180 std::vector<TreePatternNode*> NewChildren;
4181 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4182 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
4183 auto R = llvm::make_unique<TreePatternNode>(
4184 Orig->getOperator(), NewChildren, Orig->getNumTypes());
4185
4186 // Copy over properties.
4187 R->setName(Orig->getName());
4188 R->setPredicateFns(Orig->getPredicateFns());
4189 R->setTransformFn(Orig->getTransformFn());
4190 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4191 R->setType(i, Orig->getExtType(i));
4192
4193 // If this pattern cannot match, do not include it as a variant.
4194 std::string ErrString;
4195 // Scan to see if this pattern has already been emitted. We can get
4196 // duplication due to things like commuting:
4197 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4198 // which are the same pattern. Ignore the dups.
4199 if (R->canPatternMatch(ErrString, CDP) &&
4200 none_of(OutVariants, [&](TreePatternNode *Variant) {
4201 return R->isIsomorphicTo(Variant, DepVars);
4202 }))
4203 OutVariants.push_back(R.release());
4204
4205 // Increment indices to the next permutation by incrementing the
4206 // indices from last index backward, e.g., generate the sequence
4207 // [0, 0], [0, 1], [1, 0], [1, 1].
4208 int IdxsIdx;
4209 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4210 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4211 Idxs[IdxsIdx] = 0;
4212 else
4213 break;
4214 }
4215 NotDone = (IdxsIdx >= 0);
4216 } while (NotDone);
4217}
4218
4219/// CombineChildVariants - A helper function for binary operators.
4220///
4221static void CombineChildVariants(TreePatternNode *Orig,
4222 const std::vector<TreePatternNode*> &LHS,
4223 const std::vector<TreePatternNode*> &RHS,
4224 std::vector<TreePatternNode*> &OutVariants,
4225 CodeGenDAGPatterns &CDP,
4226 const MultipleUseVarSet &DepVars) {
4227 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4228 ChildVariants.push_back(LHS);
4229 ChildVariants.push_back(RHS);
4230 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
4231}
4232
4233
4234static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
4235 std::vector<TreePatternNode *> &Children) {
4236 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!")(static_cast <bool> (N->getNumChildren()==2 &&
"Associative but doesn't have 2 children!") ? void (0) : __assert_fail
("N->getNumChildren()==2 &&\"Associative but doesn't have 2 children!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 4236, __extension__ __PRETTY_FUNCTION__))
;
4237 Record *Operator = N->getOperator();
4238
4239 // Only permit raw nodes.
4240 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
4241 N->getTransformFn()) {
4242 Children.push_back(N);
4243 return;
4244 }
4245
4246 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
4247 Children.push_back(N->getChild(0));
4248 else
4249 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
4250
4251 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
4252 Children.push_back(N->getChild(1));
4253 else
4254 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
4255}
4256
4257/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4258/// the (potentially recursive) pattern by using algebraic laws.
4259///
4260static void GenerateVariantsOf(TreePatternNode *N,
4261 std::vector<TreePatternNode*> &OutVariants,
4262 CodeGenDAGPatterns &CDP,
4263 const MultipleUseVarSet &DepVars) {
4264 // We cannot permute leaves or ComplexPattern uses.
4265 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
4266 OutVariants.push_back(N);
4267 return;
4268 }
4269
4270 // Look up interesting info about the node.
4271 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4272
4273 // If this node is associative, re-associate.
4274 if (NodeInfo.hasProperty(SDNPAssociative)) {
4275 // Re-associate by pulling together all of the linked operators
4276 std::vector<TreePatternNode*> MaximalChildren;
4277 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4278
4279 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4280 // permutations.
4281 if (MaximalChildren.size() == 3) {
4282 // Find the variants of all of our maximal children.
4283 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
4284 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4285 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4286 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
4287
4288 // There are only two ways we can permute the tree:
4289 // (A op B) op C and A op (B op C)
4290 // Within these forms, we can also permute A/B/C.
4291
4292 // Generate legal pair permutations of A/B/C.
4293 std::vector<TreePatternNode*> ABVariants;
4294 std::vector<TreePatternNode*> BAVariants;
4295 std::vector<TreePatternNode*> ACVariants;
4296 std::vector<TreePatternNode*> CAVariants;
4297 std::vector<TreePatternNode*> BCVariants;
4298 std::vector<TreePatternNode*> CBVariants;
4299 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4300 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4301 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4302 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4303 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4304 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
4305
4306 // Combine those into the result: (x op x) op x
4307 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4308 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4309 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4310 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4311 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4312 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
4313
4314 // Combine those into the result: x op (x op x)
4315 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4316 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4317 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4318 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4319 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4320 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
4321 return;
4322 }
4323 }
4324
4325 // Compute permutations of all children.
4326 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4327 ChildVariants.resize(N->getNumChildren());
4328 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4329 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
4330
4331 // Build all permutations based on how the children were formed.
4332 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
4333
4334 // If this node is commutative, consider the commuted order.
4335 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4336 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
4337 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&(static_cast <bool> ((N->getNumChildren()>=2 || isCommIntrinsic
) && "Commutative but doesn't have 2 children!") ? void
(0) : __assert_fail ("(N->getNumChildren()>=2 || isCommIntrinsic) && \"Commutative but doesn't have 2 children!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 4338, __extension__ __PRETTY_FUNCTION__))
4338 "Commutative but doesn't have 2 children!")(static_cast <bool> ((N->getNumChildren()>=2 || isCommIntrinsic
) && "Commutative but doesn't have 2 children!") ? void
(0) : __assert_fail ("(N->getNumChildren()>=2 || isCommIntrinsic) && \"Commutative but doesn't have 2 children!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 4338, __extension__ __PRETTY_FUNCTION__))
;
4339 // Don't count children which are actually register references.
4340 unsigned NC = 0;
4341 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4342 TreePatternNode *Child = N->getChild(i);
4343 if (Child->isLeaf())
4344 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
4345 Record *RR = DI->getDef();
4346 if (RR->isSubClassOf("Register"))
4347 continue;
4348 }
4349 NC++;
4350 }
4351 // Consider the commuted order.
4352 if (isCommIntrinsic) {
4353 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4354 // operands are the commutative operands, and there might be more operands
4355 // after those.
4356 assert(NC >= 3 &&(static_cast <bool> (NC >= 3 && "Commutative intrinsic should have at least 3 children!"
) ? void (0) : __assert_fail ("NC >= 3 && \"Commutative intrinsic should have at least 3 children!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 4357, __extension__ __PRETTY_FUNCTION__))
4357 "Commutative intrinsic should have at least 3 children!")(static_cast <bool> (NC >= 3 && "Commutative intrinsic should have at least 3 children!"
) ? void (0) : __assert_fail ("NC >= 3 && \"Commutative intrinsic should have at least 3 children!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 4357, __extension__ __PRETTY_FUNCTION__))
;
4358 std::vector<std::vector<TreePatternNode*> > Variants;
4359 Variants.push_back(ChildVariants[0]); // Intrinsic id.
4360 Variants.push_back(ChildVariants[2]);
4361 Variants.push_back(ChildVariants[1]);
4362 for (unsigned i = 3; i != NC; ++i)
4363 Variants.push_back(ChildVariants[i]);
4364 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4365 } else if (NC == N->getNumChildren()) {
4366 std::vector<std::vector<TreePatternNode*> > Variants;
4367 Variants.push_back(ChildVariants[1]);
4368 Variants.push_back(ChildVariants[0]);
4369 for (unsigned i = 2; i != NC; ++i)
4370 Variants.push_back(ChildVariants[i]);
4371 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4372 }
4373 }
4374}
4375
4376
4377// GenerateVariants - Generate variants. For example, commutative patterns can
4378// match multiple ways. Add them to PatternsToMatch as well.
4379void CodeGenDAGPatterns::GenerateVariants() {
4380 DEBUG(errs() << "Generating instruction variants.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << "Generating instruction variants.\n"
; } } while (false)
;
4381
4382 // Loop over all of the patterns we've collected, checking to see if we can
4383 // generate variants of the instruction, through the exploitation of
4384 // identities. This permits the target to provide aggressive matching without
4385 // the .td file having to contain tons of variants of instructions.
4386 //
4387 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4388 // intentionally do not reconsider these. Any variants of added patterns have
4389 // already been added.
4390 //
4391 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
4392 MultipleUseVarSet DepVars;
4393 std::vector<TreePatternNode*> Variants;
4394 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
4395 DEBUG(errs() << "Dependent/multiply used variables: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << "Dependent/multiply used variables: "
; } } while (false)
;
4396 DEBUG(DumpDepVars(DepVars))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { DumpDepVars(DepVars); } } while (false)
;
4397 DEBUG(errs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << "\n"; } } while (false)
;
4398 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
4399 DepVars);
4400
4401 assert(!Variants.empty() && "Must create at least original variant!")(static_cast <bool> (!Variants.empty() && "Must create at least original variant!"
) ? void (0) : __assert_fail ("!Variants.empty() && \"Must create at least original variant!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/utils/TableGen/CodeGenDAGPatterns.cpp"
, 4401, __extension__ __PRETTY_FUNCTION__))
;
4402 if (Variants.size() == 1) // No additional variants for this pattern.
4403 continue;
4404
4405 DEBUG(errs() << "FOUND VARIANTS OF: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << "FOUND VARIANTS OF: "; PatternsToMatch
[i].getSrcPattern()->dump(); errs() << "\n"; } } while
(false)
4406 PatternsToMatch[i].getSrcPattern()->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << "FOUND VARIANTS OF: "; PatternsToMatch
[i].getSrcPattern()->dump(); errs() << "\n"; } } while
(false)
4407 errs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << "FOUND VARIANTS OF: "; PatternsToMatch
[i].getSrcPattern()->dump(); errs() << "\n"; } } while
(false)
;
4408
4409 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4410 TreePatternNode *Variant = Variants[v];
4411
4412 DEBUG(errs() << " VAR#" << v << ": ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << " VAR#" << v <<
": "; Variant->dump(); errs() << "\n"; } } while (false
)
4413 Variant->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << " VAR#" << v <<
": "; Variant->dump(); errs() << "\n"; } } while (false
)
4414 errs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << " VAR#" << v <<
": "; Variant->dump(); errs() << "\n"; } } while (false
)
;
4415
4416 // Scan to see if an instruction or explicit pattern already matches this.
4417 bool AlreadyExists = false;
4418 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
4419 // Skip if the top level predicates do not match.
4420 if (PatternsToMatch[i].getPredicates() !=
4421 PatternsToMatch[p].getPredicates())
4422 continue;
4423 // Check to see if this variant already exists.
4424 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4425 DepVars)) {
4426 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << " *** ALREADY EXISTS, ignoring variant.\n"
; } } while (false)
;
4427 AlreadyExists = true;
4428 break;
4429 }
4430 }
4431 // If we already have it, ignore the variant.
4432 if (AlreadyExists) continue;
4433
4434 // Otherwise, add it to the list of patterns we have.
4435 PatternsToMatch.push_back(PatternToMatch(
4436 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4437 Variant, PatternsToMatch[i].getDstPattern(),
4438 PatternsToMatch[i].getDstRegs(),
4439 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
4440 }
4441
4442 DEBUG(errs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("dag-patterns")) { errs() << "\n"; } } while (false)
;
4443 }
4444}

/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
2//
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//
10// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
11// and dyn_cast_or_null<X>() templates.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CASTING_H
16#define LLVM_SUPPORT_CASTING_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <memory>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// isa<x> Support Templates
28//===----------------------------------------------------------------------===//
29
30// Define a template that can be specialized by smart pointers to reflect the
31// fact that they are automatically dereferenced, and are not involved with the
32// template selection process... the default implementation is a noop.
33//
34template<typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
39};
40
41template<typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType =
44 typename add_const_past_pointer<NonConstSimpleType>::type;
45 using RetType =
46 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
47
48 static RetType getSimplifiedValue(const From& Val) {
49 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
8
Calling 'simplify_type::getSimplifiedValue'
9
Returning from 'simplify_type::getSimplifiedValue'
30
Calling 'simplify_type::getSimplifiedValue'
31
Returning from 'simplify_type::getSimplifiedValue'
50 }
51};
52
53// The core of the implementation of isa<X> is here; To and From should be
54// the names of classes. This template can be specialized to customize the
55// implementation of isa<> without rewriting it from scratch.
56template <typename To, typename From, typename Enabler = void>
57struct isa_impl {
58 static inline bool doit(const From &Val) {
59 return To::classof(&Val);
15
Calling 'DefInit::classof'
19
Returning from 'DefInit::classof'
37
Calling 'DefInit::classof'
40
Returning from 'DefInit::classof'
60 }
61};
62
63/// \brief Always allow upcasts, and perform no dynamic check for them.
64template <typename To, typename From>
65struct isa_impl<
66 To, From, typename std::enable_if<std::is_base_of<To, From>::value>::type> {
67 static inline bool doit(const From &) { return true; }
68};
69
70template <typename To, typename From> struct isa_impl_cl {
71 static inline bool doit(const From &Val) {
72 return isa_impl<To, From>::doit(Val);
73 }
74};
75
76template <typename To, typename From> struct isa_impl_cl<To, const From> {
77 static inline bool doit(const From &Val) {
78 return isa_impl<To, From>::doit(Val);
79 }
80};
81
82template <typename To, typename From>
83struct isa_impl_cl<To, const std::unique_ptr<From>> {
84 static inline bool doit(const std::unique_ptr<From> &Val) {
85 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h"
, 85, __extension__ __PRETTY_FUNCTION__))
;
86 return isa_impl_cl<To, From>::doit(*Val);
87 }
88};
89
90template <typename To, typename From> struct isa_impl_cl<To, From*> {
91 static inline bool doit(const From *Val) {
92 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h"
, 92, __extension__ __PRETTY_FUNCTION__))
;
93 return isa_impl<To, From>::doit(*Val);
94 }
95};
96
97template <typename To, typename From> struct isa_impl_cl<To, From*const> {
98 static inline bool doit(const From *Val) {
99 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h"
, 99, __extension__ __PRETTY_FUNCTION__))
;
100 return isa_impl<To, From>::doit(*Val);
101 }
102};
103
104template <typename To, typename From> struct isa_impl_cl<To, const From*> {
105 static inline bool doit(const From *Val) {
106 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h"
, 106, __extension__ __PRETTY_FUNCTION__))
;
13
Within the expansion of the macro 'assert':
35
Within the expansion of the macro 'assert':
107 return isa_impl<To, From>::doit(*Val);
14
Calling 'isa_impl::doit'
20
Returning from 'isa_impl::doit'
36
Calling 'isa_impl::doit'
41
Returning from 'isa_impl::doit'
108 }
109};
110
111template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
112 static inline bool doit(const From *Val) {
113 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h"
, 113, __extension__ __PRETTY_FUNCTION__))
;
114 return isa_impl<To, From>::doit(*Val);
115 }
116};
117
118template<typename To, typename From, typename SimpleFrom>
119struct isa_impl_wrap {
120 // When From != SimplifiedType, we can simplify the type some more by using
121 // the simplify_type template.
122 static bool doit(const From &Val) {
123 return isa_impl_wrap<To, SimpleFrom,
11
Calling 'isa_impl_wrap::doit'
22
Returning from 'isa_impl_wrap::doit'
33
Calling 'isa_impl_wrap::doit'
43
Returning from 'isa_impl_wrap::doit'
124 typename simplify_type<SimpleFrom>::SimpleType>::doit(
125 simplify_type<const From>::getSimplifiedValue(Val));
7
Calling 'simplify_type::getSimplifiedValue'
10
Returning from 'simplify_type::getSimplifiedValue'
29
Calling 'simplify_type::getSimplifiedValue'
32
Returning from 'simplify_type::getSimplifiedValue'
126 }
127};
128
129template<typename To, typename FromTy>
130struct isa_impl_wrap<To, FromTy, FromTy> {
131 // When From == SimpleType, we are as simple as we are going to get.
132 static bool doit(const FromTy &Val) {
133 return isa_impl_cl<To,FromTy>::doit(Val);
12
Calling 'isa_impl_cl::doit'
21
Returning from 'isa_impl_cl::doit'
34
Calling 'isa_impl_cl::doit'
42
Returning from 'isa_impl_cl::doit'
134 }
135};
136
137// isa<X> - Return true if the parameter to the template is an instance of the
138// template type argument. Used like this:
139//
140// if (isa<Type>(myVal)) { ... }
141//
142template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
143 return isa_impl_wrap<X, const Y,
6
Calling 'isa_impl_wrap::doit'
23
Returning from 'isa_impl_wrap::doit'
28
Calling 'isa_impl_wrap::doit'
44
Returning from 'isa_impl_wrap::doit'
144 typename simplify_type<const Y>::SimpleType>::doit(Val);
145}
146
147//===----------------------------------------------------------------------===//
148// cast<x> Support Templates
149//===----------------------------------------------------------------------===//
150
151template<class To, class From> struct cast_retty;
152
153// Calculate what type the 'cast' function should return, based on a requested
154// type of To and a source type of From.
155template<class To, class From> struct cast_retty_impl {
156 using ret_type = To &; // Normal case, return Ty&
157};
158template<class To, class From> struct cast_retty_impl<To, const From> {
159 using ret_type = const To &; // Normal case, return Ty&
160};
161
162template<class To, class From> struct cast_retty_impl<To, From*> {
163 using ret_type = To *; // Pointer arg case, return Ty*
164};
165
166template<class To, class From> struct cast_retty_impl<To, const From*> {
167 using ret_type = const To *; // Constant pointer arg case, return const Ty*
168};
169
170template<class To, class From> struct cast_retty_impl<To, const From*const> {
171 using ret_type = const To *; // Constant pointer arg case, return const Ty*
172};
173
174template <class To, class From>
175struct cast_retty_impl<To, std::unique_ptr<From>> {
176private:
177 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
178 using ResultType = typename std::remove_pointer<PointerType>::type;
179
180public:
181 using ret_type = std::unique_ptr<ResultType>;
182};
183
184template<class To, class From, class SimpleFrom>
185struct cast_retty_wrap {
186 // When the simplified type and the from type are not the same, use the type
187 // simplifier to reduce the type, then reuse cast_retty_impl to get the
188 // resultant type.
189 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
190};
191
192template<class To, class FromTy>
193struct cast_retty_wrap<To, FromTy, FromTy> {
194 // When the simplified type is equal to the from type, use it directly.
195 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
196};
197
198template<class To, class From>
199struct cast_retty {
200 using ret_type = typename cast_retty_wrap<
201 To, From, typename simplify_type<From>::SimpleType>::ret_type;
202};
203
204// Ensure the non-simple values are converted using the simplify_type template
205// that may be specialized by smart pointers...
206//
207template<class To, class From, class SimpleFrom> struct cast_convert_val {
208 // This is not a simple type, use the template to simplify it...
209 static typename cast_retty<To, From>::ret_type doit(From &Val) {
210 return cast_convert_val<To, SimpleFrom,
211 typename simplify_type<SimpleFrom>::SimpleType>::doit(
212 simplify_type<From>::getSimplifiedValue(Val));
213 }
214};
215
216template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
217 // This _is_ a simple type, just cast it.
218 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
219 typename cast_retty<To, FromTy>::ret_type Res2
220 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
221 return Res2;
222 }
223};
224
225template <class X> struct is_simple_type {
226 static const bool value =
227 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
228};
229
230// cast<X> - Return the argument parameter cast to the specified type. This
231// casting operator asserts that the type is correct, so it does not return null
232// on failure. It does not allow a null argument (use cast_or_null for that).
233// It is typically used like this:
234//
235// cast<Instruction>(myVal)->getParent()
236//
237template <class X, class Y>
238inline typename std::enable_if<!is_simple_type<Y>::value,
239 typename cast_retty<X, const Y>::ret_type>::type
240cast(const Y &Val) {
241 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h"
, 241, __extension__ __PRETTY_FUNCTION__))
;
242 return cast_convert_val<
243 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
244}
245
246template <class X, class Y>
247inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
248 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h"
, 248, __extension__ __PRETTY_FUNCTION__))
;
249 return cast_convert_val<X, Y,
250 typename simplify_type<Y>::SimpleType>::doit(Val);
251}
252
253template <class X, class Y>
254inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h"
, 255, __extension__ __PRETTY_FUNCTION__))
;
27
Within the expansion of the macro 'assert':
a
Calling 'isa'
b
Returning from 'isa'
256 return cast_convert_val<X, Y*,
45
Calling 'cast_convert_val::doit'
46
Returning from 'cast_convert_val::doit'
257 typename simplify_type<Y*>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
262cast(std::unique_ptr<Y> &&Val) {
263 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) &&
"cast<Ty>() argument of incompatible type!") ? void (0
) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h"
, 263, __extension__ __PRETTY_FUNCTION__))
;
264 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
265 return ret_type(
266 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
267 Val.release()));
268}
269
270// cast_or_null<X> - Functionally identical to cast, except that a null value is
271// accepted.
272//
273template <class X, class Y>
274LLVM_NODISCARD[[clang::warn_unused_result]] inline
275 typename std::enable_if<!is_simple_type<Y>::value,
276 typename cast_retty<X, const Y>::ret_type>::type
277 cast_or_null(const Y &Val) {
278 if (!Val)
279 return nullptr;
280 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h"
, 280, __extension__ __PRETTY_FUNCTION__))
;
281 return cast<X>(Val);
282}
283
284template <class X, class Y>
285LLVM_NODISCARD[[clang::warn_unused_result]] inline
286 typename std::enable_if<!is_simple_type<Y>::value,
287 typename cast_retty<X, Y>::ret_type>::type
288 cast_or_null(Y &Val) {
289 if (!Val)
290 return nullptr;
291 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h"
, 291, __extension__ __PRETTY_FUNCTION__))
;
292 return cast<X>(Val);
293}
294
295template <class X, class Y>
296LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
297cast_or_null(Y *Val) {
298 if (!Val) return nullptr;
299 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h"
, 299, __extension__ __PRETTY_FUNCTION__))
;
300 return cast<X>(Val);
301}
302
303template <class X, class Y>
304inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
305cast_or_null(std::unique_ptr<Y> &&Val) {
306 if (!Val)
307 return nullptr;
308 return cast<X>(std::move(Val));
309}
310
311// dyn_cast<X> - Return the argument parameter cast to the specified type. This
312// casting operator returns null if the argument is of the wrong type, so it can
313// be used to test for a type as well as cast if successful. This should be
314// used in the context of an if statement like this:
315//
316// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
317//
318
319template <class X, class Y>
320LLVM_NODISCARD[[clang::warn_unused_result]] inline
321 typename std::enable_if<!is_simple_type<Y>::value,
322 typename cast_retty<X, const Y>::ret_type>::type
323 dyn_cast(const Y &Val) {
324 return isa<X>(Val) ? cast<X>(Val) : nullptr;
325}
326
327template <class X, class Y>
328LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
329 return isa<X>(Val) ? cast<X>(Val) : nullptr;
330}
331
332template <class X, class Y>
333LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
334 return isa<X>(Val) ? cast<X>(Val) : nullptr;
5
Calling 'isa'
24
Returning from 'isa'
25
'?' condition is true
26
Calling 'cast'
47
Returning from 'cast'
335}
336
337// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
338// value is accepted.
339//
340template <class X, class Y>
341LLVM_NODISCARD[[clang::warn_unused_result]] inline
342 typename std::enable_if<!is_simple_type<Y>::value,
343 typename cast_retty<X, const Y>::ret_type>::type
344 dyn_cast_or_null(const Y &Val) {
345 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
346}
347
348template <class X, class Y>
349LLVM_NODISCARD[[clang::warn_unused_result]] inline
350 typename std::enable_if<!is_simple_type<Y>::value,
351 typename cast_retty<X, Y>::ret_type>::type
352 dyn_cast_or_null(Y &Val) {
353 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
354}
355
356template <class X, class Y>
357LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
358dyn_cast_or_null(Y *Val) {
359 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
360}
361
362// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
363// taking ownership of the input pointer iff isa<X>(Val) is true. If the
364// cast is successful, From refers to nullptr on exit and the casted value
365// is returned. If the cast is unsuccessful, the function returns nullptr
366// and From is unchanged.
367template <class X, class Y>
368LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
369 -> decltype(cast<X>(Val)) {
370 if (!isa<X>(Val))
371 return nullptr;
372 return cast<X>(std::move(Val));
373}
374
375template <class X, class Y>
376LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val)
377 -> decltype(cast<X>(Val)) {
378 return unique_dyn_cast<X, Y>(Val);
379}
380
381// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
382// a null value is accepted.
383template <class X, class Y>
384LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
385 -> decltype(cast<X>(Val)) {
386 if (!Val)
387 return nullptr;
388 return unique_dyn_cast<X, Y>(Val);
389}
390
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val)
393 -> decltype(cast<X>(Val)) {
394 return unique_dyn_cast_or_null<X, Y>(Val);
395}
396
397} // end namespace llvm
398
399#endif // LLVM_SUPPORT_CASTING_H

/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h

1//===- llvm/TableGen/Record.h - Classes for Table Records -------*- C++ -*-===//
2//
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//
10// This file defines the main TableGen data structures, including the TableGen
11// types, values, and high-level data structures.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_TABLEGEN_RECORD_H
16#define LLVM_TABLEGEN_RECORD_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/FoldingSet.h"
20#include "llvm/ADT/PointerIntPair.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/Casting.h"
24#include "llvm/Support/ErrorHandling.h"
25#include "llvm/Support/SMLoc.h"
26#include "llvm/Support/TrailingObjects.h"
27#include "llvm/Support/raw_ostream.h"
28#include <algorithm>
29#include <cassert>
30#include <cstddef>
31#include <cstdint>
32#include <map>
33#include <memory>
34#include <string>
35#include <utility>
36#include <vector>
37
38namespace llvm {
39
40class ListRecTy;
41struct MultiClass;
42class Record;
43class RecordKeeper;
44class RecordVal;
45class StringInit;
46
47//===----------------------------------------------------------------------===//
48// Type Classes
49//===----------------------------------------------------------------------===//
50
51class RecTy {
52public:
53 /// \brief Subclass discriminator (for dyn_cast<> et al.)
54 enum RecTyKind {
55 BitRecTyKind,
56 BitsRecTyKind,
57 CodeRecTyKind,
58 IntRecTyKind,
59 StringRecTyKind,
60 ListRecTyKind,
61 DagRecTyKind,
62 RecordRecTyKind
63 };
64
65private:
66 RecTyKind Kind;
67 ListRecTy *ListTy = nullptr;
68
69public:
70 RecTy(RecTyKind K) : Kind(K) {}
71 virtual ~RecTy() = default;
72
73 RecTyKind getRecTyKind() const { return Kind; }
74
75 virtual std::string getAsString() const = 0;
76 void print(raw_ostream &OS) const { OS << getAsString(); }
77 void dump() const;
78
79 /// Return true if all values of 'this' type can be converted to the specified
80 /// type.
81 virtual bool typeIsConvertibleTo(const RecTy *RHS) const;
82
83 /// Returns the type representing list<this>.
84 ListRecTy *getListTy();
85};
86
87inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) {
88 Ty.print(OS);
89 return OS;
90}
91
92/// 'bit' - Represent a single bit
93class BitRecTy : public RecTy {
94 static BitRecTy Shared;
95
96 BitRecTy() : RecTy(BitRecTyKind) {}
97
98public:
99 static bool classof(const RecTy *RT) {
100 return RT->getRecTyKind() == BitRecTyKind;
101 }
102
103 static BitRecTy *get() { return &Shared; }
104
105 std::string getAsString() const override { return "bit"; }
106
107 bool typeIsConvertibleTo(const RecTy *RHS) const override;
108};
109
110/// 'bits<n>' - Represent a fixed number of bits
111class BitsRecTy : public RecTy {
112 unsigned Size;
113
114 explicit BitsRecTy(unsigned Sz) : RecTy(BitsRecTyKind), Size(Sz) {}
115
116public:
117 static bool classof(const RecTy *RT) {
118 return RT->getRecTyKind() == BitsRecTyKind;
119 }
120
121 static BitsRecTy *get(unsigned Sz);
122
123 unsigned getNumBits() const { return Size; }
124
125 std::string getAsString() const override;
126
127 bool typeIsConvertibleTo(const RecTy *RHS) const override;
128};
129
130/// 'code' - Represent a code fragment
131class CodeRecTy : public RecTy {
132 static CodeRecTy Shared;
133
134 CodeRecTy() : RecTy(CodeRecTyKind) {}
135
136public:
137 static bool classof(const RecTy *RT) {
138 return RT->getRecTyKind() == CodeRecTyKind;
139 }
140
141 static CodeRecTy *get() { return &Shared; }
142
143 std::string getAsString() const override { return "code"; }
144};
145
146/// 'int' - Represent an integer value of no particular size
147class IntRecTy : public RecTy {
148 static IntRecTy Shared;
149
150 IntRecTy() : RecTy(IntRecTyKind) {}
151
152public:
153 static bool classof(const RecTy *RT) {
154 return RT->getRecTyKind() == IntRecTyKind;
155 }
156
157 static IntRecTy *get() { return &Shared; }
158
159 std::string getAsString() const override { return "int"; }
160
161 bool typeIsConvertibleTo(const RecTy *RHS) const override;
162};
163
164/// 'string' - Represent an string value
165class StringRecTy : public RecTy {
166 static StringRecTy Shared;
167
168 StringRecTy() : RecTy(StringRecTyKind) {}
169
170public:
171 static bool classof(const RecTy *RT) {
172 return RT->getRecTyKind() == StringRecTyKind ||
173 RT->getRecTyKind() == CodeRecTyKind;
174 }
175
176 static StringRecTy *get() { return &Shared; }
177
178 std::string getAsString() const override;
179};
180
181/// 'list<Ty>' - Represent a list of values, all of which must be of
182/// the specified type.
183class ListRecTy : public RecTy {
184 friend ListRecTy *RecTy::getListTy();
185
186 RecTy *Ty;
187
188 explicit ListRecTy(RecTy *T) : RecTy(ListRecTyKind), Ty(T) {}
189
190public:
191 static bool classof(const RecTy *RT) {
192 return RT->getRecTyKind() == ListRecTyKind;
193 }
194
195 static ListRecTy *get(RecTy *T) { return T->getListTy(); }
196 RecTy *getElementType() const { return Ty; }
197
198 std::string getAsString() const override;
199
200 bool typeIsConvertibleTo(const RecTy *RHS) const override;
201};
202
203/// 'dag' - Represent a dag fragment
204class DagRecTy : public RecTy {
205 static DagRecTy Shared;
206
207 DagRecTy() : RecTy(DagRecTyKind) {}
208
209public:
210 static bool classof(const RecTy *RT) {
211 return RT->getRecTyKind() == DagRecTyKind;
212 }
213
214 static DagRecTy *get() { return &Shared; }
215
216 std::string getAsString() const override;
217};
218
219/// '[classname]' - Represent an instance of a class, such as:
220/// (R32 X = EAX).
221class RecordRecTy : public RecTy {
222 friend class Record;
223
224 Record *Rec;
225
226 explicit RecordRecTy(Record *R) : RecTy(RecordRecTyKind), Rec(R) {}
227
228public:
229 static bool classof(const RecTy *RT) {
230 return RT->getRecTyKind() == RecordRecTyKind;
231 }
232
233 static RecordRecTy *get(Record *R);
234
235 Record *getRecord() const { return Rec; }
236
237 std::string getAsString() const override;
238
239 bool typeIsConvertibleTo(const RecTy *RHS) const override;
240};
241
242/// Find a common type that T1 and T2 convert to.
243/// Return 0 if no such type exists.
244RecTy *resolveTypes(RecTy *T1, RecTy *T2);
245
246//===----------------------------------------------------------------------===//
247// Initializer Classes
248//===----------------------------------------------------------------------===//
249
250class Init {
251protected:
252 /// \brief Discriminator enum (for isa<>, dyn_cast<>, et al.)
253 ///
254 /// This enum is laid out by a preorder traversal of the inheritance
255 /// hierarchy, and does not contain an entry for abstract classes, as per
256 /// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst.
257 ///
258 /// We also explicitly include "first" and "last" values for each
259 /// interior node of the inheritance tree, to make it easier to read the
260 /// corresponding classof().
261 ///
262 /// We could pack these a bit tighter by not having the IK_FirstXXXInit
263 /// and IK_LastXXXInit be their own values, but that would degrade
264 /// readability for really no benefit.
265 enum InitKind : uint8_t {
266 IK_BitInit,
267 IK_FirstTypedInit,
268 IK_BitsInit,
269 IK_CodeInit,
270 IK_DagInit,
271 IK_DefInit,
272 IK_FieldInit,
273 IK_IntInit,
274 IK_ListInit,
275 IK_FirstOpInit,
276 IK_BinOpInit,
277 IK_TernOpInit,
278 IK_UnOpInit,
279 IK_LastOpInit,
280 IK_StringInit,
281 IK_VarInit,
282 IK_VarListElementInit,
283 IK_LastTypedInit,
284 IK_UnsetInit,
285 IK_VarBitInit
286 };
287
288private:
289 const InitKind Kind;
290
291protected:
292 uint8_t Opc; // Used by UnOpInit, BinOpInit, and TernOpInit
293
294private:
295 virtual void anchor();
296
297public:
298 InitKind getKind() const { return Kind; }
299
300protected:
301 explicit Init(InitKind K, uint8_t Opc = 0) : Kind(K), Opc(Opc) {}
302
303public:
304 Init(const Init &) = delete;
305 Init &operator=(const Init &) = delete;
306 virtual ~Init() = default;
307
308 /// This virtual method should be overridden by values that may
309 /// not be completely specified yet.
310 virtual bool isComplete() const { return true; }
311
312 /// Print out this value.
313 void print(raw_ostream &OS) const { OS << getAsString(); }
314
315 /// Convert this value to a string form.
316 virtual std::string getAsString() const = 0;
317 /// Convert this value to a string form,
318 /// without adding quote markers. This primaruly affects
319 /// StringInits where we will not surround the string value with
320 /// quotes.
321 virtual std::string getAsUnquotedString() const { return getAsString(); }
322
323 /// Debugging method that may be called through a debugger, just
324 /// invokes print on stderr.
325 void dump() const;
326
327 /// This virtual function converts to the appropriate
328 /// Init based on the passed in type.
329 virtual Init *convertInitializerTo(RecTy *Ty) const = 0;
330
331 /// This method is used to implement the bitrange
332 /// selection operator. Given an initializer, it selects the specified bits
333 /// out, returning them as a new init of bits type. If it is not legal to use
334 /// the bit subscript operator on this initializer, return null.
335 virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
336 return nullptr;
337 }
338
339 /// This method is used to implement the list slice
340 /// selection operator. Given an initializer, it selects the specified list
341 /// elements, returning them as a new init of list type. If it is not legal
342 /// to take a slice of this, return null.
343 virtual Init *convertInitListSlice(ArrayRef<unsigned> Elements) const {
344 return nullptr;
345 }
346
347 /// This method is used to implement the FieldInit class.
348 /// Implementors of this method should return the type of the named field if
349 /// they are of record type.
350 virtual RecTy *getFieldType(StringInit *FieldName) const {
351 return nullptr;
352 }
353
354 /// This method complements getFieldType to return the
355 /// initializer for the specified field. If getFieldType returns non-null
356 /// this method should return non-null, otherwise it returns null.
357 virtual Init *getFieldInit(Record &R, const RecordVal *RV,
358 StringInit *FieldName) const {
359 return nullptr;
360 }
361
362 /// This method is used by classes that refer to other
363 /// variables which may not be defined at the time the expression is formed.
364 /// If a value is set for the variable later, this method will be called on
365 /// users of the value to allow the value to propagate out.
366 virtual Init *resolveReferences(Record &R, const RecordVal *RV) const {
367 return const_cast<Init *>(this);
368 }
369
370 /// This method is used to return the initializer for the specified
371 /// bit.
372 virtual Init *getBit(unsigned Bit) const = 0;
373
374 /// This method is used to retrieve the initializer for bit
375 /// reference. For non-VarBitInit, it simply returns itself.
376 virtual Init *getBitVar() const { return const_cast<Init*>(this); }
377
378 /// This method is used to retrieve the bit number of a bit
379 /// reference. For non-VarBitInit, it simply returns 0.
380 virtual unsigned getBitNum() const { return 0; }
381};
382
383inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) {
384 I.print(OS); return OS;
385}
386
387/// This is the common super-class of types that have a specific,
388/// explicit, type.
389class TypedInit : public Init {
390 RecTy *Ty;
391
392protected:
393 explicit TypedInit(InitKind K, RecTy *T, uint8_t Opc = 0)
394 : Init(K, Opc), Ty(T) {}
395
396public:
397 TypedInit(const TypedInit &) = delete;
398 TypedInit &operator=(const TypedInit &) = delete;
399
400 static bool classof(const Init *I) {
401 return I->getKind() >= IK_FirstTypedInit &&
402 I->getKind() <= IK_LastTypedInit;
403 }
404
405 RecTy *getType() const { return Ty; }
406
407 Init *convertInitializerTo(RecTy *Ty) const override;
408
409 Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
410 Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
411
412 /// This method is used to implement the FieldInit class.
413 /// Implementors of this method should return the type of the named field if
414 /// they are of record type.
415 ///
416 RecTy *getFieldType(StringInit *FieldName) const override;
417
418 /// This method is used to implement
419 /// VarListElementInit::resolveReferences. If the list element is resolvable
420 /// now, we return the resolved value, otherwise we return null.
421 virtual Init *resolveListElementReference(Record &R, const RecordVal *RV,
422 unsigned Elt) const = 0;
423};
424
425/// '?' - Represents an uninitialized value
426class UnsetInit : public Init {
427 UnsetInit() : Init(IK_UnsetInit) {}
428
429public:
430 UnsetInit(const UnsetInit &) = delete;
431 UnsetInit &operator=(const UnsetInit &) = delete;
432
433 static bool classof(const Init *I) {
434 return I->getKind() == IK_UnsetInit;
435 }
436
437 static UnsetInit *get();
438
439 Init *convertInitializerTo(RecTy *Ty) const override;
440
441 Init *getBit(unsigned Bit) const override {
442 return const_cast<UnsetInit*>(this);
443 }
444
445 bool isComplete() const override { return false; }
446 std::string getAsString() const override { return "?"; }
447};
448
449/// 'true'/'false' - Represent a concrete initializer for a bit.
450class BitInit : public Init {
451 bool Value;
452
453 explicit BitInit(bool V) : Init(IK_BitInit), Value(V) {}
454
455public:
456 BitInit(const BitInit &) = delete;
457 BitInit &operator=(BitInit &) = delete;
458
459 static bool classof(const Init *I) {
460 return I->getKind() == IK_BitInit;
461 }
462
463 static BitInit *get(bool V);
464
465 bool getValue() const { return Value; }
466
467 Init *convertInitializerTo(RecTy *Ty) const override;
468
469 Init *getBit(unsigned Bit) const override {
470 assert(Bit < 1 && "Bit index out of range!")(static_cast <bool> (Bit < 1 && "Bit index out of range!"
) ? void (0) : __assert_fail ("Bit < 1 && \"Bit index out of range!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 470, __extension__ __PRETTY_FUNCTION__))
;
471 return const_cast<BitInit*>(this);
472 }
473
474 std::string getAsString() const override { return Value ? "1" : "0"; }
475};
476
477/// '{ a, b, c }' - Represents an initializer for a BitsRecTy value.
478/// It contains a vector of bits, whose size is determined by the type.
479class BitsInit final : public TypedInit, public FoldingSetNode,
480 public TrailingObjects<BitsInit, Init *> {
481 unsigned NumBits;
482
483 BitsInit(unsigned N)
484 : TypedInit(IK_BitsInit, BitsRecTy::get(N)), NumBits(N) {}
485
486public:
487 BitsInit(const BitsInit &) = delete;
488 BitsInit &operator=(const BitsInit &) = delete;
489
490 // Do not use sized deallocation due to trailing objects.
491 void operator delete(void *p) { ::operator delete(p); }
492
493 static bool classof(const Init *I) {
494 return I->getKind() == IK_BitsInit;
495 }
496
497 static BitsInit *get(ArrayRef<Init *> Range);
498
499 void Profile(FoldingSetNodeID &ID) const;
500
501 unsigned getNumBits() const { return NumBits; }
502
503 Init *convertInitializerTo(RecTy *Ty) const override;
504 Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
505
506 bool isComplete() const override {
507 for (unsigned i = 0; i != getNumBits(); ++i)
508 if (!getBit(i)->isComplete()) return false;
509 return true;
510 }
511
512 bool allInComplete() const {
513 for (unsigned i = 0; i != getNumBits(); ++i)
514 if (getBit(i)->isComplete()) return false;
515 return true;
516 }
517
518 std::string getAsString() const override;
519
520 /// This method is used to implement
521 /// VarListElementInit::resolveReferences. If the list element is resolvable
522 /// now, we return the resolved value, otherwise we return null.
523 Init *resolveListElementReference(Record &R, const RecordVal *RV,
524 unsigned Elt) const override {
525 llvm_unreachable("Illegal element reference off bits<n>")::llvm::llvm_unreachable_internal("Illegal element reference off bits<n>"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 525)
;
526 }
527
528 Init *resolveReferences(Record &R, const RecordVal *RV) const override;
529
530 Init *getBit(unsigned Bit) const override {
531 assert(Bit < NumBits && "Bit index out of range!")(static_cast <bool> (Bit < NumBits && "Bit index out of range!"
) ? void (0) : __assert_fail ("Bit < NumBits && \"Bit index out of range!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 531, __extension__ __PRETTY_FUNCTION__))
;
532 return getTrailingObjects<Init *>()[Bit];
533 }
534};
535
536/// '7' - Represent an initialization by a literal integer value.
537class IntInit : public TypedInit {
538 int64_t Value;
539
540 explicit IntInit(int64_t V)
541 : TypedInit(IK_IntInit, IntRecTy::get()), Value(V) {}
542
543public:
544 IntInit(const IntInit &) = delete;
545 IntInit &operator=(const IntInit &) = delete;
546
547 static bool classof(const Init *I) {
548 return I->getKind() == IK_IntInit;
549 }
550
551 static IntInit *get(int64_t V);
552
553 int64_t getValue() const { return Value; }
554
555 Init *convertInitializerTo(RecTy *Ty) const override;
556 Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
557
558 std::string getAsString() const override;
559
560 /// This method is used to implement
561 /// VarListElementInit::resolveReferences. If the list element is resolvable
562 /// now, we return the resolved value, otherwise we return null.
563 Init *resolveListElementReference(Record &R, const RecordVal *RV,
564 unsigned Elt) const override {
565 llvm_unreachable("Illegal element reference off int")::llvm::llvm_unreachable_internal("Illegal element reference off int"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 565)
;
566 }
567
568 Init *getBit(unsigned Bit) const override {
569 return BitInit::get((Value & (1ULL << Bit)) != 0);
570 }
571};
572
573/// "foo" - Represent an initialization by a string value.
574class StringInit : public TypedInit {
575 StringRef Value;
576
577 explicit StringInit(StringRef V)
578 : TypedInit(IK_StringInit, StringRecTy::get()), Value(V) {}
579
580public:
581 StringInit(const StringInit &) = delete;
582 StringInit &operator=(const StringInit &) = delete;
583
584 static bool classof(const Init *I) {
585 return I->getKind() == IK_StringInit;
586 }
587
588 static StringInit *get(StringRef);
589
590 StringRef getValue() const { return Value; }
591
592 Init *convertInitializerTo(RecTy *Ty) const override;
593
594 std::string getAsString() const override { return "\"" + Value.str() + "\""; }
595
596 std::string getAsUnquotedString() const override { return Value; }
597
598 /// resolveListElementReference - This method is used to implement
599 /// VarListElementInit::resolveReferences. If the list element is resolvable
600 /// now, we return the resolved value, otherwise we return null.
601 Init *resolveListElementReference(Record &R, const RecordVal *RV,
602 unsigned Elt) const override {
603 llvm_unreachable("Illegal element reference off string")::llvm::llvm_unreachable_internal("Illegal element reference off string"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 603)
;
604 }
605
606 Init *getBit(unsigned Bit) const override {
607 llvm_unreachable("Illegal bit reference off string")::llvm::llvm_unreachable_internal("Illegal bit reference off string"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 607)
;
608 }
609};
610
611class CodeInit : public TypedInit {
612 StringRef Value;
613
614 explicit CodeInit(StringRef V)
615 : TypedInit(IK_CodeInit, static_cast<RecTy *>(CodeRecTy::get())),
616 Value(V) {}
617
618public:
619 CodeInit(const StringInit &) = delete;
620 CodeInit &operator=(const StringInit &) = delete;
621
622 static bool classof(const Init *I) {
623 return I->getKind() == IK_CodeInit;
624 }
625
626 static CodeInit *get(StringRef);
627
628 StringRef getValue() const { return Value; }
629
630 Init *convertInitializerTo(RecTy *Ty) const override;
631
632 std::string getAsString() const override {
633 return "[{" + Value.str() + "}]";
634 }
635
636 std::string getAsUnquotedString() const override { return Value; }
637
638 /// This method is used to implement
639 /// VarListElementInit::resolveReferences. If the list element is resolvable
640 /// now, we return the resolved value, otherwise we return null.
641 Init *resolveListElementReference(Record &R, const RecordVal *RV,
642 unsigned Elt) const override {
643 llvm_unreachable("Illegal element reference off string")::llvm::llvm_unreachable_internal("Illegal element reference off string"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 643)
;
644 }
645
646 Init *getBit(unsigned Bit) const override {
647 llvm_unreachable("Illegal bit reference off string")::llvm::llvm_unreachable_internal("Illegal bit reference off string"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 647)
;
648 }
649};
650
651/// [AL, AH, CL] - Represent a list of defs
652///
653class ListInit final : public TypedInit, public FoldingSetNode,
654 public TrailingObjects<ListInit, Init *> {
655 unsigned NumValues;
656
657public:
658 using const_iterator = Init *const *;
659
660private:
661 explicit ListInit(unsigned N, RecTy *EltTy)
662 : TypedInit(IK_ListInit, ListRecTy::get(EltTy)), NumValues(N) {}
663
664public:
665 ListInit(const ListInit &) = delete;
666 ListInit &operator=(const ListInit &) = delete;
667
668 // Do not use sized deallocation due to trailing objects.
669 void operator delete(void *p) { ::operator delete(p); }
670
671 static bool classof(const Init *I) {
672 return I->getKind() == IK_ListInit;
673 }
674 static ListInit *get(ArrayRef<Init *> Range, RecTy *EltTy);
675
676 void Profile(FoldingSetNodeID &ID) const;
677
678 Init *getElement(unsigned i) const {
679 assert(i < NumValues && "List element index out of range!")(static_cast <bool> (i < NumValues && "List element index out of range!"
) ? void (0) : __assert_fail ("i < NumValues && \"List element index out of range!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 679, __extension__ __PRETTY_FUNCTION__))
;
680 return getTrailingObjects<Init *>()[i];
681 }
682
683 Record *getElementAsRecord(unsigned i) const;
684
685 Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
686
687 Init *convertInitializerTo(RecTy *Ty) const override;
688
689 /// This method is used by classes that refer to other
690 /// variables which may not be defined at the time they expression is formed.
691 /// If a value is set for the variable later, this method will be called on
692 /// users of the value to allow the value to propagate out.
693 ///
694 Init *resolveReferences(Record &R, const RecordVal *RV) const override;
695
696 std::string getAsString() const override;
697
698 ArrayRef<Init*> getValues() const {
699 return makeArrayRef(getTrailingObjects<Init *>(), NumValues);
700 }
701
702 const_iterator begin() const { return getTrailingObjects<Init *>(); }
703 const_iterator end () const { return begin() + NumValues; }
704
705 size_t size () const { return NumValues; }
706 bool empty() const { return NumValues == 0; }
707
708 /// This method is used to implement
709 /// VarListElementInit::resolveReferences. If the list element is resolvable
710 /// now, we return the resolved value, otherwise we return null.
711 Init *resolveListElementReference(Record &R, const RecordVal *RV,
712 unsigned Elt) const override;
713
714 Init *getBit(unsigned Bit) const override {
715 llvm_unreachable("Illegal bit reference off list")::llvm::llvm_unreachable_internal("Illegal bit reference off list"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 715)
;
716 }
717};
718
719/// Base class for operators
720///
721class OpInit : public TypedInit {
722protected:
723 explicit OpInit(InitKind K, RecTy *Type, uint8_t Opc)
724 : TypedInit(K, Type, Opc) {}
725
726public:
727 OpInit(const OpInit &) = delete;
728 OpInit &operator=(OpInit &) = delete;
729
730 static bool classof(const Init *I) {
731 return I->getKind() >= IK_FirstOpInit &&
732 I->getKind() <= IK_LastOpInit;
733 }
734
735 // Clone - Clone this operator, replacing arguments with the new list
736 virtual OpInit *clone(ArrayRef<Init *> Operands) const = 0;
737
738 virtual unsigned getNumOperands() const = 0;
739 virtual Init *getOperand(unsigned i) const = 0;
740
741 // Fold - If possible, fold this to a simpler init. Return this if not
742 // possible to fold.
743 virtual Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const = 0;
744
745 Init *resolveListElementReference(Record &R, const RecordVal *RV,
746 unsigned Elt) const override;
747
748 Init *getBit(unsigned Bit) const override;
749};
750
751/// !op (X) - Transform an init.
752///
753class UnOpInit : public OpInit, public FoldingSetNode {
754public:
755 enum UnaryOp : uint8_t { CAST, HEAD, TAIL, EMPTY };
756
757private:
758 Init *LHS;
759
760 UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type)
761 : OpInit(IK_UnOpInit, Type, opc), LHS(lhs) {}
762
763public:
764 UnOpInit(const UnOpInit &) = delete;
765 UnOpInit &operator=(const UnOpInit &) = delete;
766
767 static bool classof(const Init *I) {
768 return I->getKind() == IK_UnOpInit;
769 }
770
771 static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type);
772
773 void Profile(FoldingSetNodeID &ID) const;
774
775 // Clone - Clone this operator, replacing arguments with the new list
776 OpInit *clone(ArrayRef<Init *> Operands) const override {
777 assert(Operands.size() == 1 &&(static_cast <bool> (Operands.size() == 1 && "Wrong number of operands for unary operation"
) ? void (0) : __assert_fail ("Operands.size() == 1 && \"Wrong number of operands for unary operation\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 778, __extension__ __PRETTY_FUNCTION__))
778 "Wrong number of operands for unary operation")(static_cast <bool> (Operands.size() == 1 && "Wrong number of operands for unary operation"
) ? void (0) : __assert_fail ("Operands.size() == 1 && \"Wrong number of operands for unary operation\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 778, __extension__ __PRETTY_FUNCTION__))
;
779 return UnOpInit::get(getOpcode(), *Operands.begin(), getType());
780 }
781
782 unsigned getNumOperands() const override { return 1; }
783
784 Init *getOperand(unsigned i) const override {
785 assert(i == 0 && "Invalid operand id for unary operator")(static_cast <bool> (i == 0 && "Invalid operand id for unary operator"
) ? void (0) : __assert_fail ("i == 0 && \"Invalid operand id for unary operator\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 785, __extension__ __PRETTY_FUNCTION__))
;
786 return getOperand();
787 }
788
789 UnaryOp getOpcode() const { return (UnaryOp)Opc; }
790 Init *getOperand() const { return LHS; }
791
792 // Fold - If possible, fold this to a simpler init. Return this if not
793 // possible to fold.
794 Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override;
795
796 Init *resolveReferences(Record &R, const RecordVal *RV) const override;
797
798 std::string getAsString() const override;
799};
800
801/// !op (X, Y) - Combine two inits.
802class BinOpInit : public OpInit, public FoldingSetNode {
803public:
804 enum BinaryOp : uint8_t { ADD, AND, OR, SHL, SRA, SRL, LISTCONCAT,
805 STRCONCAT, CONCAT, EQ };
806
807private:
808 Init *LHS, *RHS;
809
810 BinOpInit(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type) :
811 OpInit(IK_BinOpInit, Type, opc), LHS(lhs), RHS(rhs) {}
812
813public:
814 BinOpInit(const BinOpInit &) = delete;
815 BinOpInit &operator=(const BinOpInit &) = delete;
816
817 static bool classof(const Init *I) {
818 return I->getKind() == IK_BinOpInit;
819 }
820
821 static BinOpInit *get(BinaryOp opc, Init *lhs, Init *rhs,
822 RecTy *Type);
823
824 void Profile(FoldingSetNodeID &ID) const;
825
826 // Clone - Clone this operator, replacing arguments with the new list
827 OpInit *clone(ArrayRef<Init *> Operands) const override {
828 assert(Operands.size() == 2 &&(static_cast <bool> (Operands.size() == 2 && "Wrong number of operands for binary operation"
) ? void (0) : __assert_fail ("Operands.size() == 2 && \"Wrong number of operands for binary operation\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 829, __extension__ __PRETTY_FUNCTION__))
829 "Wrong number of operands for binary operation")(static_cast <bool> (Operands.size() == 2 && "Wrong number of operands for binary operation"
) ? void (0) : __assert_fail ("Operands.size() == 2 && \"Wrong number of operands for binary operation\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 829, __extension__ __PRETTY_FUNCTION__))
;
830 return BinOpInit::get(getOpcode(), Operands[0], Operands[1], getType());
831 }
832
833 unsigned getNumOperands() const override { return 2; }
834 Init *getOperand(unsigned i) const override {
835 switch (i) {
836 default: llvm_unreachable("Invalid operand id for binary operator")::llvm::llvm_unreachable_internal("Invalid operand id for binary operator"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 836)
;
837 case 0: return getLHS();
838 case 1: return getRHS();
839 }
840 }
841
842 BinaryOp getOpcode() const { return (BinaryOp)Opc; }
843 Init *getLHS() const { return LHS; }
844 Init *getRHS() const { return RHS; }
845
846 // Fold - If possible, fold this to a simpler init. Return this if not
847 // possible to fold.
848 Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override;
849
850 Init *resolveReferences(Record &R, const RecordVal *RV) const override;
851
852 std::string getAsString() const override;
853};
854
855/// !op (X, Y, Z) - Combine two inits.
856class TernOpInit : public OpInit, public FoldingSetNode {
857public:
858 enum TernaryOp : uint8_t { SUBST, FOREACH, IF };
859
860private:
861 Init *LHS, *MHS, *RHS;
862
863 TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
864 RecTy *Type) :
865 OpInit(IK_TernOpInit, Type, opc), LHS(lhs), MHS(mhs), RHS(rhs) {}
866
867public:
868 TernOpInit(const TernOpInit &) = delete;
869 TernOpInit &operator=(const TernOpInit &) = delete;
870
871 static bool classof(const Init *I) {
872 return I->getKind() == IK_TernOpInit;
873 }
874
875 static TernOpInit *get(TernaryOp opc, Init *lhs,
876 Init *mhs, Init *rhs,
877 RecTy *Type);
878
879 void Profile(FoldingSetNodeID &ID) const;
880
881 // Clone - Clone this operator, replacing arguments with the new list
882 OpInit *clone(ArrayRef<Init *> Operands) const override {
883 assert(Operands.size() == 3 &&(static_cast <bool> (Operands.size() == 3 && "Wrong number of operands for ternary operation"
) ? void (0) : __assert_fail ("Operands.size() == 3 && \"Wrong number of operands for ternary operation\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 884, __extension__ __PRETTY_FUNCTION__))
884 "Wrong number of operands for ternary operation")(static_cast <bool> (Operands.size() == 3 && "Wrong number of operands for ternary operation"
) ? void (0) : __assert_fail ("Operands.size() == 3 && \"Wrong number of operands for ternary operation\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 884, __extension__ __PRETTY_FUNCTION__))
;
885 return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2],
886 getType());
887 }
888
889 unsigned getNumOperands() const override { return 3; }
890 Init *getOperand(unsigned i) const override {
891 switch (i) {
892 default: llvm_unreachable("Invalid operand id for ternary operator")::llvm::llvm_unreachable_internal("Invalid operand id for ternary operator"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 892)
;
893 case 0: return getLHS();
894 case 1: return getMHS();
895 case 2: return getRHS();
896 }
897 }
898
899 TernaryOp getOpcode() const { return (TernaryOp)Opc; }
900 Init *getLHS() const { return LHS; }
901 Init *getMHS() const { return MHS; }
902 Init *getRHS() const { return RHS; }
903
904 // Fold - If possible, fold this to a simpler init. Return this if not
905 // possible to fold.
906 Init *Fold(Record *CurRec, MultiClass *CurMultiClass) const override;
907
908 bool isComplete() const override { return false; }
909
910 Init *resolveReferences(Record &R, const RecordVal *RV) const override;
911
912 std::string getAsString() const override;
913};
914
915/// 'Opcode' - Represent a reference to an entire variable object.
916class VarInit : public TypedInit {
917 Init *VarName;
918
919 explicit VarInit(Init *VN, RecTy *T)
920 : TypedInit(IK_VarInit, T), VarName(VN) {}
921
922public:
923 VarInit(const VarInit &) = delete;
924 VarInit &operator=(const VarInit &) = delete;
925
926 static bool classof(const Init *I) {
927 return I->getKind() == IK_VarInit;
928 }
929
930 static VarInit *get(StringRef VN, RecTy *T);
931 static VarInit *get(Init *VN, RecTy *T);
932
933 StringRef getName() const;
934 Init *getNameInit() const { return VarName; }
935
936 std::string getNameInitAsString() const {
937 return getNameInit()->getAsUnquotedString();
938 }
939
940 Init *resolveListElementReference(Record &R, const RecordVal *RV,
941 unsigned Elt) const override;
942
943 RecTy *getFieldType(StringInit *FieldName) const override;
944 Init *getFieldInit(Record &R, const RecordVal *RV,
945 StringInit *FieldName) const override;
946
947 /// This method is used by classes that refer to other
948 /// variables which may not be defined at the time they expression is formed.
949 /// If a value is set for the variable later, this method will be called on
950 /// users of the value to allow the value to propagate out.
951 ///
952 Init *resolveReferences(Record &R, const RecordVal *RV) const override;
953
954 Init *getBit(unsigned Bit) const override;
955
956 std::string getAsString() const override { return getName(); }
957};
958
959/// Opcode{0} - Represent access to one bit of a variable or field.
960class VarBitInit : public Init {
961 TypedInit *TI;
962 unsigned Bit;
963
964 VarBitInit(TypedInit *T, unsigned B) : Init(IK_VarBitInit), TI(T), Bit(B) {
965 assert(T->getType() &&(static_cast <bool> (T->getType() && (isa<
IntRecTy>(T->getType()) || (isa<BitsRecTy>(T->
getType()) && cast<BitsRecTy>(T->getType())->
getNumBits() > B)) && "Illegal VarBitInit expression!"
) ? void (0) : __assert_fail ("T->getType() && (isa<IntRecTy>(T->getType()) || (isa<BitsRecTy>(T->getType()) && cast<BitsRecTy>(T->getType())->getNumBits() > B)) && \"Illegal VarBitInit expression!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 969, __extension__ __PRETTY_FUNCTION__))
966 (isa<IntRecTy>(T->getType()) ||(static_cast <bool> (T->getType() && (isa<
IntRecTy>(T->getType()) || (isa<BitsRecTy>(T->
getType()) && cast<BitsRecTy>(T->getType())->
getNumBits() > B)) && "Illegal VarBitInit expression!"
) ? void (0) : __assert_fail ("T->getType() && (isa<IntRecTy>(T->getType()) || (isa<BitsRecTy>(T->getType()) && cast<BitsRecTy>(T->getType())->getNumBits() > B)) && \"Illegal VarBitInit expression!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 969, __extension__ __PRETTY_FUNCTION__))
967 (isa<BitsRecTy>(T->getType()) &&(static_cast <bool> (T->getType() && (isa<
IntRecTy>(T->getType()) || (isa<BitsRecTy>(T->
getType()) && cast<BitsRecTy>(T->getType())->
getNumBits() > B)) && "Illegal VarBitInit expression!"
) ? void (0) : __assert_fail ("T->getType() && (isa<IntRecTy>(T->getType()) || (isa<BitsRecTy>(T->getType()) && cast<BitsRecTy>(T->getType())->getNumBits() > B)) && \"Illegal VarBitInit expression!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 969, __extension__ __PRETTY_FUNCTION__))
968 cast<BitsRecTy>(T->getType())->getNumBits() > B)) &&(static_cast <bool> (T->getType() && (isa<
IntRecTy>(T->getType()) || (isa<BitsRecTy>(T->
getType()) && cast<BitsRecTy>(T->getType())->
getNumBits() > B)) && "Illegal VarBitInit expression!"
) ? void (0) : __assert_fail ("T->getType() && (isa<IntRecTy>(T->getType()) || (isa<BitsRecTy>(T->getType()) && cast<BitsRecTy>(T->getType())->getNumBits() > B)) && \"Illegal VarBitInit expression!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 969, __extension__ __PRETTY_FUNCTION__))
969 "Illegal VarBitInit expression!")(static_cast <bool> (T->getType() && (isa<
IntRecTy>(T->getType()) || (isa<BitsRecTy>(T->
getType()) && cast<BitsRecTy>(T->getType())->
getNumBits() > B)) && "Illegal VarBitInit expression!"
) ? void (0) : __assert_fail ("T->getType() && (isa<IntRecTy>(T->getType()) || (isa<BitsRecTy>(T->getType()) && cast<BitsRecTy>(T->getType())->getNumBits() > B)) && \"Illegal VarBitInit expression!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 969, __extension__ __PRETTY_FUNCTION__))
;
970 }
971
972public:
973 VarBitInit(const VarBitInit &) = delete;
974 VarBitInit &operator=(const VarBitInit &) = delete;
975
976 static bool classof(const Init *I) {
977 return I->getKind() == IK_VarBitInit;
978 }
979
980 static VarBitInit *get(TypedInit *T, unsigned B);
981
982 Init *convertInitializerTo(RecTy *Ty) const override;
983
984 Init *getBitVar() const override { return TI; }
985 unsigned getBitNum() const override { return Bit; }
986
987 std::string getAsString() const override;
988 Init *resolveReferences(Record &R, const RecordVal *RV) const override;
989
990 Init *getBit(unsigned B) const override {
991 assert(B < 1 && "Bit index out of range!")(static_cast <bool> (B < 1 && "Bit index out of range!"
) ? void (0) : __assert_fail ("B < 1 && \"Bit index out of range!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 991, __extension__ __PRETTY_FUNCTION__))
;
992 return const_cast<VarBitInit*>(this);
993 }
994};
995
996/// List[4] - Represent access to one element of a var or
997/// field.
998class VarListElementInit : public TypedInit {
999 TypedInit *TI;
1000 unsigned Element;
1001
1002 VarListElementInit(TypedInit *T, unsigned E)
1003 : TypedInit(IK_VarListElementInit,
1004 cast<ListRecTy>(T->getType())->getElementType()),
1005 TI(T), Element(E) {
1006 assert(T->getType() && isa<ListRecTy>(T->getType()) &&(static_cast <bool> (T->getType() && isa<
ListRecTy>(T->getType()) && "Illegal VarBitInit expression!"
) ? void (0) : __assert_fail ("T->getType() && isa<ListRecTy>(T->getType()) && \"Illegal VarBitInit expression!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1007, __extension__ __PRETTY_FUNCTION__))
1007 "Illegal VarBitInit expression!")(static_cast <bool> (T->getType() && isa<
ListRecTy>(T->getType()) && "Illegal VarBitInit expression!"
) ? void (0) : __assert_fail ("T->getType() && isa<ListRecTy>(T->getType()) && \"Illegal VarBitInit expression!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1007, __extension__ __PRETTY_FUNCTION__))
;
1008 }
1009
1010public:
1011 VarListElementInit(const VarListElementInit &) = delete;
1012 VarListElementInit &operator=(const VarListElementInit &) = delete;
1013
1014 static bool classof(const Init *I) {
1015 return I->getKind() == IK_VarListElementInit;
1016 }
1017
1018 static VarListElementInit *get(TypedInit *T, unsigned E);
1019
1020 TypedInit *getVariable() const { return TI; }
1021 unsigned getElementNum() const { return Element; }
1022
1023 /// This method is used to implement
1024 /// VarListElementInit::resolveReferences. If the list element is resolvable
1025 /// now, we return the resolved value, otherwise we return null.
1026 Init *resolveListElementReference(Record &R, const RecordVal *RV,
1027 unsigned Elt) const override;
1028
1029 std::string getAsString() const override;
1030 Init *resolveReferences(Record &R, const RecordVal *RV) const override;
1031
1032 Init *getBit(unsigned Bit) const override;
1033};
1034
1035/// AL - Represent a reference to a 'def' in the description
1036class DefInit : public TypedInit {
1037 friend class Record;
1038
1039 Record *Def;
1040
1041 DefInit(Record *D, RecordRecTy *T) : TypedInit(IK_DefInit, T), Def(D) {}
1042
1043public:
1044 DefInit(const DefInit &) = delete;
1045 DefInit &operator=(const DefInit &) = delete;
1046
1047 static bool classof(const Init *I) {
1048 return I->getKind() == IK_DefInit;
16
Calling 'Init::getKind'
17
Returning from 'Init::getKind'
18
Assuming the condition is true
38
Calling 'Init::getKind'
39
Returning from 'Init::getKind'
1049 }
1050
1051 static DefInit *get(Record*);
1052
1053 Init *convertInitializerTo(RecTy *Ty) const override;
1054
1055 Record *getDef() const { return Def; }
1056
1057 //virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits);
1058
1059 RecTy *getFieldType(StringInit *FieldName) const override;
1060 Init *getFieldInit(Record &R, const RecordVal *RV,
1061 StringInit *FieldName) const override;
1062
1063 std::string getAsString() const override;
1064
1065 Init *getBit(unsigned Bit) const override {
1066 llvm_unreachable("Illegal bit reference off def")::llvm::llvm_unreachable_internal("Illegal bit reference off def"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1066)
;
1067 }
1068
1069 /// This method is used to implement
1070 /// VarListElementInit::resolveReferences. If the list element is resolvable
1071 /// now, we return the resolved value, otherwise we return null.
1072 Init *resolveListElementReference(Record &R, const RecordVal *RV,
1073 unsigned Elt) const override {
1074 llvm_unreachable("Illegal element reference off def")::llvm::llvm_unreachable_internal("Illegal element reference off def"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1074)
;
1075 }
1076};
1077
1078/// X.Y - Represent a reference to a subfield of a variable
1079class FieldInit : public TypedInit {
1080 Init *Rec; // Record we are referring to
1081 StringInit *FieldName; // Field we are accessing
1082
1083 FieldInit(Init *R, StringInit *FN)
1084 : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) {
1085 assert(getType() && "FieldInit with non-record type!")(static_cast <bool> (getType() && "FieldInit with non-record type!"
) ? void (0) : __assert_fail ("getType() && \"FieldInit with non-record type!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1085, __extension__ __PRETTY_FUNCTION__))
;
1086 }
1087
1088public:
1089 FieldInit(const FieldInit &) = delete;
1090 FieldInit &operator=(const FieldInit &) = delete;
1091
1092 static bool classof(const Init *I) {
1093 return I->getKind() == IK_FieldInit;
1094 }
1095
1096 static FieldInit *get(Init *R, StringInit *FN);
1097
1098 Init *getBit(unsigned Bit) const override;
1099
1100 Init *resolveListElementReference(Record &R, const RecordVal *RV,
1101 unsigned Elt) const override;
1102
1103 Init *resolveReferences(Record &R, const RecordVal *RV) const override;
1104
1105 std::string getAsString() const override {
1106 return Rec->getAsString() + "." + FieldName->getValue().str();
1107 }
1108};
1109
1110/// (v a, b) - Represent a DAG tree value. DAG inits are required
1111/// to have at least one value then a (possibly empty) list of arguments. Each
1112/// argument can have a name associated with it.
1113class DagInit final : public TypedInit, public FoldingSetNode,
1114 public TrailingObjects<DagInit, Init *, StringInit *> {
1115 friend TrailingObjects;
1116
1117 Init *Val;
1118 StringInit *ValName;
1119 unsigned NumArgs;
1120 unsigned NumArgNames;
1121
1122 DagInit(Init *V, StringInit *VN, unsigned NumArgs, unsigned NumArgNames)
1123 : TypedInit(IK_DagInit, DagRecTy::get()), Val(V), ValName(VN),
1124 NumArgs(NumArgs), NumArgNames(NumArgNames) {}
1125
1126 size_t numTrailingObjects(OverloadToken<Init *>) const { return NumArgs; }
1127
1128public:
1129 DagInit(const DagInit &) = delete;
1130 DagInit &operator=(const DagInit &) = delete;
1131
1132 static bool classof(const Init *I) {
1133 return I->getKind() == IK_DagInit;
1134 }
1135
1136 static DagInit *get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1137 ArrayRef<StringInit*> NameRange);
1138 static DagInit *get(Init *V, StringInit *VN,
1139 ArrayRef<std::pair<Init*, StringInit*>> Args);
1140
1141 void Profile(FoldingSetNodeID &ID) const;
1142
1143 Init *convertInitializerTo(RecTy *Ty) const override;
1144
1145 Init *getOperator() const { return Val; }
1146
1147 StringInit *getName() const { return ValName; }
1148
1149 StringRef getNameStr() const {
1150 return ValName ? ValName->getValue() : StringRef();
1151 }
1152
1153 unsigned getNumArgs() const { return NumArgs; }
1154
1155 Init *getArg(unsigned Num) const {
1156 assert(Num < NumArgs && "Arg number out of range!")(static_cast <bool> (Num < NumArgs && "Arg number out of range!"
) ? void (0) : __assert_fail ("Num < NumArgs && \"Arg number out of range!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1156, __extension__ __PRETTY_FUNCTION__))
;
1157 return getTrailingObjects<Init *>()[Num];
1158 }
1159
1160 StringInit *getArgName(unsigned Num) const {
1161 assert(Num < NumArgNames && "Arg number out of range!")(static_cast <bool> (Num < NumArgNames && "Arg number out of range!"
) ? void (0) : __assert_fail ("Num < NumArgNames && \"Arg number out of range!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1161, __extension__ __PRETTY_FUNCTION__))
;
1162 return getTrailingObjects<StringInit *>()[Num];
1163 }
1164
1165 StringRef getArgNameStr(unsigned Num) const {
1166 StringInit *Init = getArgName(Num);
1167 return Init ? Init->getValue() : StringRef();
1168 }
1169
1170 ArrayRef<Init *> getArgs() const {
1171 return makeArrayRef(getTrailingObjects<Init *>(), NumArgs);
1172 }
1173
1174 ArrayRef<StringInit *> getArgNames() const {
1175 return makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames);
1176 }
1177
1178 Init *resolveReferences(Record &R, const RecordVal *RV) const override;
1179
1180 std::string getAsString() const override;
1181
1182 using const_arg_iterator = SmallVectorImpl<Init*>::const_iterator;
1183 using const_name_iterator = SmallVectorImpl<StringInit*>::const_iterator;
1184
1185 inline const_arg_iterator arg_begin() const { return getArgs().begin(); }
1186 inline const_arg_iterator arg_end () const { return getArgs().end(); }
1187
1188 inline size_t arg_size () const { return NumArgs; }
1189 inline bool arg_empty() const { return NumArgs == 0; }
1190
1191 inline const_name_iterator name_begin() const { return getArgNames().begin();}
1192 inline const_name_iterator name_end () const { return getArgNames().end(); }
1193
1194 inline size_t name_size () const { return NumArgNames; }
1195 inline bool name_empty() const { return NumArgNames == 0; }
1196
1197 Init *getBit(unsigned Bit) const override {
1198 llvm_unreachable("Illegal bit reference off dag")::llvm::llvm_unreachable_internal("Illegal bit reference off dag"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1198)
;
1199 }
1200
1201 Init *resolveListElementReference(Record &R, const RecordVal *RV,
1202 unsigned Elt) const override {
1203 llvm_unreachable("Illegal element reference off dag")::llvm::llvm_unreachable_internal("Illegal element reference off dag"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1203)
;
1204 }
1205};
1206
1207//===----------------------------------------------------------------------===//
1208// High-Level Classes
1209//===----------------------------------------------------------------------===//
1210
1211class RecordVal {
1212 friend class Record;
1213
1214 Init *Name;
1215 PointerIntPair<RecTy *, 1, bool> TyAndPrefix;
1216 Init *Value;
1217
1218public:
1219 RecordVal(Init *N, RecTy *T, bool P);
1220
1221 StringRef getName() const;
1222 Init *getNameInit() const { return Name; }
1223
1224 std::string getNameInitAsString() const {
1225 return getNameInit()->getAsUnquotedString();
1226 }
1227
1228 bool getPrefix() const { return TyAndPrefix.getInt(); }
1229 RecTy *getType() const { return TyAndPrefix.getPointer(); }
1230 Init *getValue() const { return Value; }
1231
1232 bool setValue(Init *V) {
1233 if (V) {
1234 Value = V->convertInitializerTo(getType());
1235 return Value == nullptr;
1236 }
1237 Value = nullptr;
1238 return false;
1239 }
1240
1241 void dump() const;
1242 void print(raw_ostream &OS, bool PrintSem = true) const;
1243};
1244
1245inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
1246 RV.print(OS << " ");
1247 return OS;
1248}
1249
1250class Record {
1251 static unsigned LastID;
1252
1253 Init *Name;
1254 // Location where record was instantiated, followed by the location of
1255 // multiclass prototypes used.
1256 SmallVector<SMLoc, 4> Locs;
1257 SmallVector<Init *, 0> TemplateArgs;
1258 SmallVector<RecordVal, 0> Values;
1259 SmallVector<std::pair<Record *, SMRange>, 0> SuperClasses;
1260
1261 // Tracks Record instances. Not owned by Record.
1262 RecordKeeper &TrackedRecords;
1263
1264 DefInit *TheInit = nullptr;
1265
1266 // Unique record ID.
1267 unsigned ID;
1268
1269 bool IsAnonymous;
1270
1271 // Class-instance values can be used by other defs. For example, Struct<i>
1272 // is used here as a template argument to another class:
1273 //
1274 // multiclass MultiClass<int i> {
1275 // def Def : Class<Struct<i>>;
1276 //
1277 // These need to get fully resolved before instantiating any other
1278 // definitions that use them (e.g. Def). However, inside a multiclass they
1279 // can't be immediately resolved so we mark them ResolveFirst to fully
1280 // resolve them later as soon as the multiclass is instantiated.
1281 bool ResolveFirst = false;
1282
1283 void init();
1284 void checkName();
1285
1286public:
1287 // Constructs a record.
1288 explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1289 bool Anonymous = false) :
1290 Name(N), Locs(locs.begin(), locs.end()), TrackedRecords(records),
1291 ID(LastID++), IsAnonymous(Anonymous) {
1292 init();
1293 }
1294
1295 explicit Record(StringRef N, ArrayRef<SMLoc> locs, RecordKeeper &records,
1296 bool Anonymous = false)
1297 : Record(StringInit::get(N), locs, records, Anonymous) {}
1298
1299 // When copy-constructing a Record, we must still guarantee a globally unique
1300 // ID number. Don't copy TheInit either since it's owned by the original
1301 // record. All other fields can be copied normally.
1302 Record(const Record &O) :
1303 Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
1304 Values(O.Values), SuperClasses(O.SuperClasses),
1305 TrackedRecords(O.TrackedRecords), ID(LastID++),
1306 IsAnonymous(O.IsAnonymous), ResolveFirst(O.ResolveFirst) { }
1307
1308 static unsigned getNewUID() { return LastID++; }
1309
1310 unsigned getID() const { return ID; }
1311
1312 StringRef getName() const;
1313
1314 Init *getNameInit() const {
1315 return Name;
1316 }
1317
1318 const std::string getNameInitAsString() const {
1319 return getNameInit()->getAsUnquotedString();
1320 }
1321
1322 void setName(Init *Name); // Also updates RecordKeeper.
1323
1324 ArrayRef<SMLoc> getLoc() const { return Locs; }
1325
1326 /// get the corresponding DefInit.
1327 DefInit *getDefInit();
1328
1329 ArrayRef<Init *> getTemplateArgs() const {
1330 return TemplateArgs;
1331 }
1332
1333 ArrayRef<RecordVal> getValues() const { return Values; }
1334
1335 ArrayRef<std::pair<Record *, SMRange>> getSuperClasses() const {
1336 return SuperClasses;
1337 }
1338
1339 bool isTemplateArg(Init *Name) const {
1340 for (Init *TA : TemplateArgs)
1341 if (TA == Name) return true;
1342 return false;
1343 }
1344
1345 const RecordVal *getValue(const Init *Name) const {
1346 for (const RecordVal &Val : Values)
1347 if (Val.Name == Name) return &Val;
1348 return nullptr;
1349 }
1350
1351 const RecordVal *getValue(StringRef Name) const {
1352 return getValue(StringInit::get(Name));
1353 }
1354
1355 RecordVal *getValue(const Init *Name) {
1356 return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1357 }
1358
1359 RecordVal *getValue(StringRef Name) {
1360 return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
1361 }
1362
1363 void addTemplateArg(Init *Name) {
1364 assert(!isTemplateArg(Name) && "Template arg already defined!")(static_cast <bool> (!isTemplateArg(Name) && "Template arg already defined!"
) ? void (0) : __assert_fail ("!isTemplateArg(Name) && \"Template arg already defined!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1364, __extension__ __PRETTY_FUNCTION__))
;
1365 TemplateArgs.push_back(Name);
1366 }
1367
1368 void addValue(const RecordVal &RV) {
1369 assert(getValue(RV.getNameInit()) == nullptr && "Value already added!")(static_cast <bool> (getValue(RV.getNameInit()) == nullptr
&& "Value already added!") ? void (0) : __assert_fail
("getValue(RV.getNameInit()) == nullptr && \"Value already added!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1369, __extension__ __PRETTY_FUNCTION__))
;
1370 Values.push_back(RV);
1371 if (Values.size() > 1)
1372 // Keep NAME at the end of the list. It makes record dumps a
1373 // bit prettier and allows TableGen tests to be written more
1374 // naturally. Tests can use CHECK-NEXT to look for Record
1375 // fields they expect to see after a def. They can't do that if
1376 // NAME is the first Record field.
1377 std::swap(Values[Values.size() - 2], Values[Values.size() - 1]);
1378 }
1379
1380 void removeValue(Init *Name) {
1381 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1382 if (Values[i].getNameInit() == Name) {
1383 Values.erase(Values.begin()+i);
1384 return;
1385 }
1386 llvm_unreachable("Cannot remove an entry that does not exist!")::llvm::llvm_unreachable_internal("Cannot remove an entry that does not exist!"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1386)
;
1387 }
1388
1389 void removeValue(StringRef Name) {
1390 removeValue(StringInit::get(Name));
1391 }
1392
1393 bool isSubClassOf(const Record *R) const {
1394 for (const auto &SCPair : SuperClasses)
1395 if (SCPair.first == R)
1396 return true;
1397 return false;
1398 }
1399
1400 bool isSubClassOf(StringRef Name) const {
1401 for (const auto &SCPair : SuperClasses) {
1402 if (const auto *SI = dyn_cast<StringInit>(SCPair.first->getNameInit())) {
1403 if (SI->getValue() == Name)
1404 return true;
1405 } else if (SCPair.first->getNameInitAsString() == Name) {
1406 return true;
1407 }
1408 }
1409 return false;
1410 }
1411
1412 void addSuperClass(Record *R, SMRange Range) {
1413 assert(!isSubClassOf(R) && "Already subclassing record!")(static_cast <bool> (!isSubClassOf(R) && "Already subclassing record!"
) ? void (0) : __assert_fail ("!isSubClassOf(R) && \"Already subclassing record!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1413, __extension__ __PRETTY_FUNCTION__))
;
1414 SuperClasses.push_back(std::make_pair(R, Range));
1415 }
1416
1417 /// If there are any field references that refer to fields
1418 /// that have been filled in, we can propagate the values now.
1419 void resolveReferences() { resolveReferencesTo(nullptr); }
1420
1421 /// If anything in this record refers to RV, replace the
1422 /// reference to RV with the RHS of RV. If RV is null, we resolve all
1423 /// possible references.
1424 void resolveReferencesTo(const RecordVal *RV);
1425
1426 RecordKeeper &getRecords() const {
1427 return TrackedRecords;
1428 }
1429
1430 bool isAnonymous() const {
1431 return IsAnonymous;
1432 }
1433
1434 bool isResolveFirst() const {
1435 return ResolveFirst;
1436 }
1437
1438 void setResolveFirst(bool b) {
1439 ResolveFirst = b;
1440 }
1441
1442 void print(raw_ostream &OS) const;
1443 void dump() const;
1444
1445 //===--------------------------------------------------------------------===//
1446 // High-level methods useful to tablegen back-ends
1447 //
1448
1449 /// Return the initializer for a value with the specified name,
1450 /// or throw an exception if the field does not exist.
1451 Init *getValueInit(StringRef FieldName) const;
1452
1453 /// Return true if the named field is unset.
1454 bool isValueUnset(StringRef FieldName) const {
1455 return isa<UnsetInit>(getValueInit(FieldName));
1456 }
1457
1458 /// This method looks up the specified field and returns
1459 /// its value as a string, throwing an exception if the field does not exist
1460 /// or if the value is not a string.
1461 StringRef getValueAsString(StringRef FieldName) const;
1462
1463 /// This method looks up the specified field and returns
1464 /// its value as a BitsInit, throwing an exception if the field does not exist
1465 /// or if the value is not the right type.
1466 BitsInit *getValueAsBitsInit(StringRef FieldName) const;
1467
1468 /// This method looks up the specified field and returns
1469 /// its value as a ListInit, throwing an exception if the field does not exist
1470 /// or if the value is not the right type.
1471 ListInit *getValueAsListInit(StringRef FieldName) const;
1472
1473 /// This method looks up the specified field and
1474 /// returns its value as a vector of records, throwing an exception if the
1475 /// field does not exist or if the value is not the right type.
1476 std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
1477
1478 /// This method looks up the specified field and
1479 /// returns its value as a vector of integers, throwing an exception if the
1480 /// field does not exist or if the value is not the right type.
1481 std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
1482
1483 /// This method looks up the specified field and
1484 /// returns its value as a vector of strings, throwing an exception if the
1485 /// field does not exist or if the value is not the right type.
1486 std::vector<StringRef> getValueAsListOfStrings(StringRef FieldName) const;
1487
1488 /// This method looks up the specified field and returns its
1489 /// value as a Record, throwing an exception if the field does not exist or if
1490 /// the value is not the right type.
1491 Record *getValueAsDef(StringRef FieldName) const;
1492
1493 /// This method looks up the specified field and returns its
1494 /// value as a bit, throwing an exception if the field does not exist or if
1495 /// the value is not the right type.
1496 bool getValueAsBit(StringRef FieldName) const;
1497
1498 /// This method looks up the specified field and
1499 /// returns its value as a bit. If the field is unset, sets Unset to true and
1500 /// returns false.
1501 bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
1502
1503 /// This method looks up the specified field and returns its
1504 /// value as an int64_t, throwing an exception if the field does not exist or
1505 /// if the value is not the right type.
1506 int64_t getValueAsInt(StringRef FieldName) const;
1507
1508 /// This method looks up the specified field and returns its
1509 /// value as an Dag, throwing an exception if the field does not exist or if
1510 /// the value is not the right type.
1511 DagInit *getValueAsDag(StringRef FieldName) const;
1512};
1513
1514raw_ostream &operator<<(raw_ostream &OS, const Record &R);
1515
1516struct MultiClass {
1517 Record Rec; // Placeholder for template args and Name.
1518 using RecordVector = std::vector<std::unique_ptr<Record>>;
1519 RecordVector DefPrototypes;
1520
1521 void dump() const;
1522
1523 MultiClass(StringRef Name, SMLoc Loc, RecordKeeper &Records) :
1524 Rec(Name, Loc, Records) {}
1525};
1526
1527class RecordKeeper {
1528 using RecordMap = std::map<StringRef, std::unique_ptr<Record>>;
1529 RecordMap Classes, Defs;
1530
1531public:
1532 const RecordMap &getClasses() const { return Classes; }
1533 const RecordMap &getDefs() const { return Defs; }
1534
1535 Record *getClass(StringRef Name) const {
1536 auto I = Classes.find(Name);
1537 return I == Classes.end() ? nullptr : I->second.get();
1538 }
1539
1540 Record *getDef(StringRef Name) const {
1541 auto I = Defs.find(Name);
1542 return I == Defs.end() ? nullptr : I->second.get();
1543 }
1544
1545 void addClass(std::unique_ptr<Record> R) {
1546 bool Ins = Classes.insert(std::make_pair(R->getName(),
1547 std::move(R))).second;
1548 (void)Ins;
1549 assert(Ins && "Class already exists")(static_cast <bool> (Ins && "Class already exists"
) ? void (0) : __assert_fail ("Ins && \"Class already exists\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1549, __extension__ __PRETTY_FUNCTION__))
;
1550 }
1551
1552 void addDef(std::unique_ptr<Record> R) {
1553 bool Ins = Defs.insert(std::make_pair(R->getName(),
1554 std::move(R))).second;
1555 (void)Ins;
1556 assert(Ins && "Record already exists")(static_cast <bool> (Ins && "Record already exists"
) ? void (0) : __assert_fail ("Ins && \"Record already exists\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1556, __extension__ __PRETTY_FUNCTION__))
;
1557 }
1558
1559 //===--------------------------------------------------------------------===//
1560 // High-level helper methods, useful for tablegen backends...
1561
1562 /// This method returns all concrete definitions
1563 /// that derive from the specified class name. A class with the specified
1564 /// name must exist.
1565 std::vector<Record *> getAllDerivedDefinitions(StringRef ClassName) const;
1566
1567 void dump() const;
1568};
1569
1570/// Sorting predicate to sort record pointers by name.
1571struct LessRecord {
1572 bool operator()(const Record *Rec1, const Record *Rec2) const {
1573 return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0;
1574 }
1575};
1576
1577/// Sorting predicate to sort record pointers by their
1578/// unique ID. If you just need a deterministic order, use this, since it
1579/// just compares two `unsigned`; the other sorting predicates require
1580/// string manipulation.
1581struct LessRecordByID {
1582 bool operator()(const Record *LHS, const Record *RHS) const {
1583 return LHS->getID() < RHS->getID();
1584 }
1585};
1586
1587/// Sorting predicate to sort record pointers by their
1588/// name field.
1589struct LessRecordFieldName {
1590 bool operator()(const Record *Rec1, const Record *Rec2) const {
1591 return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
1592 }
1593};
1594
1595struct LessRecordRegister {
1596 static bool ascii_isdigit(char x) { return x >= '0' && x <= '9'; }
1597
1598 struct RecordParts {
1599 SmallVector<std::pair< bool, StringRef>, 4> Parts;
1600
1601 RecordParts(StringRef Rec) {
1602 if (Rec.empty())
1603 return;
1604
1605 size_t Len = 0;
1606 const char *Start = Rec.data();
1607 const char *Curr = Start;
1608 bool isDigitPart = ascii_isdigit(Curr[0]);
1609 for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
1610 bool isDigit = ascii_isdigit(Curr[I]);
1611 if (isDigit != isDigitPart) {
1612 Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1613 Len = 0;
1614 Start = &Curr[I];
1615 isDigitPart = ascii_isdigit(Curr[I]);
1616 }
1617 }
1618 // Push the last part.
1619 Parts.push_back(std::make_pair(isDigitPart, StringRef(Start, Len)));
1620 }
1621
1622 size_t size() { return Parts.size(); }
1623
1624 std::pair<bool, StringRef> getPart(size_t i) {
1625 assert (i < Parts.size() && "Invalid idx!")(static_cast <bool> (i < Parts.size() && "Invalid idx!"
) ? void (0) : __assert_fail ("i < Parts.size() && \"Invalid idx!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1625, __extension__ __PRETTY_FUNCTION__))
;
1626 return Parts[i];
1627 }
1628 };
1629
1630 bool operator()(const Record *Rec1, const Record *Rec2) const {
1631 RecordParts LHSParts(StringRef(Rec1->getName()));
1632 RecordParts RHSParts(StringRef(Rec2->getName()));
1633
1634 size_t LHSNumParts = LHSParts.size();
1635 size_t RHSNumParts = RHSParts.size();
1636 assert (LHSNumParts && RHSNumParts && "Expected at least one part!")(static_cast <bool> (LHSNumParts && RHSNumParts
&& "Expected at least one part!") ? void (0) : __assert_fail
("LHSNumParts && RHSNumParts && \"Expected at least one part!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1636, __extension__ __PRETTY_FUNCTION__))
;
1637
1638 if (LHSNumParts != RHSNumParts)
1639 return LHSNumParts < RHSNumParts;
1640
1641 // We expect the registers to be of the form [_a-zA-Z]+([0-9]*[_a-zA-Z]*)*.
1642 for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
1643 std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1644 std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1645 // Expect even part to always be alpha.
1646 assert (LHSPart.first == false && RHSPart.first == false &&(static_cast <bool> (LHSPart.first == false && RHSPart
.first == false && "Expected both parts to be alpha."
) ? void (0) : __assert_fail ("LHSPart.first == false && RHSPart.first == false && \"Expected both parts to be alpha.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1647, __extension__ __PRETTY_FUNCTION__))
1647 "Expected both parts to be alpha.")(static_cast <bool> (LHSPart.first == false && RHSPart
.first == false && "Expected both parts to be alpha."
) ? void (0) : __assert_fail ("LHSPart.first == false && RHSPart.first == false && \"Expected both parts to be alpha.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1647, __extension__ __PRETTY_FUNCTION__))
;
1648 if (int Res = LHSPart.second.compare(RHSPart.second))
1649 return Res < 0;
1650 }
1651 for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
1652 std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
1653 std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
1654 // Expect odd part to always be numeric.
1655 assert (LHSPart.first == true && RHSPart.first == true &&(static_cast <bool> (LHSPart.first == true && RHSPart
.first == true && "Expected both parts to be numeric."
) ? void (0) : __assert_fail ("LHSPart.first == true && RHSPart.first == true && \"Expected both parts to be numeric.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1656, __extension__ __PRETTY_FUNCTION__))
1656 "Expected both parts to be numeric.")(static_cast <bool> (LHSPart.first == true && RHSPart
.first == true && "Expected both parts to be numeric."
) ? void (0) : __assert_fail ("LHSPart.first == true && RHSPart.first == true && \"Expected both parts to be numeric.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1656, __extension__ __PRETTY_FUNCTION__))
;
1657 if (LHSPart.second.size() != RHSPart.second.size())
1658 return LHSPart.second.size() < RHSPart.second.size();
1659
1660 unsigned LHSVal, RHSVal;
1661
1662 bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
1663 assert(!LHSFailed && "Unable to convert LHS to integer.")(static_cast <bool> (!LHSFailed && "Unable to convert LHS to integer."
) ? void (0) : __assert_fail ("!LHSFailed && \"Unable to convert LHS to integer.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1663, __extension__ __PRETTY_FUNCTION__))
;
1664 bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
1665 assert(!RHSFailed && "Unable to convert RHS to integer.")(static_cast <bool> (!RHSFailed && "Unable to convert RHS to integer."
) ? void (0) : __assert_fail ("!RHSFailed && \"Unable to convert RHS to integer.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/TableGen/Record.h"
, 1665, __extension__ __PRETTY_FUNCTION__))
;
1666
1667 if (LHSVal != RHSVal)
1668 return LHSVal < RHSVal;
1669 }
1670 return LHSNumParts < RHSNumParts;
1671 }
1672};
1673
1674raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
1675
1676/// Return an Init with a qualifier prefix referring
1677/// to CurRec's name.
1678Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1679 Init *Name, StringRef Scoper);
1680
1681} // end namespace llvm
1682
1683#endif // LLVM_TABLEGEN_RECORD_H