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