xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizerInfo.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
10b57cec5SDimitry Andric //===- lib/CodeGen/GlobalISel/LegalizerInfo.cpp - Legalizer ---------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // Implement an interface to specify and query how an illegal operation on a
100b57cec5SDimitry Andric // given type should be expanded.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // Issues to be resolved:
130b57cec5SDimitry Andric //   + Make it fast.
140b57cec5SDimitry Andric //   + Support weird types like i3, <7 x i3>, ...
150b57cec5SDimitry Andric //   + Operations with more than one type (ICMP, CMPXCHG, intrinsics, ...)
160b57cec5SDimitry Andric //
170b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
180b57cec5SDimitry Andric 
190b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallBitVector.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
260b57cec5SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
270b57cec5SDimitry Andric #include "llvm/MC/MCInstrInfo.h"
280b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
290b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
300b57cec5SDimitry Andric #include "llvm/Support/LowLevelTypeImpl.h"
310b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
320b57cec5SDimitry Andric #include <algorithm>
330b57cec5SDimitry Andric #include <map>
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric using namespace llvm;
360b57cec5SDimitry Andric using namespace LegalizeActions;
370b57cec5SDimitry Andric 
380b57cec5SDimitry Andric #define DEBUG_TYPE "legalizer-info"
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric cl::opt<bool> llvm::DisableGISelLegalityCheck(
410b57cec5SDimitry Andric     "disable-gisel-legality-check",
420b57cec5SDimitry Andric     cl::desc("Don't verify that MIR is fully legal between GlobalISel passes"),
430b57cec5SDimitry Andric     cl::Hidden);
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric raw_ostream &llvm::operator<<(raw_ostream &OS, LegalizeAction Action) {
460b57cec5SDimitry Andric   switch (Action) {
470b57cec5SDimitry Andric   case Legal:
480b57cec5SDimitry Andric     OS << "Legal";
490b57cec5SDimitry Andric     break;
500b57cec5SDimitry Andric   case NarrowScalar:
510b57cec5SDimitry Andric     OS << "NarrowScalar";
520b57cec5SDimitry Andric     break;
530b57cec5SDimitry Andric   case WidenScalar:
540b57cec5SDimitry Andric     OS << "WidenScalar";
550b57cec5SDimitry Andric     break;
560b57cec5SDimitry Andric   case FewerElements:
570b57cec5SDimitry Andric     OS << "FewerElements";
580b57cec5SDimitry Andric     break;
590b57cec5SDimitry Andric   case MoreElements:
600b57cec5SDimitry Andric     OS << "MoreElements";
610b57cec5SDimitry Andric     break;
625ffd83dbSDimitry Andric   case Bitcast:
635ffd83dbSDimitry Andric     OS << "Bitcast";
645ffd83dbSDimitry Andric     break;
650b57cec5SDimitry Andric   case Lower:
660b57cec5SDimitry Andric     OS << "Lower";
670b57cec5SDimitry Andric     break;
680b57cec5SDimitry Andric   case Libcall:
690b57cec5SDimitry Andric     OS << "Libcall";
700b57cec5SDimitry Andric     break;
710b57cec5SDimitry Andric   case Custom:
720b57cec5SDimitry Andric     OS << "Custom";
730b57cec5SDimitry Andric     break;
740b57cec5SDimitry Andric   case Unsupported:
750b57cec5SDimitry Andric     OS << "Unsupported";
760b57cec5SDimitry Andric     break;
770b57cec5SDimitry Andric   case NotFound:
780b57cec5SDimitry Andric     OS << "NotFound";
790b57cec5SDimitry Andric     break;
800b57cec5SDimitry Andric   case UseLegacyRules:
810b57cec5SDimitry Andric     OS << "UseLegacyRules";
820b57cec5SDimitry Andric     break;
830b57cec5SDimitry Andric   }
840b57cec5SDimitry Andric   return OS;
850b57cec5SDimitry Andric }
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric raw_ostream &LegalityQuery::print(raw_ostream &OS) const {
880b57cec5SDimitry Andric   OS << Opcode << ", Tys={";
890b57cec5SDimitry Andric   for (const auto &Type : Types) {
900b57cec5SDimitry Andric     OS << Type << ", ";
910b57cec5SDimitry Andric   }
920b57cec5SDimitry Andric   OS << "}, Opcode=";
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric   OS << Opcode << ", MMOs={";
950b57cec5SDimitry Andric   for (const auto &MMODescr : MMODescrs) {
960b57cec5SDimitry Andric     OS << MMODescr.SizeInBits << ", ";
970b57cec5SDimitry Andric   }
980b57cec5SDimitry Andric   OS << "}";
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric   return OS;
1010b57cec5SDimitry Andric }
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric #ifndef NDEBUG
1040b57cec5SDimitry Andric // Make sure the rule won't (trivially) loop forever.
1050b57cec5SDimitry Andric static bool hasNoSimpleLoops(const LegalizeRule &Rule, const LegalityQuery &Q,
1060b57cec5SDimitry Andric                              const std::pair<unsigned, LLT> &Mutation) {
1070b57cec5SDimitry Andric   switch (Rule.getAction()) {
108*e8d8bef9SDimitry Andric   case Legal:
1090b57cec5SDimitry Andric   case Custom:
1100b57cec5SDimitry Andric   case Lower:
1110b57cec5SDimitry Andric   case MoreElements:
1120b57cec5SDimitry Andric   case FewerElements:
1130b57cec5SDimitry Andric     break;
1140b57cec5SDimitry Andric   default:
1150b57cec5SDimitry Andric     return Q.Types[Mutation.first] != Mutation.second;
1160b57cec5SDimitry Andric   }
1170b57cec5SDimitry Andric   return true;
1180b57cec5SDimitry Andric }
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric // Make sure the returned mutation makes sense for the match type.
1210b57cec5SDimitry Andric static bool mutationIsSane(const LegalizeRule &Rule,
1220b57cec5SDimitry Andric                            const LegalityQuery &Q,
1230b57cec5SDimitry Andric                            std::pair<unsigned, LLT> Mutation) {
1240b57cec5SDimitry Andric   // If the user wants a custom mutation, then we can't really say much about
1250b57cec5SDimitry Andric   // it. Return true, and trust that they're doing the right thing.
126*e8d8bef9SDimitry Andric   if (Rule.getAction() == Custom || Rule.getAction() == Legal)
1270b57cec5SDimitry Andric     return true;
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric   const unsigned TypeIdx = Mutation.first;
1300b57cec5SDimitry Andric   const LLT OldTy = Q.Types[TypeIdx];
1310b57cec5SDimitry Andric   const LLT NewTy = Mutation.second;
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   switch (Rule.getAction()) {
1340b57cec5SDimitry Andric   case FewerElements:
1350b57cec5SDimitry Andric     if (!OldTy.isVector())
1360b57cec5SDimitry Andric       return false;
137480093f4SDimitry Andric     LLVM_FALLTHROUGH;
138480093f4SDimitry Andric   case MoreElements: {
139480093f4SDimitry Andric     // MoreElements can go from scalar to vector.
140480093f4SDimitry Andric     const unsigned OldElts = OldTy.isVector() ? OldTy.getNumElements() : 1;
1410b57cec5SDimitry Andric     if (NewTy.isVector()) {
1420b57cec5SDimitry Andric       if (Rule.getAction() == FewerElements) {
1430b57cec5SDimitry Andric         // Make sure the element count really decreased.
144480093f4SDimitry Andric         if (NewTy.getNumElements() >= OldElts)
1450b57cec5SDimitry Andric           return false;
1460b57cec5SDimitry Andric       } else {
1470b57cec5SDimitry Andric         // Make sure the element count really increased.
148480093f4SDimitry Andric         if (NewTy.getNumElements() <= OldElts)
1490b57cec5SDimitry Andric           return false;
1500b57cec5SDimitry Andric       }
151*e8d8bef9SDimitry Andric     } else if (Rule.getAction() == MoreElements)
152*e8d8bef9SDimitry Andric       return false;
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric     // Make sure the element type didn't change.
155480093f4SDimitry Andric     return NewTy.getScalarType() == OldTy.getScalarType();
1560b57cec5SDimitry Andric   }
1570b57cec5SDimitry Andric   case NarrowScalar:
1580b57cec5SDimitry Andric   case WidenScalar: {
1590b57cec5SDimitry Andric     if (OldTy.isVector()) {
1600b57cec5SDimitry Andric       // Number of elements should not change.
1610b57cec5SDimitry Andric       if (!NewTy.isVector() || OldTy.getNumElements() != NewTy.getNumElements())
1620b57cec5SDimitry Andric         return false;
1630b57cec5SDimitry Andric     } else {
1640b57cec5SDimitry Andric       // Both types must be vectors
1650b57cec5SDimitry Andric       if (NewTy.isVector())
1660b57cec5SDimitry Andric         return false;
1670b57cec5SDimitry Andric     }
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric     if (Rule.getAction() == NarrowScalar)  {
1700b57cec5SDimitry Andric       // Make sure the size really decreased.
1710b57cec5SDimitry Andric       if (NewTy.getScalarSizeInBits() >= OldTy.getScalarSizeInBits())
1720b57cec5SDimitry Andric         return false;
1730b57cec5SDimitry Andric     } else {
1740b57cec5SDimitry Andric       // Make sure the size really increased.
1750b57cec5SDimitry Andric       if (NewTy.getScalarSizeInBits() <= OldTy.getScalarSizeInBits())
1760b57cec5SDimitry Andric         return false;
1770b57cec5SDimitry Andric     }
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric     return true;
1800b57cec5SDimitry Andric   }
1815ffd83dbSDimitry Andric   case Bitcast: {
1825ffd83dbSDimitry Andric     return OldTy != NewTy && OldTy.getSizeInBits() == NewTy.getSizeInBits();
1835ffd83dbSDimitry Andric   }
1840b57cec5SDimitry Andric   default:
1850b57cec5SDimitry Andric     return true;
1860b57cec5SDimitry Andric   }
1870b57cec5SDimitry Andric }
1880b57cec5SDimitry Andric #endif
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric LegalizeActionStep LegalizeRuleSet::apply(const LegalityQuery &Query) const {
1910b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Applying legalizer ruleset to: "; Query.print(dbgs());
1920b57cec5SDimitry Andric              dbgs() << "\n");
1930b57cec5SDimitry Andric   if (Rules.empty()) {
1940b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. fallback to legacy rules (no rules defined)\n");
1950b57cec5SDimitry Andric     return {LegalizeAction::UseLegacyRules, 0, LLT{}};
1960b57cec5SDimitry Andric   }
1970b57cec5SDimitry Andric   for (const LegalizeRule &Rule : Rules) {
1980b57cec5SDimitry Andric     if (Rule.match(Query)) {
1990b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << ".. match\n");
2000b57cec5SDimitry Andric       std::pair<unsigned, LLT> Mutation = Rule.determineMutation(Query);
2010b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << ".. .. " << Rule.getAction() << ", "
2020b57cec5SDimitry Andric                         << Mutation.first << ", " << Mutation.second << "\n");
2030b57cec5SDimitry Andric       assert(mutationIsSane(Rule, Query, Mutation) &&
2040b57cec5SDimitry Andric              "legality mutation invalid for match");
2050b57cec5SDimitry Andric       assert(hasNoSimpleLoops(Rule, Query, Mutation) && "Simple loop detected");
2060b57cec5SDimitry Andric       return {Rule.getAction(), Mutation.first, Mutation.second};
2070b57cec5SDimitry Andric     } else
2080b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << ".. no match\n");
2090b57cec5SDimitry Andric   }
2100b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << ".. unsupported\n");
2110b57cec5SDimitry Andric   return {LegalizeAction::Unsupported, 0, LLT{}};
2120b57cec5SDimitry Andric }
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric bool LegalizeRuleSet::verifyTypeIdxsCoverage(unsigned NumTypeIdxs) const {
2150b57cec5SDimitry Andric #ifndef NDEBUG
2160b57cec5SDimitry Andric   if (Rules.empty()) {
2170b57cec5SDimitry Andric     LLVM_DEBUG(
2180b57cec5SDimitry Andric         dbgs() << ".. type index coverage check SKIPPED: no rules defined\n");
2190b57cec5SDimitry Andric     return true;
2200b57cec5SDimitry Andric   }
2210b57cec5SDimitry Andric   const int64_t FirstUncovered = TypeIdxsCovered.find_first_unset();
2220b57cec5SDimitry Andric   if (FirstUncovered < 0) {
2230b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. type index coverage check SKIPPED:"
2240b57cec5SDimitry Andric                          " user-defined predicate detected\n");
2250b57cec5SDimitry Andric     return true;
2260b57cec5SDimitry Andric   }
2270b57cec5SDimitry Andric   const bool AllCovered = (FirstUncovered >= NumTypeIdxs);
2288bcb0991SDimitry Andric   if (NumTypeIdxs > 0)
2290b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. the first uncovered type index: " << FirstUncovered
2300b57cec5SDimitry Andric                       << ", " << (AllCovered ? "OK" : "FAIL") << "\n");
2310b57cec5SDimitry Andric   return AllCovered;
2320b57cec5SDimitry Andric #else
2330b57cec5SDimitry Andric   return true;
2340b57cec5SDimitry Andric #endif
2350b57cec5SDimitry Andric }
2360b57cec5SDimitry Andric 
2378bcb0991SDimitry Andric bool LegalizeRuleSet::verifyImmIdxsCoverage(unsigned NumImmIdxs) const {
2388bcb0991SDimitry Andric #ifndef NDEBUG
2398bcb0991SDimitry Andric   if (Rules.empty()) {
2408bcb0991SDimitry Andric     LLVM_DEBUG(
2418bcb0991SDimitry Andric         dbgs() << ".. imm index coverage check SKIPPED: no rules defined\n");
2428bcb0991SDimitry Andric     return true;
2438bcb0991SDimitry Andric   }
2448bcb0991SDimitry Andric   const int64_t FirstUncovered = ImmIdxsCovered.find_first_unset();
2458bcb0991SDimitry Andric   if (FirstUncovered < 0) {
2468bcb0991SDimitry Andric     LLVM_DEBUG(dbgs() << ".. imm index coverage check SKIPPED:"
2478bcb0991SDimitry Andric                          " user-defined predicate detected\n");
2488bcb0991SDimitry Andric     return true;
2498bcb0991SDimitry Andric   }
2508bcb0991SDimitry Andric   const bool AllCovered = (FirstUncovered >= NumImmIdxs);
2518bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << ".. the first uncovered imm index: " << FirstUncovered
2528bcb0991SDimitry Andric                     << ", " << (AllCovered ? "OK" : "FAIL") << "\n");
2538bcb0991SDimitry Andric   return AllCovered;
2548bcb0991SDimitry Andric #else
2558bcb0991SDimitry Andric   return true;
2568bcb0991SDimitry Andric #endif
2578bcb0991SDimitry Andric }
2588bcb0991SDimitry Andric 
2590b57cec5SDimitry Andric LegalizerInfo::LegalizerInfo() : TablesInitialized(false) {
2600b57cec5SDimitry Andric   // Set defaults.
2610b57cec5SDimitry Andric   // FIXME: these two (G_ANYEXT and G_TRUNC?) can be legalized to the
2620b57cec5SDimitry Andric   // fundamental load/store Jakob proposed. Once loads & stores are supported.
2630b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_ANYEXT, 1, {{1, Legal}});
2640b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_ZEXT, 1, {{1, Legal}});
2650b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_SEXT, 1, {{1, Legal}});
2660b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_TRUNC, 0, {{1, Legal}});
2670b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_TRUNC, 1, {{1, Legal}});
2680b57cec5SDimitry Andric 
2690b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_INTRINSIC, 0, {{1, Legal}});
2700b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS, 0, {{1, Legal}});
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2730b57cec5SDimitry Andric       TargetOpcode::G_IMPLICIT_DEF, 0, narrowToSmallerAndUnsupportedIfTooSmall);
2740b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2750b57cec5SDimitry Andric       TargetOpcode::G_ADD, 0, widenToLargerTypesAndNarrowToLargest);
2760b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2770b57cec5SDimitry Andric       TargetOpcode::G_OR, 0, widenToLargerTypesAndNarrowToLargest);
2780b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2790b57cec5SDimitry Andric       TargetOpcode::G_LOAD, 0, narrowToSmallerAndUnsupportedIfTooSmall);
2800b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2810b57cec5SDimitry Andric       TargetOpcode::G_STORE, 0, narrowToSmallerAndUnsupportedIfTooSmall);
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2840b57cec5SDimitry Andric       TargetOpcode::G_BRCOND, 0, widenToLargerTypesUnsupportedOtherwise);
2850b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2860b57cec5SDimitry Andric       TargetOpcode::G_INSERT, 0, narrowToSmallerAndUnsupportedIfTooSmall);
2870b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2880b57cec5SDimitry Andric       TargetOpcode::G_EXTRACT, 0, narrowToSmallerAndUnsupportedIfTooSmall);
2890b57cec5SDimitry Andric   setLegalizeScalarToDifferentSizeStrategy(
2900b57cec5SDimitry Andric       TargetOpcode::G_EXTRACT, 1, narrowToSmallerAndUnsupportedIfTooSmall);
2910b57cec5SDimitry Andric   setScalarAction(TargetOpcode::G_FNEG, 0, {{1, Lower}});
2920b57cec5SDimitry Andric }
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric void LegalizerInfo::computeTables() {
2950b57cec5SDimitry Andric   assert(TablesInitialized == false);
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric   for (unsigned OpcodeIdx = 0; OpcodeIdx <= LastOp - FirstOp; ++OpcodeIdx) {
2980b57cec5SDimitry Andric     const unsigned Opcode = FirstOp + OpcodeIdx;
2990b57cec5SDimitry Andric     for (unsigned TypeIdx = 0; TypeIdx != SpecifiedActions[OpcodeIdx].size();
3000b57cec5SDimitry Andric          ++TypeIdx) {
3010b57cec5SDimitry Andric       // 0. Collect information specified through the setAction API, i.e.
3020b57cec5SDimitry Andric       // for specific bit sizes.
3030b57cec5SDimitry Andric       // For scalar types:
3040b57cec5SDimitry Andric       SizeAndActionsVec ScalarSpecifiedActions;
3050b57cec5SDimitry Andric       // For pointer types:
3060b57cec5SDimitry Andric       std::map<uint16_t, SizeAndActionsVec> AddressSpace2SpecifiedActions;
3070b57cec5SDimitry Andric       // For vector types:
3080b57cec5SDimitry Andric       std::map<uint16_t, SizeAndActionsVec> ElemSize2SpecifiedActions;
3090b57cec5SDimitry Andric       for (auto LLT2Action : SpecifiedActions[OpcodeIdx][TypeIdx]) {
3100b57cec5SDimitry Andric         const LLT Type = LLT2Action.first;
3110b57cec5SDimitry Andric         const LegalizeAction Action = LLT2Action.second;
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric         auto SizeAction = std::make_pair(Type.getSizeInBits(), Action);
3140b57cec5SDimitry Andric         if (Type.isPointer())
3150b57cec5SDimitry Andric           AddressSpace2SpecifiedActions[Type.getAddressSpace()].push_back(
3160b57cec5SDimitry Andric               SizeAction);
3170b57cec5SDimitry Andric         else if (Type.isVector())
3180b57cec5SDimitry Andric           ElemSize2SpecifiedActions[Type.getElementType().getSizeInBits()]
3190b57cec5SDimitry Andric               .push_back(SizeAction);
3200b57cec5SDimitry Andric         else
3210b57cec5SDimitry Andric           ScalarSpecifiedActions.push_back(SizeAction);
3220b57cec5SDimitry Andric       }
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric       // 1. Handle scalar types
3250b57cec5SDimitry Andric       {
3260b57cec5SDimitry Andric         // Decide how to handle bit sizes for which no explicit specification
3270b57cec5SDimitry Andric         // was given.
3280b57cec5SDimitry Andric         SizeChangeStrategy S = &unsupportedForDifferentSizes;
3290b57cec5SDimitry Andric         if (TypeIdx < ScalarSizeChangeStrategies[OpcodeIdx].size() &&
3300b57cec5SDimitry Andric             ScalarSizeChangeStrategies[OpcodeIdx][TypeIdx] != nullptr)
3310b57cec5SDimitry Andric           S = ScalarSizeChangeStrategies[OpcodeIdx][TypeIdx];
3320b57cec5SDimitry Andric         llvm::sort(ScalarSpecifiedActions);
3330b57cec5SDimitry Andric         checkPartialSizeAndActionsVector(ScalarSpecifiedActions);
3340b57cec5SDimitry Andric         setScalarAction(Opcode, TypeIdx, S(ScalarSpecifiedActions));
3350b57cec5SDimitry Andric       }
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric       // 2. Handle pointer types
3380b57cec5SDimitry Andric       for (auto PointerSpecifiedActions : AddressSpace2SpecifiedActions) {
3390b57cec5SDimitry Andric         llvm::sort(PointerSpecifiedActions.second);
3400b57cec5SDimitry Andric         checkPartialSizeAndActionsVector(PointerSpecifiedActions.second);
3410b57cec5SDimitry Andric         // For pointer types, we assume that there isn't a meaningfull way
3420b57cec5SDimitry Andric         // to change the number of bits used in the pointer.
3430b57cec5SDimitry Andric         setPointerAction(
3440b57cec5SDimitry Andric             Opcode, TypeIdx, PointerSpecifiedActions.first,
3450b57cec5SDimitry Andric             unsupportedForDifferentSizes(PointerSpecifiedActions.second));
3460b57cec5SDimitry Andric       }
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric       // 3. Handle vector types
3490b57cec5SDimitry Andric       SizeAndActionsVec ElementSizesSeen;
3500b57cec5SDimitry Andric       for (auto VectorSpecifiedActions : ElemSize2SpecifiedActions) {
3510b57cec5SDimitry Andric         llvm::sort(VectorSpecifiedActions.second);
3520b57cec5SDimitry Andric         const uint16_t ElementSize = VectorSpecifiedActions.first;
3530b57cec5SDimitry Andric         ElementSizesSeen.push_back({ElementSize, Legal});
3540b57cec5SDimitry Andric         checkPartialSizeAndActionsVector(VectorSpecifiedActions.second);
3550b57cec5SDimitry Andric         // For vector types, we assume that the best way to adapt the number
3560b57cec5SDimitry Andric         // of elements is to the next larger number of elements type for which
3570b57cec5SDimitry Andric         // the vector type is legal, unless there is no such type. In that case,
3580b57cec5SDimitry Andric         // legalize towards a vector type with a smaller number of elements.
3590b57cec5SDimitry Andric         SizeAndActionsVec NumElementsActions;
3600b57cec5SDimitry Andric         for (SizeAndAction BitsizeAndAction : VectorSpecifiedActions.second) {
3610b57cec5SDimitry Andric           assert(BitsizeAndAction.first % ElementSize == 0);
3620b57cec5SDimitry Andric           const uint16_t NumElements = BitsizeAndAction.first / ElementSize;
3630b57cec5SDimitry Andric           NumElementsActions.push_back({NumElements, BitsizeAndAction.second});
3640b57cec5SDimitry Andric         }
3650b57cec5SDimitry Andric         setVectorNumElementAction(
3660b57cec5SDimitry Andric             Opcode, TypeIdx, ElementSize,
3670b57cec5SDimitry Andric             moreToWiderTypesAndLessToWidest(NumElementsActions));
3680b57cec5SDimitry Andric       }
3690b57cec5SDimitry Andric       llvm::sort(ElementSizesSeen);
3700b57cec5SDimitry Andric       SizeChangeStrategy VectorElementSizeChangeStrategy =
3710b57cec5SDimitry Andric           &unsupportedForDifferentSizes;
3720b57cec5SDimitry Andric       if (TypeIdx < VectorElementSizeChangeStrategies[OpcodeIdx].size() &&
3730b57cec5SDimitry Andric           VectorElementSizeChangeStrategies[OpcodeIdx][TypeIdx] != nullptr)
3740b57cec5SDimitry Andric         VectorElementSizeChangeStrategy =
3750b57cec5SDimitry Andric             VectorElementSizeChangeStrategies[OpcodeIdx][TypeIdx];
3760b57cec5SDimitry Andric       setScalarInVectorAction(
3770b57cec5SDimitry Andric           Opcode, TypeIdx, VectorElementSizeChangeStrategy(ElementSizesSeen));
3780b57cec5SDimitry Andric     }
3790b57cec5SDimitry Andric   }
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric   TablesInitialized = true;
3820b57cec5SDimitry Andric }
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric // FIXME: inefficient implementation for now. Without ComputeValueVTs we're
3850b57cec5SDimitry Andric // probably going to need specialized lookup structures for various types before
3860b57cec5SDimitry Andric // we have any hope of doing well with something like <13 x i3>. Even the common
3870b57cec5SDimitry Andric // cases should do better than what we have now.
3880b57cec5SDimitry Andric std::pair<LegalizeAction, LLT>
3890b57cec5SDimitry Andric LegalizerInfo::getAspectAction(const InstrAspect &Aspect) const {
3900b57cec5SDimitry Andric   assert(TablesInitialized && "backend forgot to call computeTables");
3910b57cec5SDimitry Andric   // These *have* to be implemented for now, they're the fundamental basis of
3920b57cec5SDimitry Andric   // how everything else is transformed.
3930b57cec5SDimitry Andric   if (Aspect.Type.isScalar() || Aspect.Type.isPointer())
3940b57cec5SDimitry Andric     return findScalarLegalAction(Aspect);
3950b57cec5SDimitry Andric   assert(Aspect.Type.isVector());
3960b57cec5SDimitry Andric   return findVectorLegalAction(Aspect);
3970b57cec5SDimitry Andric }
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric /// Helper function to get LLT for the given type index.
4000b57cec5SDimitry Andric static LLT getTypeFromTypeIdx(const MachineInstr &MI,
4010b57cec5SDimitry Andric                               const MachineRegisterInfo &MRI, unsigned OpIdx,
4020b57cec5SDimitry Andric                               unsigned TypeIdx) {
4030b57cec5SDimitry Andric   assert(TypeIdx < MI.getNumOperands() && "Unexpected TypeIdx");
4040b57cec5SDimitry Andric   // G_UNMERGE_VALUES has variable number of operands, but there is only
4050b57cec5SDimitry Andric   // one source type and one destination type as all destinations must be the
4060b57cec5SDimitry Andric   // same type. So, get the last operand if TypeIdx == 1.
4070b57cec5SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && TypeIdx == 1)
4080b57cec5SDimitry Andric     return MRI.getType(MI.getOperand(MI.getNumOperands() - 1).getReg());
4090b57cec5SDimitry Andric   return MRI.getType(MI.getOperand(OpIdx).getReg());
4100b57cec5SDimitry Andric }
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric unsigned LegalizerInfo::getOpcodeIdxForOpcode(unsigned Opcode) const {
4130b57cec5SDimitry Andric   assert(Opcode >= FirstOp && Opcode <= LastOp && "Unsupported opcode");
4140b57cec5SDimitry Andric   return Opcode - FirstOp;
4150b57cec5SDimitry Andric }
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric unsigned LegalizerInfo::getActionDefinitionsIdx(unsigned Opcode) const {
4180b57cec5SDimitry Andric   unsigned OpcodeIdx = getOpcodeIdxForOpcode(Opcode);
4190b57cec5SDimitry Andric   if (unsigned Alias = RulesForOpcode[OpcodeIdx].getAlias()) {
4200b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ".. opcode " << Opcode << " is aliased to " << Alias
4210b57cec5SDimitry Andric                       << "\n");
4220b57cec5SDimitry Andric     OpcodeIdx = getOpcodeIdxForOpcode(Alias);
4230b57cec5SDimitry Andric     assert(RulesForOpcode[OpcodeIdx].getAlias() == 0 && "Cannot chain aliases");
4240b57cec5SDimitry Andric   }
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   return OpcodeIdx;
4270b57cec5SDimitry Andric }
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric const LegalizeRuleSet &
4300b57cec5SDimitry Andric LegalizerInfo::getActionDefinitions(unsigned Opcode) const {
4310b57cec5SDimitry Andric   unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
4320b57cec5SDimitry Andric   return RulesForOpcode[OpcodeIdx];
4330b57cec5SDimitry Andric }
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric LegalizeRuleSet &LegalizerInfo::getActionDefinitionsBuilder(unsigned Opcode) {
4360b57cec5SDimitry Andric   unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
4370b57cec5SDimitry Andric   auto &Result = RulesForOpcode[OpcodeIdx];
4380b57cec5SDimitry Andric   assert(!Result.isAliasedByAnother() && "Modifying this opcode will modify aliases");
4390b57cec5SDimitry Andric   return Result;
4400b57cec5SDimitry Andric }
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric LegalizeRuleSet &LegalizerInfo::getActionDefinitionsBuilder(
4430b57cec5SDimitry Andric     std::initializer_list<unsigned> Opcodes) {
4440b57cec5SDimitry Andric   unsigned Representative = *Opcodes.begin();
4450b57cec5SDimitry Andric 
4468bcb0991SDimitry Andric   assert(!llvm::empty(Opcodes) && Opcodes.begin() + 1 != Opcodes.end() &&
4470b57cec5SDimitry Andric          "Initializer list must have at least two opcodes");
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric   for (auto I = Opcodes.begin() + 1, E = Opcodes.end(); I != E; ++I)
4500b57cec5SDimitry Andric     aliasActionDefinitions(Representative, *I);
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   auto &Return = getActionDefinitionsBuilder(Representative);
4530b57cec5SDimitry Andric   Return.setIsAliasedByAnother();
4540b57cec5SDimitry Andric   return Return;
4550b57cec5SDimitry Andric }
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric void LegalizerInfo::aliasActionDefinitions(unsigned OpcodeTo,
4580b57cec5SDimitry Andric                                            unsigned OpcodeFrom) {
4590b57cec5SDimitry Andric   assert(OpcodeTo != OpcodeFrom && "Cannot alias to self");
4600b57cec5SDimitry Andric   assert(OpcodeTo >= FirstOp && OpcodeTo <= LastOp && "Unsupported opcode");
4610b57cec5SDimitry Andric   const unsigned OpcodeFromIdx = getOpcodeIdxForOpcode(OpcodeFrom);
4620b57cec5SDimitry Andric   RulesForOpcode[OpcodeFromIdx].aliasTo(OpcodeTo);
4630b57cec5SDimitry Andric }
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric LegalizeActionStep
4660b57cec5SDimitry Andric LegalizerInfo::getAction(const LegalityQuery &Query) const {
4670b57cec5SDimitry Andric   LegalizeActionStep Step = getActionDefinitions(Query.Opcode).apply(Query);
4680b57cec5SDimitry Andric   if (Step.Action != LegalizeAction::UseLegacyRules) {
4690b57cec5SDimitry Andric     return Step;
4700b57cec5SDimitry Andric   }
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   for (unsigned i = 0; i < Query.Types.size(); ++i) {
4730b57cec5SDimitry Andric     auto Action = getAspectAction({Query.Opcode, i, Query.Types[i]});
4740b57cec5SDimitry Andric     if (Action.first != Legal) {
4750b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << ".. (legacy) Type " << i << " Action="
4760b57cec5SDimitry Andric                         << Action.first << ", " << Action.second << "\n");
4770b57cec5SDimitry Andric       return {Action.first, i, Action.second};
4780b57cec5SDimitry Andric     } else
4790b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << ".. (legacy) Type " << i << " Legal\n");
4800b57cec5SDimitry Andric   }
4810b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << ".. (legacy) Legal\n");
4820b57cec5SDimitry Andric   return {Legal, 0, LLT{}};
4830b57cec5SDimitry Andric }
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric LegalizeActionStep
4860b57cec5SDimitry Andric LegalizerInfo::getAction(const MachineInstr &MI,
4870b57cec5SDimitry Andric                          const MachineRegisterInfo &MRI) const {
4880b57cec5SDimitry Andric   SmallVector<LLT, 2> Types;
4890b57cec5SDimitry Andric   SmallBitVector SeenTypes(8);
4900b57cec5SDimitry Andric   const MCOperandInfo *OpInfo = MI.getDesc().OpInfo;
4910b57cec5SDimitry Andric   // FIXME: probably we'll need to cache the results here somehow?
4920b57cec5SDimitry Andric   for (unsigned i = 0; i < MI.getDesc().getNumOperands(); ++i) {
4930b57cec5SDimitry Andric     if (!OpInfo[i].isGenericType())
4940b57cec5SDimitry Andric       continue;
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric     // We must only record actions once for each TypeIdx; otherwise we'd
4970b57cec5SDimitry Andric     // try to legalize operands multiple times down the line.
4980b57cec5SDimitry Andric     unsigned TypeIdx = OpInfo[i].getGenericTypeIndex();
4990b57cec5SDimitry Andric     if (SeenTypes[TypeIdx])
5000b57cec5SDimitry Andric       continue;
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric     SeenTypes.set(TypeIdx);
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric     LLT Ty = getTypeFromTypeIdx(MI, MRI, i, TypeIdx);
5050b57cec5SDimitry Andric     Types.push_back(Ty);
5060b57cec5SDimitry Andric   }
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   SmallVector<LegalityQuery::MemDesc, 2> MemDescrs;
5090b57cec5SDimitry Andric   for (const auto &MMO : MI.memoperands())
5100b57cec5SDimitry Andric     MemDescrs.push_back({8 * MMO->getSize() /* in bits */,
5115ffd83dbSDimitry Andric                          8 * MMO->getAlign().value(), MMO->getOrdering()});
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric   return getAction({MI.getOpcode(), Types, MemDescrs});
5140b57cec5SDimitry Andric }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric bool LegalizerInfo::isLegal(const MachineInstr &MI,
5170b57cec5SDimitry Andric                             const MachineRegisterInfo &MRI) const {
5180b57cec5SDimitry Andric   return getAction(MI, MRI).Action == Legal;
5190b57cec5SDimitry Andric }
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric bool LegalizerInfo::isLegalOrCustom(const MachineInstr &MI,
5220b57cec5SDimitry Andric                                     const MachineRegisterInfo &MRI) const {
5230b57cec5SDimitry Andric   auto Action = getAction(MI, MRI).Action;
5240b57cec5SDimitry Andric   // If the action is custom, it may not necessarily modify the instruction,
5250b57cec5SDimitry Andric   // so we have to assume it's legal.
5260b57cec5SDimitry Andric   return Action == Legal || Action == Custom;
5270b57cec5SDimitry Andric }
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric LegalizerInfo::SizeAndActionsVec
5300b57cec5SDimitry Andric LegalizerInfo::increaseToLargerTypesAndDecreaseToLargest(
5310b57cec5SDimitry Andric     const SizeAndActionsVec &v, LegalizeAction IncreaseAction,
5320b57cec5SDimitry Andric     LegalizeAction DecreaseAction) {
5330b57cec5SDimitry Andric   SizeAndActionsVec result;
5340b57cec5SDimitry Andric   unsigned LargestSizeSoFar = 0;
5350b57cec5SDimitry Andric   if (v.size() >= 1 && v[0].first != 1)
5360b57cec5SDimitry Andric     result.push_back({1, IncreaseAction});
5370b57cec5SDimitry Andric   for (size_t i = 0; i < v.size(); ++i) {
5380b57cec5SDimitry Andric     result.push_back(v[i]);
5390b57cec5SDimitry Andric     LargestSizeSoFar = v[i].first;
5400b57cec5SDimitry Andric     if (i + 1 < v.size() && v[i + 1].first != v[i].first + 1) {
5410b57cec5SDimitry Andric       result.push_back({LargestSizeSoFar + 1, IncreaseAction});
5420b57cec5SDimitry Andric       LargestSizeSoFar = v[i].first + 1;
5430b57cec5SDimitry Andric     }
5440b57cec5SDimitry Andric   }
5450b57cec5SDimitry Andric   result.push_back({LargestSizeSoFar + 1, DecreaseAction});
5460b57cec5SDimitry Andric   return result;
5470b57cec5SDimitry Andric }
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric LegalizerInfo::SizeAndActionsVec
5500b57cec5SDimitry Andric LegalizerInfo::decreaseToSmallerTypesAndIncreaseToSmallest(
5510b57cec5SDimitry Andric     const SizeAndActionsVec &v, LegalizeAction DecreaseAction,
5520b57cec5SDimitry Andric     LegalizeAction IncreaseAction) {
5530b57cec5SDimitry Andric   SizeAndActionsVec result;
5540b57cec5SDimitry Andric   if (v.size() == 0 || v[0].first != 1)
5550b57cec5SDimitry Andric     result.push_back({1, IncreaseAction});
5560b57cec5SDimitry Andric   for (size_t i = 0; i < v.size(); ++i) {
5570b57cec5SDimitry Andric     result.push_back(v[i]);
5580b57cec5SDimitry Andric     if (i + 1 == v.size() || v[i + 1].first != v[i].first + 1) {
5590b57cec5SDimitry Andric       result.push_back({v[i].first + 1, DecreaseAction});
5600b57cec5SDimitry Andric     }
5610b57cec5SDimitry Andric   }
5620b57cec5SDimitry Andric   return result;
5630b57cec5SDimitry Andric }
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric LegalizerInfo::SizeAndAction
5660b57cec5SDimitry Andric LegalizerInfo::findAction(const SizeAndActionsVec &Vec, const uint32_t Size) {
5670b57cec5SDimitry Andric   assert(Size >= 1);
5680b57cec5SDimitry Andric   // Find the last element in Vec that has a bitsize equal to or smaller than
5690b57cec5SDimitry Andric   // the requested bit size.
5700b57cec5SDimitry Andric   // That is the element just before the first element that is bigger than Size.
5710b57cec5SDimitry Andric   auto It = partition_point(
5720b57cec5SDimitry Andric       Vec, [=](const SizeAndAction &A) { return A.first <= Size; });
5730b57cec5SDimitry Andric   assert(It != Vec.begin() && "Does Vec not start with size 1?");
5740b57cec5SDimitry Andric   int VecIdx = It - Vec.begin() - 1;
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric   LegalizeAction Action = Vec[VecIdx].second;
5770b57cec5SDimitry Andric   switch (Action) {
5780b57cec5SDimitry Andric   case Legal:
5795ffd83dbSDimitry Andric   case Bitcast:
5800b57cec5SDimitry Andric   case Lower:
5810b57cec5SDimitry Andric   case Libcall:
5820b57cec5SDimitry Andric   case Custom:
5830b57cec5SDimitry Andric     return {Size, Action};
5840b57cec5SDimitry Andric   case FewerElements:
5850b57cec5SDimitry Andric     // FIXME: is this special case still needed and correct?
5860b57cec5SDimitry Andric     // Special case for scalarization:
5870b57cec5SDimitry Andric     if (Vec == SizeAndActionsVec({{1, FewerElements}}))
5880b57cec5SDimitry Andric       return {1, FewerElements};
5890b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
5900b57cec5SDimitry Andric   case NarrowScalar: {
5910b57cec5SDimitry Andric     // The following needs to be a loop, as for now, we do allow needing to
5920b57cec5SDimitry Andric     // go over "Unsupported" bit sizes before finding a legalizable bit size.
5930b57cec5SDimitry Andric     // e.g. (s8, WidenScalar), (s9, Unsupported), (s32, Legal). if Size==8,
5940b57cec5SDimitry Andric     // we need to iterate over s9, and then to s32 to return (s32, Legal).
5950b57cec5SDimitry Andric     // If we want to get rid of the below loop, we should have stronger asserts
5960b57cec5SDimitry Andric     // when building the SizeAndActionsVecs, probably not allowing
5970b57cec5SDimitry Andric     // "Unsupported" unless at the ends of the vector.
5980b57cec5SDimitry Andric     for (int i = VecIdx - 1; i >= 0; --i)
5990b57cec5SDimitry Andric       if (!needsLegalizingToDifferentSize(Vec[i].second) &&
6000b57cec5SDimitry Andric           Vec[i].second != Unsupported)
6010b57cec5SDimitry Andric         return {Vec[i].first, Action};
6020b57cec5SDimitry Andric     llvm_unreachable("");
6030b57cec5SDimitry Andric   }
6040b57cec5SDimitry Andric   case WidenScalar:
6050b57cec5SDimitry Andric   case MoreElements: {
6060b57cec5SDimitry Andric     // See above, the following needs to be a loop, at least for now.
6070b57cec5SDimitry Andric     for (std::size_t i = VecIdx + 1; i < Vec.size(); ++i)
6080b57cec5SDimitry Andric       if (!needsLegalizingToDifferentSize(Vec[i].second) &&
6090b57cec5SDimitry Andric           Vec[i].second != Unsupported)
6100b57cec5SDimitry Andric         return {Vec[i].first, Action};
6110b57cec5SDimitry Andric     llvm_unreachable("");
6120b57cec5SDimitry Andric   }
6130b57cec5SDimitry Andric   case Unsupported:
6140b57cec5SDimitry Andric     return {Size, Unsupported};
6150b57cec5SDimitry Andric   case NotFound:
6160b57cec5SDimitry Andric   case UseLegacyRules:
6170b57cec5SDimitry Andric     llvm_unreachable("NotFound");
6180b57cec5SDimitry Andric   }
6190b57cec5SDimitry Andric   llvm_unreachable("Action has an unknown enum value");
6200b57cec5SDimitry Andric }
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric std::pair<LegalizeAction, LLT>
6230b57cec5SDimitry Andric LegalizerInfo::findScalarLegalAction(const InstrAspect &Aspect) const {
6240b57cec5SDimitry Andric   assert(Aspect.Type.isScalar() || Aspect.Type.isPointer());
6250b57cec5SDimitry Andric   if (Aspect.Opcode < FirstOp || Aspect.Opcode > LastOp)
6260b57cec5SDimitry Andric     return {NotFound, LLT()};
6270b57cec5SDimitry Andric   const unsigned OpcodeIdx = getOpcodeIdxForOpcode(Aspect.Opcode);
6280b57cec5SDimitry Andric   if (Aspect.Type.isPointer() &&
6290b57cec5SDimitry Andric       AddrSpace2PointerActions[OpcodeIdx].find(Aspect.Type.getAddressSpace()) ==
6300b57cec5SDimitry Andric           AddrSpace2PointerActions[OpcodeIdx].end()) {
6310b57cec5SDimitry Andric     return {NotFound, LLT()};
6320b57cec5SDimitry Andric   }
6330b57cec5SDimitry Andric   const SmallVector<SizeAndActionsVec, 1> &Actions =
6340b57cec5SDimitry Andric       Aspect.Type.isPointer()
6350b57cec5SDimitry Andric           ? AddrSpace2PointerActions[OpcodeIdx]
6360b57cec5SDimitry Andric                 .find(Aspect.Type.getAddressSpace())
6370b57cec5SDimitry Andric                 ->second
6380b57cec5SDimitry Andric           : ScalarActions[OpcodeIdx];
6390b57cec5SDimitry Andric   if (Aspect.Idx >= Actions.size())
6400b57cec5SDimitry Andric     return {NotFound, LLT()};
6410b57cec5SDimitry Andric   const SizeAndActionsVec &Vec = Actions[Aspect.Idx];
6420b57cec5SDimitry Andric   // FIXME: speed up this search, e.g. by using a results cache for repeated
6430b57cec5SDimitry Andric   // queries?
6440b57cec5SDimitry Andric   auto SizeAndAction = findAction(Vec, Aspect.Type.getSizeInBits());
6450b57cec5SDimitry Andric   return {SizeAndAction.second,
6460b57cec5SDimitry Andric           Aspect.Type.isScalar() ? LLT::scalar(SizeAndAction.first)
6470b57cec5SDimitry Andric                                  : LLT::pointer(Aspect.Type.getAddressSpace(),
6480b57cec5SDimitry Andric                                                 SizeAndAction.first)};
6490b57cec5SDimitry Andric }
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric std::pair<LegalizeAction, LLT>
6520b57cec5SDimitry Andric LegalizerInfo::findVectorLegalAction(const InstrAspect &Aspect) const {
6530b57cec5SDimitry Andric   assert(Aspect.Type.isVector());
6540b57cec5SDimitry Andric   // First legalize the vector element size, then legalize the number of
6550b57cec5SDimitry Andric   // lanes in the vector.
6560b57cec5SDimitry Andric   if (Aspect.Opcode < FirstOp || Aspect.Opcode > LastOp)
6570b57cec5SDimitry Andric     return {NotFound, Aspect.Type};
6580b57cec5SDimitry Andric   const unsigned OpcodeIdx = getOpcodeIdxForOpcode(Aspect.Opcode);
6590b57cec5SDimitry Andric   const unsigned TypeIdx = Aspect.Idx;
6600b57cec5SDimitry Andric   if (TypeIdx >= ScalarInVectorActions[OpcodeIdx].size())
6610b57cec5SDimitry Andric     return {NotFound, Aspect.Type};
6620b57cec5SDimitry Andric   const SizeAndActionsVec &ElemSizeVec =
6630b57cec5SDimitry Andric       ScalarInVectorActions[OpcodeIdx][TypeIdx];
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   LLT IntermediateType;
6660b57cec5SDimitry Andric   auto ElementSizeAndAction =
6670b57cec5SDimitry Andric       findAction(ElemSizeVec, Aspect.Type.getScalarSizeInBits());
6680b57cec5SDimitry Andric   IntermediateType =
6690b57cec5SDimitry Andric       LLT::vector(Aspect.Type.getNumElements(), ElementSizeAndAction.first);
6700b57cec5SDimitry Andric   if (ElementSizeAndAction.second != Legal)
6710b57cec5SDimitry Andric     return {ElementSizeAndAction.second, IntermediateType};
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric   auto i = NumElements2Actions[OpcodeIdx].find(
6740b57cec5SDimitry Andric       IntermediateType.getScalarSizeInBits());
6750b57cec5SDimitry Andric   if (i == NumElements2Actions[OpcodeIdx].end()) {
6760b57cec5SDimitry Andric     return {NotFound, IntermediateType};
6770b57cec5SDimitry Andric   }
6780b57cec5SDimitry Andric   const SizeAndActionsVec &NumElementsVec = (*i).second[TypeIdx];
6790b57cec5SDimitry Andric   auto NumElementsAndAction =
6800b57cec5SDimitry Andric       findAction(NumElementsVec, IntermediateType.getNumElements());
6810b57cec5SDimitry Andric   return {NumElementsAndAction.second,
6820b57cec5SDimitry Andric           LLT::vector(NumElementsAndAction.first,
6830b57cec5SDimitry Andric                       IntermediateType.getScalarSizeInBits())};
6840b57cec5SDimitry Andric }
6850b57cec5SDimitry Andric 
686480093f4SDimitry Andric unsigned LegalizerInfo::getExtOpcodeForWideningConstant(LLT SmallTy) const {
687480093f4SDimitry Andric   return SmallTy.isByteSized() ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
688480093f4SDimitry Andric }
689480093f4SDimitry Andric 
6900b57cec5SDimitry Andric /// \pre Type indices of every opcode form a dense set starting from 0.
6910b57cec5SDimitry Andric void LegalizerInfo::verify(const MCInstrInfo &MII) const {
6920b57cec5SDimitry Andric #ifndef NDEBUG
6930b57cec5SDimitry Andric   std::vector<unsigned> FailedOpcodes;
6940b57cec5SDimitry Andric   for (unsigned Opcode = FirstOp; Opcode <= LastOp; ++Opcode) {
6950b57cec5SDimitry Andric     const MCInstrDesc &MCID = MII.get(Opcode);
6960b57cec5SDimitry Andric     const unsigned NumTypeIdxs = std::accumulate(
6970b57cec5SDimitry Andric         MCID.opInfo_begin(), MCID.opInfo_end(), 0U,
6980b57cec5SDimitry Andric         [](unsigned Acc, const MCOperandInfo &OpInfo) {
6990b57cec5SDimitry Andric           return OpInfo.isGenericType()
7000b57cec5SDimitry Andric                      ? std::max(OpInfo.getGenericTypeIndex() + 1U, Acc)
7010b57cec5SDimitry Andric                      : Acc;
7020b57cec5SDimitry Andric         });
7038bcb0991SDimitry Andric     const unsigned NumImmIdxs = std::accumulate(
7048bcb0991SDimitry Andric         MCID.opInfo_begin(), MCID.opInfo_end(), 0U,
7058bcb0991SDimitry Andric         [](unsigned Acc, const MCOperandInfo &OpInfo) {
7068bcb0991SDimitry Andric           return OpInfo.isGenericImm()
7078bcb0991SDimitry Andric                      ? std::max(OpInfo.getGenericImmIndex() + 1U, Acc)
7088bcb0991SDimitry Andric                      : Acc;
7098bcb0991SDimitry Andric         });
7100b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << MII.getName(Opcode) << " (opcode " << Opcode
7110b57cec5SDimitry Andric                       << "): " << NumTypeIdxs << " type ind"
7128bcb0991SDimitry Andric                       << (NumTypeIdxs == 1 ? "ex" : "ices") << ", "
7138bcb0991SDimitry Andric                       << NumImmIdxs << " imm ind"
7148bcb0991SDimitry Andric                       << (NumImmIdxs == 1 ? "ex" : "ices") << "\n");
7150b57cec5SDimitry Andric     const LegalizeRuleSet &RuleSet = getActionDefinitions(Opcode);
7160b57cec5SDimitry Andric     if (!RuleSet.verifyTypeIdxsCoverage(NumTypeIdxs))
7170b57cec5SDimitry Andric       FailedOpcodes.push_back(Opcode);
7188bcb0991SDimitry Andric     else if (!RuleSet.verifyImmIdxsCoverage(NumImmIdxs))
7198bcb0991SDimitry Andric       FailedOpcodes.push_back(Opcode);
7200b57cec5SDimitry Andric   }
7210b57cec5SDimitry Andric   if (!FailedOpcodes.empty()) {
7220b57cec5SDimitry Andric     errs() << "The following opcodes have ill-defined legalization rules:";
7230b57cec5SDimitry Andric     for (unsigned Opcode : FailedOpcodes)
7240b57cec5SDimitry Andric       errs() << " " << MII.getName(Opcode);
7250b57cec5SDimitry Andric     errs() << "\n";
7260b57cec5SDimitry Andric 
7270b57cec5SDimitry Andric     report_fatal_error("ill-defined LegalizerInfo"
7280b57cec5SDimitry Andric                        ", try -debug-only=legalizer-info for details");
7290b57cec5SDimitry Andric   }
7300b57cec5SDimitry Andric #endif
7310b57cec5SDimitry Andric }
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric #ifndef NDEBUG
7340b57cec5SDimitry Andric // FIXME: This should be in the MachineVerifier, but it can't use the
7350b57cec5SDimitry Andric // LegalizerInfo as it's currently in the separate GlobalISel library.
7360b57cec5SDimitry Andric // Note that RegBankSelected property already checked in the verifier
7370b57cec5SDimitry Andric // has the same layering problem, but we only use inline methods so
7380b57cec5SDimitry Andric // end up not needing to link against the GlobalISel library.
7390b57cec5SDimitry Andric const MachineInstr *llvm::machineFunctionIsIllegal(const MachineFunction &MF) {
7400b57cec5SDimitry Andric   if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo()) {
7410b57cec5SDimitry Andric     const MachineRegisterInfo &MRI = MF.getRegInfo();
7420b57cec5SDimitry Andric     for (const MachineBasicBlock &MBB : MF)
7430b57cec5SDimitry Andric       for (const MachineInstr &MI : MBB)
7440b57cec5SDimitry Andric         if (isPreISelGenericOpcode(MI.getOpcode()) &&
7450b57cec5SDimitry Andric             !MLI->isLegalOrCustom(MI, MRI))
7460b57cec5SDimitry Andric           return &MI;
7470b57cec5SDimitry Andric   }
7480b57cec5SDimitry Andric   return nullptr;
7490b57cec5SDimitry Andric }
7500b57cec5SDimitry Andric #endif
751