1 //===- lib/CodeGen/GlobalISel/LegalizerInfo.cpp - Legalizer ---------------===//
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 // Implement an interface to specify and query how an illegal operation on a
10 // given type should be expanded.
11 //
12 // Issues to be resolved:
13 //   + Make it fast.
14 //   + Support weird types like i3, <7 x i3>, ...
15 //   + Operations with more than one type (ICMP, CMPXCHG, intrinsics, ...)
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
20 #include "llvm/ADT/SmallBitVector.h"
21 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineOperand.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/TargetOpcodes.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/LowLevelTypeImpl.h"
31 #include "llvm/Support/MathExtras.h"
32 #include <algorithm>
33 #include <map>
34 
35 using namespace llvm;
36 using namespace LegalizeActions;
37 
38 #define DEBUG_TYPE "legalizer-info"
39 
40 cl::opt<bool> llvm::DisableGISelLegalityCheck(
41     "disable-gisel-legality-check",
42     cl::desc("Don't verify that MIR is fully legal between GlobalISel passes"),
43     cl::Hidden);
44 
45 raw_ostream &llvm::operator<<(raw_ostream &OS, LegalizeAction Action) {
46   switch (Action) {
47   case Legal:
48     OS << "Legal";
49     break;
50   case NarrowScalar:
51     OS << "NarrowScalar";
52     break;
53   case WidenScalar:
54     OS << "WidenScalar";
55     break;
56   case FewerElements:
57     OS << "FewerElements";
58     break;
59   case MoreElements:
60     OS << "MoreElements";
61     break;
62   case Bitcast:
63     OS << "Bitcast";
64     break;
65   case Lower:
66     OS << "Lower";
67     break;
68   case Libcall:
69     OS << "Libcall";
70     break;
71   case Custom:
72     OS << "Custom";
73     break;
74   case Unsupported:
75     OS << "Unsupported";
76     break;
77   case NotFound:
78     OS << "NotFound";
79     break;
80   case UseLegacyRules:
81     OS << "UseLegacyRules";
82     break;
83   }
84   return OS;
85 }
86 
87 raw_ostream &LegalityQuery::print(raw_ostream &OS) const {
88   OS << Opcode << ", Tys={";
89   for (const auto &Type : Types) {
90     OS << Type << ", ";
91   }
92   OS << "}, Opcode=";
93 
94   OS << Opcode << ", MMOs={";
95   for (const auto &MMODescr : MMODescrs) {
96     OS << MMODescr.SizeInBits << ", ";
97   }
98   OS << "}";
99 
100   return OS;
101 }
102 
103 #ifndef NDEBUG
104 // Make sure the rule won't (trivially) loop forever.
105 static bool hasNoSimpleLoops(const LegalizeRule &Rule, const LegalityQuery &Q,
106                              const std::pair<unsigned, LLT> &Mutation) {
107   switch (Rule.getAction()) {
108   case Legal:
109   case Custom:
110   case Lower:
111   case MoreElements:
112   case FewerElements:
113     break;
114   default:
115     return Q.Types[Mutation.first] != Mutation.second;
116   }
117   return true;
118 }
119 
120 // Make sure the returned mutation makes sense for the match type.
121 static bool mutationIsSane(const LegalizeRule &Rule,
122                            const LegalityQuery &Q,
123                            std::pair<unsigned, LLT> Mutation) {
124   // If the user wants a custom mutation, then we can't really say much about
125   // it. Return true, and trust that they're doing the right thing.
126   if (Rule.getAction() == Custom || Rule.getAction() == Legal)
127     return true;
128 
129   const unsigned TypeIdx = Mutation.first;
130   const LLT OldTy = Q.Types[TypeIdx];
131   const LLT NewTy = Mutation.second;
132 
133   switch (Rule.getAction()) {
134   case FewerElements:
135     if (!OldTy.isVector())
136       return false;
137     LLVM_FALLTHROUGH;
138   case MoreElements: {
139     // MoreElements can go from scalar to vector.
140     const unsigned OldElts = OldTy.isVector() ? OldTy.getNumElements() : 1;
141     if (NewTy.isVector()) {
142       if (Rule.getAction() == FewerElements) {
143         // Make sure the element count really decreased.
144         if (NewTy.getNumElements() >= OldElts)
145           return false;
146       } else {
147         // Make sure the element count really increased.
148         if (NewTy.getNumElements() <= OldElts)
149           return false;
150       }
151     }
152 
153     // Make sure the element type didn't change.
154     return NewTy.getScalarType() == OldTy.getScalarType();
155   }
156   case NarrowScalar:
157   case WidenScalar: {
158     if (OldTy.isVector()) {
159       // Number of elements should not change.
160       if (!NewTy.isVector() || OldTy.getNumElements() != NewTy.getNumElements())
161         return false;
162     } else {
163       // Both types must be vectors
164       if (NewTy.isVector())
165         return false;
166     }
167 
168     if (Rule.getAction() == NarrowScalar)  {
169       // Make sure the size really decreased.
170       if (NewTy.getScalarSizeInBits() >= OldTy.getScalarSizeInBits())
171         return false;
172     } else {
173       // Make sure the size really increased.
174       if (NewTy.getScalarSizeInBits() <= OldTy.getScalarSizeInBits())
175         return false;
176     }
177 
178     return true;
179   }
180   case Bitcast: {
181     return OldTy != NewTy && OldTy.getSizeInBits() == NewTy.getSizeInBits();
182   }
183   default:
184     return true;
185   }
186 }
187 #endif
188 
189 LegalizeActionStep LegalizeRuleSet::apply(const LegalityQuery &Query) const {
190   LLVM_DEBUG(dbgs() << "Applying legalizer ruleset to: "; Query.print(dbgs());
191              dbgs() << "\n");
192   if (Rules.empty()) {
193     LLVM_DEBUG(dbgs() << ".. fallback to legacy rules (no rules defined)\n");
194     return {LegalizeAction::UseLegacyRules, 0, LLT{}};
195   }
196   for (const LegalizeRule &Rule : Rules) {
197     if (Rule.match(Query)) {
198       LLVM_DEBUG(dbgs() << ".. match\n");
199       std::pair<unsigned, LLT> Mutation = Rule.determineMutation(Query);
200       LLVM_DEBUG(dbgs() << ".. .. " << Rule.getAction() << ", "
201                         << Mutation.first << ", " << Mutation.second << "\n");
202       assert(mutationIsSane(Rule, Query, Mutation) &&
203              "legality mutation invalid for match");
204       assert(hasNoSimpleLoops(Rule, Query, Mutation) && "Simple loop detected");
205       return {Rule.getAction(), Mutation.first, Mutation.second};
206     } else
207       LLVM_DEBUG(dbgs() << ".. no match\n");
208   }
209   LLVM_DEBUG(dbgs() << ".. unsupported\n");
210   return {LegalizeAction::Unsupported, 0, LLT{}};
211 }
212 
213 bool LegalizeRuleSet::verifyTypeIdxsCoverage(unsigned NumTypeIdxs) const {
214 #ifndef NDEBUG
215   if (Rules.empty()) {
216     LLVM_DEBUG(
217         dbgs() << ".. type index coverage check SKIPPED: no rules defined\n");
218     return true;
219   }
220   const int64_t FirstUncovered = TypeIdxsCovered.find_first_unset();
221   if (FirstUncovered < 0) {
222     LLVM_DEBUG(dbgs() << ".. type index coverage check SKIPPED:"
223                          " user-defined predicate detected\n");
224     return true;
225   }
226   const bool AllCovered = (FirstUncovered >= NumTypeIdxs);
227   if (NumTypeIdxs > 0)
228     LLVM_DEBUG(dbgs() << ".. the first uncovered type index: " << FirstUncovered
229                       << ", " << (AllCovered ? "OK" : "FAIL") << "\n");
230   return AllCovered;
231 #else
232   return true;
233 #endif
234 }
235 
236 bool LegalizeRuleSet::verifyImmIdxsCoverage(unsigned NumImmIdxs) const {
237 #ifndef NDEBUG
238   if (Rules.empty()) {
239     LLVM_DEBUG(
240         dbgs() << ".. imm index coverage check SKIPPED: no rules defined\n");
241     return true;
242   }
243   const int64_t FirstUncovered = ImmIdxsCovered.find_first_unset();
244   if (FirstUncovered < 0) {
245     LLVM_DEBUG(dbgs() << ".. imm index coverage check SKIPPED:"
246                          " user-defined predicate detected\n");
247     return true;
248   }
249   const bool AllCovered = (FirstUncovered >= NumImmIdxs);
250   LLVM_DEBUG(dbgs() << ".. the first uncovered imm index: " << FirstUncovered
251                     << ", " << (AllCovered ? "OK" : "FAIL") << "\n");
252   return AllCovered;
253 #else
254   return true;
255 #endif
256 }
257 
258 LegalizerInfo::LegalizerInfo() : TablesInitialized(false) {
259   // Set defaults.
260   // FIXME: these two (G_ANYEXT and G_TRUNC?) can be legalized to the
261   // fundamental load/store Jakob proposed. Once loads & stores are supported.
262   setScalarAction(TargetOpcode::G_ANYEXT, 1, {{1, Legal}});
263   setScalarAction(TargetOpcode::G_ZEXT, 1, {{1, Legal}});
264   setScalarAction(TargetOpcode::G_SEXT, 1, {{1, Legal}});
265   setScalarAction(TargetOpcode::G_TRUNC, 0, {{1, Legal}});
266   setScalarAction(TargetOpcode::G_TRUNC, 1, {{1, Legal}});
267 
268   setScalarAction(TargetOpcode::G_INTRINSIC, 0, {{1, Legal}});
269   setScalarAction(TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS, 0, {{1, Legal}});
270 
271   setLegalizeScalarToDifferentSizeStrategy(
272       TargetOpcode::G_IMPLICIT_DEF, 0, narrowToSmallerAndUnsupportedIfTooSmall);
273   setLegalizeScalarToDifferentSizeStrategy(
274       TargetOpcode::G_ADD, 0, widenToLargerTypesAndNarrowToLargest);
275   setLegalizeScalarToDifferentSizeStrategy(
276       TargetOpcode::G_OR, 0, widenToLargerTypesAndNarrowToLargest);
277   setLegalizeScalarToDifferentSizeStrategy(
278       TargetOpcode::G_LOAD, 0, narrowToSmallerAndUnsupportedIfTooSmall);
279   setLegalizeScalarToDifferentSizeStrategy(
280       TargetOpcode::G_STORE, 0, narrowToSmallerAndUnsupportedIfTooSmall);
281 
282   setLegalizeScalarToDifferentSizeStrategy(
283       TargetOpcode::G_BRCOND, 0, widenToLargerTypesUnsupportedOtherwise);
284   setLegalizeScalarToDifferentSizeStrategy(
285       TargetOpcode::G_INSERT, 0, narrowToSmallerAndUnsupportedIfTooSmall);
286   setLegalizeScalarToDifferentSizeStrategy(
287       TargetOpcode::G_EXTRACT, 0, narrowToSmallerAndUnsupportedIfTooSmall);
288   setLegalizeScalarToDifferentSizeStrategy(
289       TargetOpcode::G_EXTRACT, 1, narrowToSmallerAndUnsupportedIfTooSmall);
290   setScalarAction(TargetOpcode::G_FNEG, 0, {{1, Lower}});
291 }
292 
293 void LegalizerInfo::computeTables() {
294   assert(TablesInitialized == false);
295 
296   for (unsigned OpcodeIdx = 0; OpcodeIdx <= LastOp - FirstOp; ++OpcodeIdx) {
297     const unsigned Opcode = FirstOp + OpcodeIdx;
298     for (unsigned TypeIdx = 0; TypeIdx != SpecifiedActions[OpcodeIdx].size();
299          ++TypeIdx) {
300       // 0. Collect information specified through the setAction API, i.e.
301       // for specific bit sizes.
302       // For scalar types:
303       SizeAndActionsVec ScalarSpecifiedActions;
304       // For pointer types:
305       std::map<uint16_t, SizeAndActionsVec> AddressSpace2SpecifiedActions;
306       // For vector types:
307       std::map<uint16_t, SizeAndActionsVec> ElemSize2SpecifiedActions;
308       for (auto LLT2Action : SpecifiedActions[OpcodeIdx][TypeIdx]) {
309         const LLT Type = LLT2Action.first;
310         const LegalizeAction Action = LLT2Action.second;
311 
312         auto SizeAction = std::make_pair(Type.getSizeInBits(), Action);
313         if (Type.isPointer())
314           AddressSpace2SpecifiedActions[Type.getAddressSpace()].push_back(
315               SizeAction);
316         else if (Type.isVector())
317           ElemSize2SpecifiedActions[Type.getElementType().getSizeInBits()]
318               .push_back(SizeAction);
319         else
320           ScalarSpecifiedActions.push_back(SizeAction);
321       }
322 
323       // 1. Handle scalar types
324       {
325         // Decide how to handle bit sizes for which no explicit specification
326         // was given.
327         SizeChangeStrategy S = &unsupportedForDifferentSizes;
328         if (TypeIdx < ScalarSizeChangeStrategies[OpcodeIdx].size() &&
329             ScalarSizeChangeStrategies[OpcodeIdx][TypeIdx] != nullptr)
330           S = ScalarSizeChangeStrategies[OpcodeIdx][TypeIdx];
331         llvm::sort(ScalarSpecifiedActions);
332         checkPartialSizeAndActionsVector(ScalarSpecifiedActions);
333         setScalarAction(Opcode, TypeIdx, S(ScalarSpecifiedActions));
334       }
335 
336       // 2. Handle pointer types
337       for (auto PointerSpecifiedActions : AddressSpace2SpecifiedActions) {
338         llvm::sort(PointerSpecifiedActions.second);
339         checkPartialSizeAndActionsVector(PointerSpecifiedActions.second);
340         // For pointer types, we assume that there isn't a meaningfull way
341         // to change the number of bits used in the pointer.
342         setPointerAction(
343             Opcode, TypeIdx, PointerSpecifiedActions.first,
344             unsupportedForDifferentSizes(PointerSpecifiedActions.second));
345       }
346 
347       // 3. Handle vector types
348       SizeAndActionsVec ElementSizesSeen;
349       for (auto VectorSpecifiedActions : ElemSize2SpecifiedActions) {
350         llvm::sort(VectorSpecifiedActions.second);
351         const uint16_t ElementSize = VectorSpecifiedActions.first;
352         ElementSizesSeen.push_back({ElementSize, Legal});
353         checkPartialSizeAndActionsVector(VectorSpecifiedActions.second);
354         // For vector types, we assume that the best way to adapt the number
355         // of elements is to the next larger number of elements type for which
356         // the vector type is legal, unless there is no such type. In that case,
357         // legalize towards a vector type with a smaller number of elements.
358         SizeAndActionsVec NumElementsActions;
359         for (SizeAndAction BitsizeAndAction : VectorSpecifiedActions.second) {
360           assert(BitsizeAndAction.first % ElementSize == 0);
361           const uint16_t NumElements = BitsizeAndAction.first / ElementSize;
362           NumElementsActions.push_back({NumElements, BitsizeAndAction.second});
363         }
364         setVectorNumElementAction(
365             Opcode, TypeIdx, ElementSize,
366             moreToWiderTypesAndLessToWidest(NumElementsActions));
367       }
368       llvm::sort(ElementSizesSeen);
369       SizeChangeStrategy VectorElementSizeChangeStrategy =
370           &unsupportedForDifferentSizes;
371       if (TypeIdx < VectorElementSizeChangeStrategies[OpcodeIdx].size() &&
372           VectorElementSizeChangeStrategies[OpcodeIdx][TypeIdx] != nullptr)
373         VectorElementSizeChangeStrategy =
374             VectorElementSizeChangeStrategies[OpcodeIdx][TypeIdx];
375       setScalarInVectorAction(
376           Opcode, TypeIdx, VectorElementSizeChangeStrategy(ElementSizesSeen));
377     }
378   }
379 
380   TablesInitialized = true;
381 }
382 
383 // FIXME: inefficient implementation for now. Without ComputeValueVTs we're
384 // probably going to need specialized lookup structures for various types before
385 // we have any hope of doing well with something like <13 x i3>. Even the common
386 // cases should do better than what we have now.
387 std::pair<LegalizeAction, LLT>
388 LegalizerInfo::getAspectAction(const InstrAspect &Aspect) const {
389   assert(TablesInitialized && "backend forgot to call computeTables");
390   // These *have* to be implemented for now, they're the fundamental basis of
391   // how everything else is transformed.
392   if (Aspect.Type.isScalar() || Aspect.Type.isPointer())
393     return findScalarLegalAction(Aspect);
394   assert(Aspect.Type.isVector());
395   return findVectorLegalAction(Aspect);
396 }
397 
398 /// Helper function to get LLT for the given type index.
399 static LLT getTypeFromTypeIdx(const MachineInstr &MI,
400                               const MachineRegisterInfo &MRI, unsigned OpIdx,
401                               unsigned TypeIdx) {
402   assert(TypeIdx < MI.getNumOperands() && "Unexpected TypeIdx");
403   // G_UNMERGE_VALUES has variable number of operands, but there is only
404   // one source type and one destination type as all destinations must be the
405   // same type. So, get the last operand if TypeIdx == 1.
406   if (MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && TypeIdx == 1)
407     return MRI.getType(MI.getOperand(MI.getNumOperands() - 1).getReg());
408   return MRI.getType(MI.getOperand(OpIdx).getReg());
409 }
410 
411 unsigned LegalizerInfo::getOpcodeIdxForOpcode(unsigned Opcode) const {
412   assert(Opcode >= FirstOp && Opcode <= LastOp && "Unsupported opcode");
413   return Opcode - FirstOp;
414 }
415 
416 unsigned LegalizerInfo::getActionDefinitionsIdx(unsigned Opcode) const {
417   unsigned OpcodeIdx = getOpcodeIdxForOpcode(Opcode);
418   if (unsigned Alias = RulesForOpcode[OpcodeIdx].getAlias()) {
419     LLVM_DEBUG(dbgs() << ".. opcode " << Opcode << " is aliased to " << Alias
420                       << "\n");
421     OpcodeIdx = getOpcodeIdxForOpcode(Alias);
422     assert(RulesForOpcode[OpcodeIdx].getAlias() == 0 && "Cannot chain aliases");
423   }
424 
425   return OpcodeIdx;
426 }
427 
428 const LegalizeRuleSet &
429 LegalizerInfo::getActionDefinitions(unsigned Opcode) const {
430   unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
431   return RulesForOpcode[OpcodeIdx];
432 }
433 
434 LegalizeRuleSet &LegalizerInfo::getActionDefinitionsBuilder(unsigned Opcode) {
435   unsigned OpcodeIdx = getActionDefinitionsIdx(Opcode);
436   auto &Result = RulesForOpcode[OpcodeIdx];
437   assert(!Result.isAliasedByAnother() && "Modifying this opcode will modify aliases");
438   return Result;
439 }
440 
441 LegalizeRuleSet &LegalizerInfo::getActionDefinitionsBuilder(
442     std::initializer_list<unsigned> Opcodes) {
443   unsigned Representative = *Opcodes.begin();
444 
445   assert(!llvm::empty(Opcodes) && Opcodes.begin() + 1 != Opcodes.end() &&
446          "Initializer list must have at least two opcodes");
447 
448   for (auto I = Opcodes.begin() + 1, E = Opcodes.end(); I != E; ++I)
449     aliasActionDefinitions(Representative, *I);
450 
451   auto &Return = getActionDefinitionsBuilder(Representative);
452   Return.setIsAliasedByAnother();
453   return Return;
454 }
455 
456 void LegalizerInfo::aliasActionDefinitions(unsigned OpcodeTo,
457                                            unsigned OpcodeFrom) {
458   assert(OpcodeTo != OpcodeFrom && "Cannot alias to self");
459   assert(OpcodeTo >= FirstOp && OpcodeTo <= LastOp && "Unsupported opcode");
460   const unsigned OpcodeFromIdx = getOpcodeIdxForOpcode(OpcodeFrom);
461   RulesForOpcode[OpcodeFromIdx].aliasTo(OpcodeTo);
462 }
463 
464 LegalizeActionStep
465 LegalizerInfo::getAction(const LegalityQuery &Query) const {
466   LegalizeActionStep Step = getActionDefinitions(Query.Opcode).apply(Query);
467   if (Step.Action != LegalizeAction::UseLegacyRules) {
468     return Step;
469   }
470 
471   for (unsigned i = 0; i < Query.Types.size(); ++i) {
472     auto Action = getAspectAction({Query.Opcode, i, Query.Types[i]});
473     if (Action.first != Legal) {
474       LLVM_DEBUG(dbgs() << ".. (legacy) Type " << i << " Action="
475                         << Action.first << ", " << Action.second << "\n");
476       return {Action.first, i, Action.second};
477     } else
478       LLVM_DEBUG(dbgs() << ".. (legacy) Type " << i << " Legal\n");
479   }
480   LLVM_DEBUG(dbgs() << ".. (legacy) Legal\n");
481   return {Legal, 0, LLT{}};
482 }
483 
484 LegalizeActionStep
485 LegalizerInfo::getAction(const MachineInstr &MI,
486                          const MachineRegisterInfo &MRI) const {
487   SmallVector<LLT, 2> Types;
488   SmallBitVector SeenTypes(8);
489   const MCOperandInfo *OpInfo = MI.getDesc().OpInfo;
490   // FIXME: probably we'll need to cache the results here somehow?
491   for (unsigned i = 0; i < MI.getDesc().getNumOperands(); ++i) {
492     if (!OpInfo[i].isGenericType())
493       continue;
494 
495     // We must only record actions once for each TypeIdx; otherwise we'd
496     // try to legalize operands multiple times down the line.
497     unsigned TypeIdx = OpInfo[i].getGenericTypeIndex();
498     if (SeenTypes[TypeIdx])
499       continue;
500 
501     SeenTypes.set(TypeIdx);
502 
503     LLT Ty = getTypeFromTypeIdx(MI, MRI, i, TypeIdx);
504     Types.push_back(Ty);
505   }
506 
507   SmallVector<LegalityQuery::MemDesc, 2> MemDescrs;
508   for (const auto &MMO : MI.memoperands())
509     MemDescrs.push_back({8 * MMO->getSize() /* in bits */,
510                          8 * MMO->getAlign().value(), MMO->getOrdering()});
511 
512   return getAction({MI.getOpcode(), Types, MemDescrs});
513 }
514 
515 bool LegalizerInfo::isLegal(const MachineInstr &MI,
516                             const MachineRegisterInfo &MRI) const {
517   return getAction(MI, MRI).Action == Legal;
518 }
519 
520 bool LegalizerInfo::isLegalOrCustom(const MachineInstr &MI,
521                                     const MachineRegisterInfo &MRI) const {
522   auto Action = getAction(MI, MRI).Action;
523   // If the action is custom, it may not necessarily modify the instruction,
524   // so we have to assume it's legal.
525   return Action == Legal || Action == Custom;
526 }
527 
528 LegalizerInfo::SizeAndActionsVec
529 LegalizerInfo::increaseToLargerTypesAndDecreaseToLargest(
530     const SizeAndActionsVec &v, LegalizeAction IncreaseAction,
531     LegalizeAction DecreaseAction) {
532   SizeAndActionsVec result;
533   unsigned LargestSizeSoFar = 0;
534   if (v.size() >= 1 && v[0].first != 1)
535     result.push_back({1, IncreaseAction});
536   for (size_t i = 0; i < v.size(); ++i) {
537     result.push_back(v[i]);
538     LargestSizeSoFar = v[i].first;
539     if (i + 1 < v.size() && v[i + 1].first != v[i].first + 1) {
540       result.push_back({LargestSizeSoFar + 1, IncreaseAction});
541       LargestSizeSoFar = v[i].first + 1;
542     }
543   }
544   result.push_back({LargestSizeSoFar + 1, DecreaseAction});
545   return result;
546 }
547 
548 LegalizerInfo::SizeAndActionsVec
549 LegalizerInfo::decreaseToSmallerTypesAndIncreaseToSmallest(
550     const SizeAndActionsVec &v, LegalizeAction DecreaseAction,
551     LegalizeAction IncreaseAction) {
552   SizeAndActionsVec result;
553   if (v.size() == 0 || v[0].first != 1)
554     result.push_back({1, IncreaseAction});
555   for (size_t i = 0; i < v.size(); ++i) {
556     result.push_back(v[i]);
557     if (i + 1 == v.size() || v[i + 1].first != v[i].first + 1) {
558       result.push_back({v[i].first + 1, DecreaseAction});
559     }
560   }
561   return result;
562 }
563 
564 LegalizerInfo::SizeAndAction
565 LegalizerInfo::findAction(const SizeAndActionsVec &Vec, const uint32_t Size) {
566   assert(Size >= 1);
567   // Find the last element in Vec that has a bitsize equal to or smaller than
568   // the requested bit size.
569   // That is the element just before the first element that is bigger than Size.
570   auto It = partition_point(
571       Vec, [=](const SizeAndAction &A) { return A.first <= Size; });
572   assert(It != Vec.begin() && "Does Vec not start with size 1?");
573   int VecIdx = It - Vec.begin() - 1;
574 
575   LegalizeAction Action = Vec[VecIdx].second;
576   switch (Action) {
577   case Legal:
578   case Bitcast:
579   case Lower:
580   case Libcall:
581   case Custom:
582     return {Size, Action};
583   case FewerElements:
584     // FIXME: is this special case still needed and correct?
585     // Special case for scalarization:
586     if (Vec == SizeAndActionsVec({{1, FewerElements}}))
587       return {1, FewerElements};
588     LLVM_FALLTHROUGH;
589   case NarrowScalar: {
590     // The following needs to be a loop, as for now, we do allow needing to
591     // go over "Unsupported" bit sizes before finding a legalizable bit size.
592     // e.g. (s8, WidenScalar), (s9, Unsupported), (s32, Legal). if Size==8,
593     // we need to iterate over s9, and then to s32 to return (s32, Legal).
594     // If we want to get rid of the below loop, we should have stronger asserts
595     // when building the SizeAndActionsVecs, probably not allowing
596     // "Unsupported" unless at the ends of the vector.
597     for (int i = VecIdx - 1; i >= 0; --i)
598       if (!needsLegalizingToDifferentSize(Vec[i].second) &&
599           Vec[i].second != Unsupported)
600         return {Vec[i].first, Action};
601     llvm_unreachable("");
602   }
603   case WidenScalar:
604   case MoreElements: {
605     // See above, the following needs to be a loop, at least for now.
606     for (std::size_t i = VecIdx + 1; i < Vec.size(); ++i)
607       if (!needsLegalizingToDifferentSize(Vec[i].second) &&
608           Vec[i].second != Unsupported)
609         return {Vec[i].first, Action};
610     llvm_unreachable("");
611   }
612   case Unsupported:
613     return {Size, Unsupported};
614   case NotFound:
615   case UseLegacyRules:
616     llvm_unreachable("NotFound");
617   }
618   llvm_unreachable("Action has an unknown enum value");
619 }
620 
621 std::pair<LegalizeAction, LLT>
622 LegalizerInfo::findScalarLegalAction(const InstrAspect &Aspect) const {
623   assert(Aspect.Type.isScalar() || Aspect.Type.isPointer());
624   if (Aspect.Opcode < FirstOp || Aspect.Opcode > LastOp)
625     return {NotFound, LLT()};
626   const unsigned OpcodeIdx = getOpcodeIdxForOpcode(Aspect.Opcode);
627   if (Aspect.Type.isPointer() &&
628       AddrSpace2PointerActions[OpcodeIdx].find(Aspect.Type.getAddressSpace()) ==
629           AddrSpace2PointerActions[OpcodeIdx].end()) {
630     return {NotFound, LLT()};
631   }
632   const SmallVector<SizeAndActionsVec, 1> &Actions =
633       Aspect.Type.isPointer()
634           ? AddrSpace2PointerActions[OpcodeIdx]
635                 .find(Aspect.Type.getAddressSpace())
636                 ->second
637           : ScalarActions[OpcodeIdx];
638   if (Aspect.Idx >= Actions.size())
639     return {NotFound, LLT()};
640   const SizeAndActionsVec &Vec = Actions[Aspect.Idx];
641   // FIXME: speed up this search, e.g. by using a results cache for repeated
642   // queries?
643   auto SizeAndAction = findAction(Vec, Aspect.Type.getSizeInBits());
644   return {SizeAndAction.second,
645           Aspect.Type.isScalar() ? LLT::scalar(SizeAndAction.first)
646                                  : LLT::pointer(Aspect.Type.getAddressSpace(),
647                                                 SizeAndAction.first)};
648 }
649 
650 std::pair<LegalizeAction, LLT>
651 LegalizerInfo::findVectorLegalAction(const InstrAspect &Aspect) const {
652   assert(Aspect.Type.isVector());
653   // First legalize the vector element size, then legalize the number of
654   // lanes in the vector.
655   if (Aspect.Opcode < FirstOp || Aspect.Opcode > LastOp)
656     return {NotFound, Aspect.Type};
657   const unsigned OpcodeIdx = getOpcodeIdxForOpcode(Aspect.Opcode);
658   const unsigned TypeIdx = Aspect.Idx;
659   if (TypeIdx >= ScalarInVectorActions[OpcodeIdx].size())
660     return {NotFound, Aspect.Type};
661   const SizeAndActionsVec &ElemSizeVec =
662       ScalarInVectorActions[OpcodeIdx][TypeIdx];
663 
664   LLT IntermediateType;
665   auto ElementSizeAndAction =
666       findAction(ElemSizeVec, Aspect.Type.getScalarSizeInBits());
667   IntermediateType =
668       LLT::vector(Aspect.Type.getNumElements(), ElementSizeAndAction.first);
669   if (ElementSizeAndAction.second != Legal)
670     return {ElementSizeAndAction.second, IntermediateType};
671 
672   auto i = NumElements2Actions[OpcodeIdx].find(
673       IntermediateType.getScalarSizeInBits());
674   if (i == NumElements2Actions[OpcodeIdx].end()) {
675     return {NotFound, IntermediateType};
676   }
677   const SizeAndActionsVec &NumElementsVec = (*i).second[TypeIdx];
678   auto NumElementsAndAction =
679       findAction(NumElementsVec, IntermediateType.getNumElements());
680   return {NumElementsAndAction.second,
681           LLT::vector(NumElementsAndAction.first,
682                       IntermediateType.getScalarSizeInBits())};
683 }
684 
685 unsigned LegalizerInfo::getExtOpcodeForWideningConstant(LLT SmallTy) const {
686   return SmallTy.isByteSized() ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
687 }
688 
689 /// \pre Type indices of every opcode form a dense set starting from 0.
690 void LegalizerInfo::verify(const MCInstrInfo &MII) const {
691 #ifndef NDEBUG
692   std::vector<unsigned> FailedOpcodes;
693   for (unsigned Opcode = FirstOp; Opcode <= LastOp; ++Opcode) {
694     const MCInstrDesc &MCID = MII.get(Opcode);
695     const unsigned NumTypeIdxs = std::accumulate(
696         MCID.opInfo_begin(), MCID.opInfo_end(), 0U,
697         [](unsigned Acc, const MCOperandInfo &OpInfo) {
698           return OpInfo.isGenericType()
699                      ? std::max(OpInfo.getGenericTypeIndex() + 1U, Acc)
700                      : Acc;
701         });
702     const unsigned NumImmIdxs = std::accumulate(
703         MCID.opInfo_begin(), MCID.opInfo_end(), 0U,
704         [](unsigned Acc, const MCOperandInfo &OpInfo) {
705           return OpInfo.isGenericImm()
706                      ? std::max(OpInfo.getGenericImmIndex() + 1U, Acc)
707                      : Acc;
708         });
709     LLVM_DEBUG(dbgs() << MII.getName(Opcode) << " (opcode " << Opcode
710                       << "): " << NumTypeIdxs << " type ind"
711                       << (NumTypeIdxs == 1 ? "ex" : "ices") << ", "
712                       << NumImmIdxs << " imm ind"
713                       << (NumImmIdxs == 1 ? "ex" : "ices") << "\n");
714     const LegalizeRuleSet &RuleSet = getActionDefinitions(Opcode);
715     if (!RuleSet.verifyTypeIdxsCoverage(NumTypeIdxs))
716       FailedOpcodes.push_back(Opcode);
717     else if (!RuleSet.verifyImmIdxsCoverage(NumImmIdxs))
718       FailedOpcodes.push_back(Opcode);
719   }
720   if (!FailedOpcodes.empty()) {
721     errs() << "The following opcodes have ill-defined legalization rules:";
722     for (unsigned Opcode : FailedOpcodes)
723       errs() << " " << MII.getName(Opcode);
724     errs() << "\n";
725 
726     report_fatal_error("ill-defined LegalizerInfo"
727                        ", try -debug-only=legalizer-info for details");
728   }
729 #endif
730 }
731 
732 #ifndef NDEBUG
733 // FIXME: This should be in the MachineVerifier, but it can't use the
734 // LegalizerInfo as it's currently in the separate GlobalISel library.
735 // Note that RegBankSelected property already checked in the verifier
736 // has the same layering problem, but we only use inline methods so
737 // end up not needing to link against the GlobalISel library.
738 const MachineInstr *llvm::machineFunctionIsIllegal(const MachineFunction &MF) {
739   if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo()) {
740     const MachineRegisterInfo &MRI = MF.getRegInfo();
741     for (const MachineBasicBlock &MBB : MF)
742       for (const MachineInstr &MI : MBB)
743         if (isPreISelGenericOpcode(MI.getOpcode()) &&
744             !MLI->isLegalOrCustom(MI, MRI))
745           return &MI;
746   }
747   return nullptr;
748 }
749 #endif
750