1 //===- LegalizeVectorOps.cpp - Implement SelectionDAG::LegalizeVectors ----===//
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 SelectionDAG::LegalizeVectors method.
10 //
11 // The vector legalizer looks for vector operations which might need to be
12 // scalarized and legalizes them. This is a separate step from Legalize because
13 // scalarizing can introduce illegal types.  For example, suppose we have an
14 // ISD::SDIV of type v2i64 on x86-32.  The type is legal (for example, addition
15 // on a v2i64 is legal), but ISD::SDIV isn't legal, so we have to unroll the
16 // operation, which introduces nodes with the illegal type i64 which must be
17 // expanded.  Similarly, suppose we have an ISD::SRA of type v16i8 on PowerPC;
18 // the operation must be unrolled, which introduces nodes with the illegal
19 // type i8 which must be promoted.
20 //
21 // This does not legalize vector manipulations like ISD::BUILD_VECTOR,
22 // or operations that happen to take a vector which are custom-lowered;
23 // the legalization for such operations never produces nodes
24 // with illegal types, so it's okay to put off legalizing them until
25 // SelectionDAG::Legalize runs.
26 //
27 //===----------------------------------------------------------------------===//
28 
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/CodeGen/SelectionDAGNodes.h"
36 #include "llvm/CodeGen/TargetLowering.h"
37 #include "llvm/CodeGen/ValueTypes.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/MachineValueType.h"
44 #include "llvm/Support/MathExtras.h"
45 #include <cassert>
46 #include <cstdint>
47 #include <iterator>
48 #include <utility>
49 
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "legalizevectorops"
53 
54 namespace {
55 
56 class VectorLegalizer {
57   SelectionDAG& DAG;
58   const TargetLowering &TLI;
59   bool Changed = false; // Keep track of whether anything changed
60 
61   /// For nodes that are of legal width, and that have more than one use, this
62   /// map indicates what regularized operand to use.  This allows us to avoid
63   /// legalizing the same thing more than once.
64   SmallDenseMap<SDValue, SDValue, 64> LegalizedNodes;
65 
66   /// Adds a node to the translation cache.
67   void AddLegalizedOperand(SDValue From, SDValue To) {
68     LegalizedNodes.insert(std::make_pair(From, To));
69     // If someone requests legalization of the new node, return itself.
70     if (From != To)
71       LegalizedNodes.insert(std::make_pair(To, To));
72   }
73 
74   /// Legalizes the given node.
75   SDValue LegalizeOp(SDValue Op);
76 
77   /// Assuming the node is legal, "legalize" the results.
78   SDValue TranslateLegalizeResults(SDValue Op, SDValue Result);
79 
80   /// Implements unrolling a VSETCC.
81   SDValue UnrollVSETCC(SDValue Op);
82 
83   /// Implement expand-based legalization of vector operations.
84   ///
85   /// This is just a high-level routine to dispatch to specific code paths for
86   /// operations to legalize them.
87   SDValue Expand(SDValue Op);
88 
89   /// Implements expansion for FP_TO_UINT; falls back to UnrollVectorOp if
90   /// FP_TO_SINT isn't legal.
91   SDValue ExpandFP_TO_UINT(SDValue Op);
92 
93   /// Implements expansion for UINT_TO_FLOAT; falls back to UnrollVectorOp if
94   /// SINT_TO_FLOAT and SHR on vectors isn't legal.
95   SDValue ExpandUINT_TO_FLOAT(SDValue Op);
96 
97   /// Implement expansion for SIGN_EXTEND_INREG using SRL and SRA.
98   SDValue ExpandSEXTINREG(SDValue Op);
99 
100   /// Implement expansion for ANY_EXTEND_VECTOR_INREG.
101   ///
102   /// Shuffles the low lanes of the operand into place and bitcasts to the proper
103   /// type. The contents of the bits in the extended part of each element are
104   /// undef.
105   SDValue ExpandANY_EXTEND_VECTOR_INREG(SDValue Op);
106 
107   /// Implement expansion for SIGN_EXTEND_VECTOR_INREG.
108   ///
109   /// Shuffles the low lanes of the operand into place, bitcasts to the proper
110   /// type, then shifts left and arithmetic shifts right to introduce a sign
111   /// extension.
112   SDValue ExpandSIGN_EXTEND_VECTOR_INREG(SDValue Op);
113 
114   /// Implement expansion for ZERO_EXTEND_VECTOR_INREG.
115   ///
116   /// Shuffles the low lanes of the operand into place and blends zeros into
117   /// the remaining lanes, finally bitcasting to the proper type.
118   SDValue ExpandZERO_EXTEND_VECTOR_INREG(SDValue Op);
119 
120   /// Implement expand-based legalization of ABS vector operations.
121   /// If following expanding is legal/custom then do it:
122   /// (ABS x) --> (XOR (ADD x, (SRA x, sizeof(x)-1)), (SRA x, sizeof(x)-1))
123   /// else unroll the operation.
124   SDValue ExpandABS(SDValue Op);
125 
126   /// Expand bswap of vectors into a shuffle if legal.
127   SDValue ExpandBSWAP(SDValue Op);
128 
129   /// Implement vselect in terms of XOR, AND, OR when blend is not
130   /// supported by the target.
131   SDValue ExpandVSELECT(SDValue Op);
132   SDValue ExpandSELECT(SDValue Op);
133   SDValue ExpandLoad(SDValue Op);
134   SDValue ExpandStore(SDValue Op);
135   SDValue ExpandFNEG(SDValue Op);
136   SDValue ExpandFSUB(SDValue Op);
137   SDValue ExpandBITREVERSE(SDValue Op);
138   SDValue ExpandCTPOP(SDValue Op);
139   SDValue ExpandCTLZ(SDValue Op);
140   SDValue ExpandCTTZ(SDValue Op);
141   SDValue ExpandFunnelShift(SDValue Op);
142   SDValue ExpandROT(SDValue Op);
143   SDValue ExpandFMINNUM_FMAXNUM(SDValue Op);
144   SDValue ExpandUADDSUBO(SDValue Op);
145   SDValue ExpandSADDSUBO(SDValue Op);
146   SDValue ExpandMULO(SDValue Op);
147   SDValue ExpandAddSubSat(SDValue Op);
148   SDValue ExpandFixedPointMul(SDValue Op);
149   SDValue ExpandStrictFPOp(SDValue Op);
150 
151   /// Implements vector promotion.
152   ///
153   /// This is essentially just bitcasting the operands to a different type and
154   /// bitcasting the result back to the original type.
155   SDValue Promote(SDValue Op);
156 
157   /// Implements [SU]INT_TO_FP vector promotion.
158   ///
159   /// This is a [zs]ext of the input operand to a larger integer type.
160   SDValue PromoteINT_TO_FP(SDValue Op);
161 
162   /// Implements FP_TO_[SU]INT vector promotion of the result type.
163   ///
164   /// It is promoted to a larger integer type.  The result is then
165   /// truncated back to the original type.
166   SDValue PromoteFP_TO_INT(SDValue Op);
167 
168 public:
169   VectorLegalizer(SelectionDAG& dag) :
170       DAG(dag), TLI(dag.getTargetLoweringInfo()) {}
171 
172   /// Begin legalizer the vector operations in the DAG.
173   bool Run();
174 };
175 
176 } // end anonymous namespace
177 
178 bool VectorLegalizer::Run() {
179   // Before we start legalizing vector nodes, check if there are any vectors.
180   bool HasVectors = false;
181   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
182        E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I) {
183     // Check if the values of the nodes contain vectors. We don't need to check
184     // the operands because we are going to check their values at some point.
185     for (SDNode::value_iterator J = I->value_begin(), E = I->value_end();
186          J != E; ++J)
187       HasVectors |= J->isVector();
188 
189     // If we found a vector node we can start the legalization.
190     if (HasVectors)
191       break;
192   }
193 
194   // If this basic block has no vectors then no need to legalize vectors.
195   if (!HasVectors)
196     return false;
197 
198   // The legalize process is inherently a bottom-up recursive process (users
199   // legalize their uses before themselves).  Given infinite stack space, we
200   // could just start legalizing on the root and traverse the whole graph.  In
201   // practice however, this causes us to run out of stack space on large basic
202   // blocks.  To avoid this problem, compute an ordering of the nodes where each
203   // node is only legalized after all of its operands are legalized.
204   DAG.AssignTopologicalOrder();
205   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
206        E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I)
207     LegalizeOp(SDValue(&*I, 0));
208 
209   // Finally, it's possible the root changed.  Get the new root.
210   SDValue OldRoot = DAG.getRoot();
211   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
212   DAG.setRoot(LegalizedNodes[OldRoot]);
213 
214   LegalizedNodes.clear();
215 
216   // Remove dead nodes now.
217   DAG.RemoveDeadNodes();
218 
219   return Changed;
220 }
221 
222 SDValue VectorLegalizer::TranslateLegalizeResults(SDValue Op, SDValue Result) {
223   // Generic legalization: just pass the operand through.
224   for (unsigned i = 0, e = Op.getNode()->getNumValues(); i != e; ++i)
225     AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
226   return Result.getValue(Op.getResNo());
227 }
228 
229 SDValue VectorLegalizer::LegalizeOp(SDValue Op) {
230   // Note that LegalizeOp may be reentered even from single-use nodes, which
231   // means that we always must cache transformed nodes.
232   DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
233   if (I != LegalizedNodes.end()) return I->second;
234 
235   SDNode* Node = Op.getNode();
236 
237   // Legalize the operands
238   SmallVector<SDValue, 8> Ops;
239   for (const SDValue &Op : Node->op_values())
240     Ops.push_back(LegalizeOp(Op));
241 
242   SDValue Result = SDValue(DAG.UpdateNodeOperands(Op.getNode(), Ops),
243                            Op.getResNo());
244 
245   if (Op.getOpcode() == ISD::LOAD) {
246     LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
247     ISD::LoadExtType ExtType = LD->getExtensionType();
248     if (LD->getMemoryVT().isVector() && ExtType != ISD::NON_EXTLOAD) {
249       LLVM_DEBUG(dbgs() << "\nLegalizing extending vector load: ";
250                  Node->dump(&DAG));
251       switch (TLI.getLoadExtAction(LD->getExtensionType(), LD->getValueType(0),
252                                    LD->getMemoryVT())) {
253       default: llvm_unreachable("This action is not supported yet!");
254       case TargetLowering::Legal:
255         return TranslateLegalizeResults(Op, Result);
256       case TargetLowering::Custom:
257         if (SDValue Lowered = TLI.LowerOperation(Result, DAG)) {
258           assert(Lowered->getNumValues() == Op->getNumValues() &&
259                  "Unexpected number of results");
260           if (Lowered != Result) {
261             // Make sure the new code is also legal.
262             Lowered = LegalizeOp(Lowered);
263             Changed = true;
264           }
265           return TranslateLegalizeResults(Op, Lowered);
266         }
267         LLVM_FALLTHROUGH;
268       case TargetLowering::Expand:
269         Changed = true;
270         return ExpandLoad(Op);
271       }
272     }
273   } else if (Op.getOpcode() == ISD::STORE) {
274     StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
275     EVT StVT = ST->getMemoryVT();
276     MVT ValVT = ST->getValue().getSimpleValueType();
277     if (StVT.isVector() && ST->isTruncatingStore()) {
278       LLVM_DEBUG(dbgs() << "\nLegalizing truncating vector store: ";
279                  Node->dump(&DAG));
280       switch (TLI.getTruncStoreAction(ValVT, StVT)) {
281       default: llvm_unreachable("This action is not supported yet!");
282       case TargetLowering::Legal:
283         return TranslateLegalizeResults(Op, Result);
284       case TargetLowering::Custom: {
285         SDValue Lowered = TLI.LowerOperation(Result, DAG);
286         if (Lowered != Result) {
287           // Make sure the new code is also legal.
288           Lowered = LegalizeOp(Lowered);
289           Changed = true;
290         }
291         return TranslateLegalizeResults(Op, Lowered);
292       }
293       case TargetLowering::Expand:
294         Changed = true;
295         return ExpandStore(Op);
296       }
297     }
298   }
299 
300   bool HasVectorValueOrOp = false;
301   for (auto J = Node->value_begin(), E = Node->value_end(); J != E; ++J)
302     HasVectorValueOrOp |= J->isVector();
303   for (const SDValue &Op : Node->op_values())
304     HasVectorValueOrOp |= Op.getValueType().isVector();
305 
306   if (!HasVectorValueOrOp)
307     return TranslateLegalizeResults(Op, Result);
308 
309   TargetLowering::LegalizeAction Action = TargetLowering::Legal;
310   EVT ValVT;
311   switch (Op.getOpcode()) {
312   default:
313     return TranslateLegalizeResults(Op, Result);
314 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
315   case ISD::STRICT_##DAGN:
316 #include "llvm/IR/ConstrainedOps.def"
317     ValVT = Node->getValueType(0);
318     if (Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
319         Op.getOpcode() == ISD::STRICT_UINT_TO_FP)
320       ValVT = Node->getOperand(1).getValueType();
321     Action = TLI.getOperationAction(Node->getOpcode(), ValVT);
322     // If we're asked to expand a strict vector floating-point operation,
323     // by default we're going to simply unroll it.  That is usually the
324     // best approach, except in the case where the resulting strict (scalar)
325     // operations would themselves use the fallback mutation to non-strict.
326     // In that specific case, just do the fallback on the vector op.
327     if (Action == TargetLowering::Expand && !TLI.isStrictFPEnabled() &&
328         TLI.getStrictFPOperationAction(Node->getOpcode(), ValVT) ==
329             TargetLowering::Legal) {
330       EVT EltVT = ValVT.getVectorElementType();
331       if (TLI.getOperationAction(Node->getOpcode(), EltVT)
332           == TargetLowering::Expand &&
333           TLI.getStrictFPOperationAction(Node->getOpcode(), EltVT)
334           == TargetLowering::Legal)
335         Action = TargetLowering::Legal;
336     }
337     break;
338   case ISD::ADD:
339   case ISD::SUB:
340   case ISD::MUL:
341   case ISD::MULHS:
342   case ISD::MULHU:
343   case ISD::SDIV:
344   case ISD::UDIV:
345   case ISD::SREM:
346   case ISD::UREM:
347   case ISD::SDIVREM:
348   case ISD::UDIVREM:
349   case ISD::FADD:
350   case ISD::FSUB:
351   case ISD::FMUL:
352   case ISD::FDIV:
353   case ISD::FREM:
354   case ISD::AND:
355   case ISD::OR:
356   case ISD::XOR:
357   case ISD::SHL:
358   case ISD::SRA:
359   case ISD::SRL:
360   case ISD::FSHL:
361   case ISD::FSHR:
362   case ISD::ROTL:
363   case ISD::ROTR:
364   case ISD::ABS:
365   case ISD::BSWAP:
366   case ISD::BITREVERSE:
367   case ISD::CTLZ:
368   case ISD::CTTZ:
369   case ISD::CTLZ_ZERO_UNDEF:
370   case ISD::CTTZ_ZERO_UNDEF:
371   case ISD::CTPOP:
372   case ISD::SELECT:
373   case ISD::VSELECT:
374   case ISD::SELECT_CC:
375   case ISD::SETCC:
376   case ISD::ZERO_EXTEND:
377   case ISD::ANY_EXTEND:
378   case ISD::TRUNCATE:
379   case ISD::SIGN_EXTEND:
380   case ISD::FP_TO_SINT:
381   case ISD::FP_TO_UINT:
382   case ISD::FNEG:
383   case ISD::FABS:
384   case ISD::FMINNUM:
385   case ISD::FMAXNUM:
386   case ISD::FMINNUM_IEEE:
387   case ISD::FMAXNUM_IEEE:
388   case ISD::FMINIMUM:
389   case ISD::FMAXIMUM:
390   case ISD::FCOPYSIGN:
391   case ISD::FSQRT:
392   case ISD::FSIN:
393   case ISD::FCOS:
394   case ISD::FPOWI:
395   case ISD::FPOW:
396   case ISD::FLOG:
397   case ISD::FLOG2:
398   case ISD::FLOG10:
399   case ISD::FEXP:
400   case ISD::FEXP2:
401   case ISD::FCEIL:
402   case ISD::FTRUNC:
403   case ISD::FRINT:
404   case ISD::FNEARBYINT:
405   case ISD::FROUND:
406   case ISD::FFLOOR:
407   case ISD::FP_ROUND:
408   case ISD::FP_EXTEND:
409   case ISD::FMA:
410   case ISD::SIGN_EXTEND_INREG:
411   case ISD::ANY_EXTEND_VECTOR_INREG:
412   case ISD::SIGN_EXTEND_VECTOR_INREG:
413   case ISD::ZERO_EXTEND_VECTOR_INREG:
414   case ISD::SMIN:
415   case ISD::SMAX:
416   case ISD::UMIN:
417   case ISD::UMAX:
418   case ISD::SMUL_LOHI:
419   case ISD::UMUL_LOHI:
420   case ISD::SADDO:
421   case ISD::UADDO:
422   case ISD::SSUBO:
423   case ISD::USUBO:
424   case ISD::SMULO:
425   case ISD::UMULO:
426   case ISD::FCANONICALIZE:
427   case ISD::SADDSAT:
428   case ISD::UADDSAT:
429   case ISD::SSUBSAT:
430   case ISD::USUBSAT:
431     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
432     break;
433   case ISD::SMULFIX:
434   case ISD::SMULFIXSAT:
435   case ISD::UMULFIX:
436   case ISD::UMULFIXSAT: {
437     unsigned Scale = Node->getConstantOperandVal(2);
438     Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
439                                               Node->getValueType(0), Scale);
440     break;
441   }
442   case ISD::SINT_TO_FP:
443   case ISD::UINT_TO_FP:
444   case ISD::VECREDUCE_ADD:
445   case ISD::VECREDUCE_MUL:
446   case ISD::VECREDUCE_AND:
447   case ISD::VECREDUCE_OR:
448   case ISD::VECREDUCE_XOR:
449   case ISD::VECREDUCE_SMAX:
450   case ISD::VECREDUCE_SMIN:
451   case ISD::VECREDUCE_UMAX:
452   case ISD::VECREDUCE_UMIN:
453   case ISD::VECREDUCE_FADD:
454   case ISD::VECREDUCE_FMUL:
455   case ISD::VECREDUCE_FMAX:
456   case ISD::VECREDUCE_FMIN:
457     Action = TLI.getOperationAction(Node->getOpcode(),
458                                     Node->getOperand(0).getValueType());
459     break;
460   }
461 
462   LLVM_DEBUG(dbgs() << "\nLegalizing vector op: "; Node->dump(&DAG));
463 
464   switch (Action) {
465   default: llvm_unreachable("This action is not supported yet!");
466   case TargetLowering::Promote:
467     Result = Promote(Op);
468     Changed = true;
469     break;
470   case TargetLowering::Legal:
471     LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
472     break;
473   case TargetLowering::Custom: {
474     LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
475     if (SDValue Tmp1 = TLI.LowerOperation(Op, DAG)) {
476       LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
477       Result = Tmp1;
478       break;
479     }
480     LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
481     LLVM_FALLTHROUGH;
482   }
483   case TargetLowering::Expand:
484     Result = Expand(Op);
485   }
486 
487   // Make sure that the generated code is itself legal.
488   if (Result != Op) {
489     Result = LegalizeOp(Result);
490     Changed = true;
491   }
492 
493   // Note that LegalizeOp may be reentered even from single-use nodes, which
494   // means that we always must cache transformed nodes.
495   AddLegalizedOperand(Op, Result);
496   return Result;
497 }
498 
499 SDValue VectorLegalizer::Promote(SDValue Op) {
500   // For a few operations there is a specific concept for promotion based on
501   // the operand's type.
502   switch (Op.getOpcode()) {
503   case ISD::SINT_TO_FP:
504   case ISD::UINT_TO_FP:
505   case ISD::STRICT_SINT_TO_FP:
506   case ISD::STRICT_UINT_TO_FP:
507     // "Promote" the operation by extending the operand.
508     return PromoteINT_TO_FP(Op);
509   case ISD::FP_TO_UINT:
510   case ISD::FP_TO_SINT:
511   case ISD::STRICT_FP_TO_UINT:
512   case ISD::STRICT_FP_TO_SINT:
513     // Promote the operation by extending the operand.
514     return PromoteFP_TO_INT(Op);
515   case ISD::FP_ROUND:
516   case ISD::FP_EXTEND:
517     // These operations are used to do promotion so they can't be promoted
518     // themselves.
519     llvm_unreachable("Don't know how to promote this operation!");
520   }
521 
522   // There are currently two cases of vector promotion:
523   // 1) Bitcasting a vector of integers to a different type to a vector of the
524   //    same overall length. For example, x86 promotes ISD::AND v2i32 to v1i64.
525   // 2) Extending a vector of floats to a vector of the same number of larger
526   //    floats. For example, AArch64 promotes ISD::FADD on v4f16 to v4f32.
527   MVT VT = Op.getSimpleValueType();
528   assert(Op.getNode()->getNumValues() == 1 &&
529          "Can't promote a vector with multiple results!");
530   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
531   SDLoc dl(Op);
532   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
533 
534   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
535     if (Op.getOperand(j).getValueType().isVector())
536       if (Op.getOperand(j)
537               .getValueType()
538               .getVectorElementType()
539               .isFloatingPoint() &&
540           NVT.isVector() && NVT.getVectorElementType().isFloatingPoint())
541         Operands[j] = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Op.getOperand(j));
542       else
543         Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Op.getOperand(j));
544     else
545       Operands[j] = Op.getOperand(j);
546   }
547 
548   Op = DAG.getNode(Op.getOpcode(), dl, NVT, Operands, Op.getNode()->getFlags());
549   if ((VT.isFloatingPoint() && NVT.isFloatingPoint()) ||
550       (VT.isVector() && VT.getVectorElementType().isFloatingPoint() &&
551        NVT.isVector() && NVT.getVectorElementType().isFloatingPoint()))
552     return DAG.getNode(ISD::FP_ROUND, dl, VT, Op, DAG.getIntPtrConstant(0, dl));
553   else
554     return DAG.getNode(ISD::BITCAST, dl, VT, Op);
555 }
556 
557 SDValue VectorLegalizer::PromoteINT_TO_FP(SDValue Op) {
558   // INT_TO_FP operations may require the input operand be promoted even
559   // when the type is otherwise legal.
560   bool IsStrict = Op->isStrictFPOpcode();
561   MVT VT = Op.getOperand(IsStrict ? 1 : 0).getSimpleValueType();
562   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
563   assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
564          "Vectors have different number of elements!");
565 
566   SDLoc dl(Op);
567   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
568 
569   unsigned Opc = (Op.getOpcode() == ISD::UINT_TO_FP ||
570                   Op.getOpcode() == ISD::STRICT_UINT_TO_FP)
571                      ? ISD::ZERO_EXTEND
572                      : ISD::SIGN_EXTEND;
573   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
574     if (Op.getOperand(j).getValueType().isVector())
575       Operands[j] = DAG.getNode(Opc, dl, NVT, Op.getOperand(j));
576     else
577       Operands[j] = Op.getOperand(j);
578   }
579 
580   if (IsStrict)
581     return DAG.getNode(Op.getOpcode(), dl, {Op.getValueType(), MVT::Other},
582                        Operands);
583 
584   return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Operands);
585 }
586 
587 // For FP_TO_INT we promote the result type to a vector type with wider
588 // elements and then truncate the result.  This is different from the default
589 // PromoteVector which uses bitcast to promote thus assumning that the
590 // promoted vector type has the same overall size.
591 SDValue VectorLegalizer::PromoteFP_TO_INT(SDValue Op) {
592   MVT VT = Op.getSimpleValueType();
593   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
594   bool IsStrict = Op->isStrictFPOpcode();
595   assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
596          "Vectors have different number of elements!");
597 
598   unsigned NewOpc = Op->getOpcode();
599   // Change FP_TO_UINT to FP_TO_SINT if possible.
600   // TODO: Should we only do this if FP_TO_UINT itself isn't legal?
601   if (NewOpc == ISD::FP_TO_UINT &&
602       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
603     NewOpc = ISD::FP_TO_SINT;
604 
605   if (NewOpc == ISD::STRICT_FP_TO_UINT &&
606       TLI.isOperationLegalOrCustom(ISD::STRICT_FP_TO_SINT, NVT))
607     NewOpc = ISD::STRICT_FP_TO_SINT;
608 
609   SDLoc dl(Op);
610   SDValue Promoted, Chain;
611   if (IsStrict) {
612     Promoted = DAG.getNode(NewOpc, dl, {NVT, MVT::Other},
613                            {Op.getOperand(0), Op.getOperand(1)});
614     Chain = Promoted.getValue(1);
615   } else
616     Promoted = DAG.getNode(NewOpc, dl, NVT, Op.getOperand(0));
617 
618   // Assert that the converted value fits in the original type.  If it doesn't
619   // (eg: because the value being converted is too big), then the result of the
620   // original operation was undefined anyway, so the assert is still correct.
621   if (Op->getOpcode() == ISD::FP_TO_UINT ||
622       Op->getOpcode() == ISD::STRICT_FP_TO_UINT)
623     NewOpc = ISD::AssertZext;
624   else
625     NewOpc = ISD::AssertSext;
626 
627   Promoted = DAG.getNode(NewOpc, dl, NVT, Promoted,
628                          DAG.getValueType(VT.getScalarType()));
629   Promoted = DAG.getNode(ISD::TRUNCATE, dl, VT, Promoted);
630   if (IsStrict)
631     return DAG.getMergeValues({Promoted, Chain}, dl);
632 
633   return Promoted;
634 }
635 
636 SDValue VectorLegalizer::ExpandLoad(SDValue Op) {
637   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
638 
639   EVT SrcVT = LD->getMemoryVT();
640   EVT SrcEltVT = SrcVT.getScalarType();
641   unsigned NumElem = SrcVT.getVectorNumElements();
642 
643   SDValue NewChain;
644   SDValue Value;
645   if (SrcVT.getVectorNumElements() > 1 && !SrcEltVT.isByteSized()) {
646     SDLoc dl(Op);
647 
648     SmallVector<SDValue, 8> Vals;
649     SmallVector<SDValue, 8> LoadChains;
650 
651     EVT DstEltVT = LD->getValueType(0).getScalarType();
652     SDValue Chain = LD->getChain();
653     SDValue BasePTR = LD->getBasePtr();
654     ISD::LoadExtType ExtType = LD->getExtensionType();
655 
656     // When elements in a vector is not byte-addressable, we cannot directly
657     // load each element by advancing pointer, which could only address bytes.
658     // Instead, we load all significant words, mask bits off, and concatenate
659     // them to form each element. Finally, they are extended to destination
660     // scalar type to build the destination vector.
661     EVT WideVT = TLI.getPointerTy(DAG.getDataLayout());
662 
663     assert(WideVT.isRound() &&
664            "Could not handle the sophisticated case when the widest integer is"
665            " not power of 2.");
666     assert(WideVT.bitsGE(SrcEltVT) &&
667            "Type is not legalized?");
668 
669     unsigned WideBytes = WideVT.getStoreSize();
670     unsigned Offset = 0;
671     unsigned RemainingBytes = SrcVT.getStoreSize();
672     SmallVector<SDValue, 8> LoadVals;
673     while (RemainingBytes > 0) {
674       SDValue ScalarLoad;
675       unsigned LoadBytes = WideBytes;
676 
677       if (RemainingBytes >= LoadBytes) {
678         ScalarLoad =
679             DAG.getLoad(WideVT, dl, Chain, BasePTR,
680                         LD->getPointerInfo().getWithOffset(Offset),
681                         MinAlign(LD->getAlignment(), Offset),
682                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
683       } else {
684         EVT LoadVT = WideVT;
685         while (RemainingBytes < LoadBytes) {
686           LoadBytes >>= 1; // Reduce the load size by half.
687           LoadVT = EVT::getIntegerVT(*DAG.getContext(), LoadBytes << 3);
688         }
689         ScalarLoad =
690             DAG.getExtLoad(ISD::EXTLOAD, dl, WideVT, Chain, BasePTR,
691                            LD->getPointerInfo().getWithOffset(Offset), LoadVT,
692                            MinAlign(LD->getAlignment(), Offset),
693                            LD->getMemOperand()->getFlags(), LD->getAAInfo());
694       }
695 
696       RemainingBytes -= LoadBytes;
697       Offset += LoadBytes;
698 
699       BasePTR = DAG.getObjectPtrOffset(dl, BasePTR, LoadBytes);
700 
701       LoadVals.push_back(ScalarLoad.getValue(0));
702       LoadChains.push_back(ScalarLoad.getValue(1));
703     }
704 
705     unsigned BitOffset = 0;
706     unsigned WideIdx = 0;
707     unsigned WideBits = WideVT.getSizeInBits();
708 
709     // Extract bits, pack and extend/trunc them into destination type.
710     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
711     SDValue SrcEltBitMask = DAG.getConstant(
712         APInt::getLowBitsSet(WideBits, SrcEltBits), dl, WideVT);
713 
714     for (unsigned Idx = 0; Idx != NumElem; ++Idx) {
715       assert(BitOffset < WideBits && "Unexpected offset!");
716 
717       SDValue ShAmt = DAG.getConstant(
718           BitOffset, dl, TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
719       SDValue Lo = DAG.getNode(ISD::SRL, dl, WideVT, LoadVals[WideIdx], ShAmt);
720 
721       BitOffset += SrcEltBits;
722       if (BitOffset >= WideBits) {
723         WideIdx++;
724         BitOffset -= WideBits;
725         if (BitOffset > 0) {
726           ShAmt = DAG.getConstant(
727               SrcEltBits - BitOffset, dl,
728               TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
729           SDValue Hi =
730               DAG.getNode(ISD::SHL, dl, WideVT, LoadVals[WideIdx], ShAmt);
731           Lo = DAG.getNode(ISD::OR, dl, WideVT, Lo, Hi);
732         }
733       }
734 
735       Lo = DAG.getNode(ISD::AND, dl, WideVT, Lo, SrcEltBitMask);
736 
737       switch (ExtType) {
738       default: llvm_unreachable("Unknown extended-load op!");
739       case ISD::EXTLOAD:
740         Lo = DAG.getAnyExtOrTrunc(Lo, dl, DstEltVT);
741         break;
742       case ISD::ZEXTLOAD:
743         Lo = DAG.getZExtOrTrunc(Lo, dl, DstEltVT);
744         break;
745       case ISD::SEXTLOAD:
746         ShAmt =
747             DAG.getConstant(WideBits - SrcEltBits, dl,
748                             TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
749         Lo = DAG.getNode(ISD::SHL, dl, WideVT, Lo, ShAmt);
750         Lo = DAG.getNode(ISD::SRA, dl, WideVT, Lo, ShAmt);
751         Lo = DAG.getSExtOrTrunc(Lo, dl, DstEltVT);
752         break;
753       }
754       Vals.push_back(Lo);
755     }
756 
757     NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
758     Value = DAG.getBuildVector(Op.getNode()->getValueType(0), dl, Vals);
759   } else {
760     std::tie(Value, NewChain) = TLI.scalarizeVectorLoad(LD, DAG);
761   }
762 
763   AddLegalizedOperand(Op.getValue(0), Value);
764   AddLegalizedOperand(Op.getValue(1), NewChain);
765 
766   return (Op.getResNo() ? NewChain : Value);
767 }
768 
769 SDValue VectorLegalizer::ExpandStore(SDValue Op) {
770   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
771   SDValue TF = TLI.scalarizeVectorStore(ST, DAG);
772   AddLegalizedOperand(Op, TF);
773   return TF;
774 }
775 
776 SDValue VectorLegalizer::Expand(SDValue Op) {
777   switch (Op->getOpcode()) {
778   case ISD::SIGN_EXTEND_INREG:
779     return ExpandSEXTINREG(Op);
780   case ISD::ANY_EXTEND_VECTOR_INREG:
781     return ExpandANY_EXTEND_VECTOR_INREG(Op);
782   case ISD::SIGN_EXTEND_VECTOR_INREG:
783     return ExpandSIGN_EXTEND_VECTOR_INREG(Op);
784   case ISD::ZERO_EXTEND_VECTOR_INREG:
785     return ExpandZERO_EXTEND_VECTOR_INREG(Op);
786   case ISD::BSWAP:
787     return ExpandBSWAP(Op);
788   case ISD::VSELECT:
789     return ExpandVSELECT(Op);
790   case ISD::SELECT:
791     return ExpandSELECT(Op);
792   case ISD::FP_TO_UINT:
793     return ExpandFP_TO_UINT(Op);
794   case ISD::UINT_TO_FP:
795     return ExpandUINT_TO_FLOAT(Op);
796   case ISD::FNEG:
797     return ExpandFNEG(Op);
798   case ISD::FSUB:
799     return ExpandFSUB(Op);
800   case ISD::SETCC:
801     return UnrollVSETCC(Op);
802   case ISD::ABS:
803     return ExpandABS(Op);
804   case ISD::BITREVERSE:
805     return ExpandBITREVERSE(Op);
806   case ISD::CTPOP:
807     return ExpandCTPOP(Op);
808   case ISD::CTLZ:
809   case ISD::CTLZ_ZERO_UNDEF:
810     return ExpandCTLZ(Op);
811   case ISD::CTTZ:
812   case ISD::CTTZ_ZERO_UNDEF:
813     return ExpandCTTZ(Op);
814   case ISD::FSHL:
815   case ISD::FSHR:
816     return ExpandFunnelShift(Op);
817   case ISD::ROTL:
818   case ISD::ROTR:
819     return ExpandROT(Op);
820   case ISD::FMINNUM:
821   case ISD::FMAXNUM:
822     return ExpandFMINNUM_FMAXNUM(Op);
823   case ISD::UADDO:
824   case ISD::USUBO:
825     return ExpandUADDSUBO(Op);
826   case ISD::SADDO:
827   case ISD::SSUBO:
828     return ExpandSADDSUBO(Op);
829   case ISD::UMULO:
830   case ISD::SMULO:
831     return ExpandMULO(Op);
832   case ISD::USUBSAT:
833   case ISD::SSUBSAT:
834   case ISD::UADDSAT:
835   case ISD::SADDSAT:
836     return ExpandAddSubSat(Op);
837   case ISD::SMULFIX:
838   case ISD::UMULFIX:
839     return ExpandFixedPointMul(Op);
840   case ISD::SMULFIXSAT:
841   case ISD::UMULFIXSAT:
842     // FIXME: We do not expand SMULFIXSAT/UMULFIXSAT here yet, not sure exactly
843     // why. Maybe it results in worse codegen compared to the unroll for some
844     // targets? This should probably be investigated. And if we still prefer to
845     // unroll an explanation could be helpful.
846     return DAG.UnrollVectorOp(Op.getNode());
847 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
848   case ISD::STRICT_##DAGN:
849 #include "llvm/IR/ConstrainedOps.def"
850     return ExpandStrictFPOp(Op);
851   case ISD::VECREDUCE_ADD:
852   case ISD::VECREDUCE_MUL:
853   case ISD::VECREDUCE_AND:
854   case ISD::VECREDUCE_OR:
855   case ISD::VECREDUCE_XOR:
856   case ISD::VECREDUCE_SMAX:
857   case ISD::VECREDUCE_SMIN:
858   case ISD::VECREDUCE_UMAX:
859   case ISD::VECREDUCE_UMIN:
860   case ISD::VECREDUCE_FADD:
861   case ISD::VECREDUCE_FMUL:
862   case ISD::VECREDUCE_FMAX:
863   case ISD::VECREDUCE_FMIN:
864     return TLI.expandVecReduce(Op.getNode(), DAG);
865   default:
866     return DAG.UnrollVectorOp(Op.getNode());
867   }
868 }
869 
870 SDValue VectorLegalizer::ExpandSELECT(SDValue Op) {
871   // Lower a select instruction where the condition is a scalar and the
872   // operands are vectors. Lower this select to VSELECT and implement it
873   // using XOR AND OR. The selector bit is broadcasted.
874   EVT VT = Op.getValueType();
875   SDLoc DL(Op);
876 
877   SDValue Mask = Op.getOperand(0);
878   SDValue Op1 = Op.getOperand(1);
879   SDValue Op2 = Op.getOperand(2);
880 
881   assert(VT.isVector() && !Mask.getValueType().isVector()
882          && Op1.getValueType() == Op2.getValueType() && "Invalid type");
883 
884   // If we can't even use the basic vector operations of
885   // AND,OR,XOR, we will have to scalarize the op.
886   // Notice that the operation may be 'promoted' which means that it is
887   // 'bitcasted' to another type which is handled.
888   // Also, we need to be able to construct a splat vector using BUILD_VECTOR.
889   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
890       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
891       TLI.getOperationAction(ISD::OR,  VT) == TargetLowering::Expand ||
892       TLI.getOperationAction(ISD::BUILD_VECTOR,  VT) == TargetLowering::Expand)
893     return DAG.UnrollVectorOp(Op.getNode());
894 
895   // Generate a mask operand.
896   EVT MaskTy = VT.changeVectorElementTypeToInteger();
897 
898   // What is the size of each element in the vector mask.
899   EVT BitTy = MaskTy.getScalarType();
900 
901   Mask = DAG.getSelect(DL, BitTy, Mask,
902           DAG.getConstant(APInt::getAllOnesValue(BitTy.getSizeInBits()), DL,
903                           BitTy),
904           DAG.getConstant(0, DL, BitTy));
905 
906   // Broadcast the mask so that the entire vector is all-one or all zero.
907   Mask = DAG.getSplatBuildVector(MaskTy, DL, Mask);
908 
909   // Bitcast the operands to be the same type as the mask.
910   // This is needed when we select between FP types because
911   // the mask is a vector of integers.
912   Op1 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op1);
913   Op2 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op2);
914 
915   SDValue AllOnes = DAG.getConstant(
916             APInt::getAllOnesValue(BitTy.getSizeInBits()), DL, MaskTy);
917   SDValue NotMask = DAG.getNode(ISD::XOR, DL, MaskTy, Mask, AllOnes);
918 
919   Op1 = DAG.getNode(ISD::AND, DL, MaskTy, Op1, Mask);
920   Op2 = DAG.getNode(ISD::AND, DL, MaskTy, Op2, NotMask);
921   SDValue Val = DAG.getNode(ISD::OR, DL, MaskTy, Op1, Op2);
922   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
923 }
924 
925 SDValue VectorLegalizer::ExpandSEXTINREG(SDValue Op) {
926   EVT VT = Op.getValueType();
927 
928   // Make sure that the SRA and SHL instructions are available.
929   if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Expand ||
930       TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Expand)
931     return DAG.UnrollVectorOp(Op.getNode());
932 
933   SDLoc DL(Op);
934   EVT OrigTy = cast<VTSDNode>(Op->getOperand(1))->getVT();
935 
936   unsigned BW = VT.getScalarSizeInBits();
937   unsigned OrigBW = OrigTy.getScalarSizeInBits();
938   SDValue ShiftSz = DAG.getConstant(BW - OrigBW, DL, VT);
939 
940   Op = Op.getOperand(0);
941   Op =   DAG.getNode(ISD::SHL, DL, VT, Op, ShiftSz);
942   return DAG.getNode(ISD::SRA, DL, VT, Op, ShiftSz);
943 }
944 
945 // Generically expand a vector anyext in register to a shuffle of the relevant
946 // lanes into the appropriate locations, with other lanes left undef.
947 SDValue VectorLegalizer::ExpandANY_EXTEND_VECTOR_INREG(SDValue Op) {
948   SDLoc DL(Op);
949   EVT VT = Op.getValueType();
950   int NumElements = VT.getVectorNumElements();
951   SDValue Src = Op.getOperand(0);
952   EVT SrcVT = Src.getValueType();
953   int NumSrcElements = SrcVT.getVectorNumElements();
954 
955   // *_EXTEND_VECTOR_INREG SrcVT can be smaller than VT - so insert the vector
956   // into a larger vector type.
957   if (SrcVT.bitsLE(VT)) {
958     assert((VT.getSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
959            "ANY_EXTEND_VECTOR_INREG vector size mismatch");
960     NumSrcElements = VT.getSizeInBits() / SrcVT.getScalarSizeInBits();
961     SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
962                              NumSrcElements);
963     Src = DAG.getNode(
964         ISD::INSERT_SUBVECTOR, DL, SrcVT, DAG.getUNDEF(SrcVT), Src,
965         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
966   }
967 
968   // Build a base mask of undef shuffles.
969   SmallVector<int, 16> ShuffleMask;
970   ShuffleMask.resize(NumSrcElements, -1);
971 
972   // Place the extended lanes into the correct locations.
973   int ExtLaneScale = NumSrcElements / NumElements;
974   int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
975   for (int i = 0; i < NumElements; ++i)
976     ShuffleMask[i * ExtLaneScale + EndianOffset] = i;
977 
978   return DAG.getNode(
979       ISD::BITCAST, DL, VT,
980       DAG.getVectorShuffle(SrcVT, DL, Src, DAG.getUNDEF(SrcVT), ShuffleMask));
981 }
982 
983 SDValue VectorLegalizer::ExpandSIGN_EXTEND_VECTOR_INREG(SDValue Op) {
984   SDLoc DL(Op);
985   EVT VT = Op.getValueType();
986   SDValue Src = Op.getOperand(0);
987   EVT SrcVT = Src.getValueType();
988 
989   // First build an any-extend node which can be legalized above when we
990   // recurse through it.
991   Op = DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Src);
992 
993   // Now we need sign extend. Do this by shifting the elements. Even if these
994   // aren't legal operations, they have a better chance of being legalized
995   // without full scalarization than the sign extension does.
996   unsigned EltWidth = VT.getScalarSizeInBits();
997   unsigned SrcEltWidth = SrcVT.getScalarSizeInBits();
998   SDValue ShiftAmount = DAG.getConstant(EltWidth - SrcEltWidth, DL, VT);
999   return DAG.getNode(ISD::SRA, DL, VT,
1000                      DAG.getNode(ISD::SHL, DL, VT, Op, ShiftAmount),
1001                      ShiftAmount);
1002 }
1003 
1004 // Generically expand a vector zext in register to a shuffle of the relevant
1005 // lanes into the appropriate locations, a blend of zero into the high bits,
1006 // and a bitcast to the wider element type.
1007 SDValue VectorLegalizer::ExpandZERO_EXTEND_VECTOR_INREG(SDValue Op) {
1008   SDLoc DL(Op);
1009   EVT VT = Op.getValueType();
1010   int NumElements = VT.getVectorNumElements();
1011   SDValue Src = Op.getOperand(0);
1012   EVT SrcVT = Src.getValueType();
1013   int NumSrcElements = SrcVT.getVectorNumElements();
1014 
1015   // *_EXTEND_VECTOR_INREG SrcVT can be smaller than VT - so insert the vector
1016   // into a larger vector type.
1017   if (SrcVT.bitsLE(VT)) {
1018     assert((VT.getSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
1019            "ZERO_EXTEND_VECTOR_INREG vector size mismatch");
1020     NumSrcElements = VT.getSizeInBits() / SrcVT.getScalarSizeInBits();
1021     SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
1022                              NumSrcElements);
1023     Src = DAG.getNode(
1024         ISD::INSERT_SUBVECTOR, DL, SrcVT, DAG.getUNDEF(SrcVT), Src,
1025         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
1026   }
1027 
1028   // Build up a zero vector to blend into this one.
1029   SDValue Zero = DAG.getConstant(0, DL, SrcVT);
1030 
1031   // Shuffle the incoming lanes into the correct position, and pull all other
1032   // lanes from the zero vector.
1033   SmallVector<int, 16> ShuffleMask;
1034   ShuffleMask.reserve(NumSrcElements);
1035   for (int i = 0; i < NumSrcElements; ++i)
1036     ShuffleMask.push_back(i);
1037 
1038   int ExtLaneScale = NumSrcElements / NumElements;
1039   int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
1040   for (int i = 0; i < NumElements; ++i)
1041     ShuffleMask[i * ExtLaneScale + EndianOffset] = NumSrcElements + i;
1042 
1043   return DAG.getNode(ISD::BITCAST, DL, VT,
1044                      DAG.getVectorShuffle(SrcVT, DL, Zero, Src, ShuffleMask));
1045 }
1046 
1047 static void createBSWAPShuffleMask(EVT VT, SmallVectorImpl<int> &ShuffleMask) {
1048   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
1049   for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I)
1050     for (int J = ScalarSizeInBytes - 1; J >= 0; --J)
1051       ShuffleMask.push_back((I * ScalarSizeInBytes) + J);
1052 }
1053 
1054 SDValue VectorLegalizer::ExpandBSWAP(SDValue Op) {
1055   EVT VT = Op.getValueType();
1056 
1057   // Generate a byte wise shuffle mask for the BSWAP.
1058   SmallVector<int, 16> ShuffleMask;
1059   createBSWAPShuffleMask(VT, ShuffleMask);
1060   EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, ShuffleMask.size());
1061 
1062   // Only emit a shuffle if the mask is legal.
1063   if (!TLI.isShuffleMaskLegal(ShuffleMask, ByteVT))
1064     return DAG.UnrollVectorOp(Op.getNode());
1065 
1066   SDLoc DL(Op);
1067   Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
1068   Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT), ShuffleMask);
1069   return DAG.getNode(ISD::BITCAST, DL, VT, Op);
1070 }
1071 
1072 SDValue VectorLegalizer::ExpandBITREVERSE(SDValue Op) {
1073   EVT VT = Op.getValueType();
1074 
1075   // If we have the scalar operation, it's probably cheaper to unroll it.
1076   if (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, VT.getScalarType()))
1077     return DAG.UnrollVectorOp(Op.getNode());
1078 
1079   // If the vector element width is a whole number of bytes, test if its legal
1080   // to BSWAP shuffle the bytes and then perform the BITREVERSE on the byte
1081   // vector. This greatly reduces the number of bit shifts necessary.
1082   unsigned ScalarSizeInBits = VT.getScalarSizeInBits();
1083   if (ScalarSizeInBits > 8 && (ScalarSizeInBits % 8) == 0) {
1084     SmallVector<int, 16> BSWAPMask;
1085     createBSWAPShuffleMask(VT, BSWAPMask);
1086 
1087     EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, BSWAPMask.size());
1088     if (TLI.isShuffleMaskLegal(BSWAPMask, ByteVT) &&
1089         (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, ByteVT) ||
1090          (TLI.isOperationLegalOrCustom(ISD::SHL, ByteVT) &&
1091           TLI.isOperationLegalOrCustom(ISD::SRL, ByteVT) &&
1092           TLI.isOperationLegalOrCustomOrPromote(ISD::AND, ByteVT) &&
1093           TLI.isOperationLegalOrCustomOrPromote(ISD::OR, ByteVT)))) {
1094       SDLoc DL(Op);
1095       Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
1096       Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT),
1097                                 BSWAPMask);
1098       Op = DAG.getNode(ISD::BITREVERSE, DL, ByteVT, Op);
1099       return DAG.getNode(ISD::BITCAST, DL, VT, Op);
1100     }
1101   }
1102 
1103   // If we have the appropriate vector bit operations, it is better to use them
1104   // than unrolling and expanding each component.
1105   if (!TLI.isOperationLegalOrCustom(ISD::SHL, VT) ||
1106       !TLI.isOperationLegalOrCustom(ISD::SRL, VT) ||
1107       !TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
1108       !TLI.isOperationLegalOrCustomOrPromote(ISD::OR, VT))
1109     return DAG.UnrollVectorOp(Op.getNode());
1110 
1111   // Let LegalizeDAG handle this later.
1112   return Op;
1113 }
1114 
1115 SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) {
1116   // Implement VSELECT in terms of XOR, AND, OR
1117   // on platforms which do not support blend natively.
1118   SDLoc DL(Op);
1119 
1120   SDValue Mask = Op.getOperand(0);
1121   SDValue Op1 = Op.getOperand(1);
1122   SDValue Op2 = Op.getOperand(2);
1123 
1124   EVT VT = Mask.getValueType();
1125 
1126   // If we can't even use the basic vector operations of
1127   // AND,OR,XOR, we will have to scalarize the op.
1128   // Notice that the operation may be 'promoted' which means that it is
1129   // 'bitcasted' to another type which is handled.
1130   // This operation also isn't safe with AND, OR, XOR when the boolean
1131   // type is 0/1 as we need an all ones vector constant to mask with.
1132   // FIXME: Sign extend 1 to all ones if thats legal on the target.
1133   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
1134       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
1135       TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand ||
1136       TLI.getBooleanContents(Op1.getValueType()) !=
1137           TargetLowering::ZeroOrNegativeOneBooleanContent)
1138     return DAG.UnrollVectorOp(Op.getNode());
1139 
1140   // If the mask and the type are different sizes, unroll the vector op. This
1141   // can occur when getSetCCResultType returns something that is different in
1142   // size from the operand types. For example, v4i8 = select v4i32, v4i8, v4i8.
1143   if (VT.getSizeInBits() != Op1.getValueSizeInBits())
1144     return DAG.UnrollVectorOp(Op.getNode());
1145 
1146   // Bitcast the operands to be the same type as the mask.
1147   // This is needed when we select between FP types because
1148   // the mask is a vector of integers.
1149   Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
1150   Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
1151 
1152   SDValue AllOnes = DAG.getConstant(
1153     APInt::getAllOnesValue(VT.getScalarSizeInBits()), DL, VT);
1154   SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
1155 
1156   Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
1157   Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
1158   SDValue Val = DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
1159   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
1160 }
1161 
1162 SDValue VectorLegalizer::ExpandABS(SDValue Op) {
1163   // Attempt to expand using TargetLowering.
1164   SDValue Result;
1165   if (TLI.expandABS(Op.getNode(), Result, DAG))
1166     return Result;
1167 
1168   // Otherwise go ahead and unroll.
1169   return DAG.UnrollVectorOp(Op.getNode());
1170 }
1171 
1172 SDValue VectorLegalizer::ExpandFP_TO_UINT(SDValue Op) {
1173   // Attempt to expand using TargetLowering.
1174   SDValue Result, Chain;
1175   if (TLI.expandFP_TO_UINT(Op.getNode(), Result, Chain, DAG)) {
1176     if (Op.getNode()->isStrictFPOpcode())
1177       // Relink the chain
1178       DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Chain);
1179     return Result;
1180   }
1181 
1182   // Otherwise go ahead and unroll.
1183   return DAG.UnrollVectorOp(Op.getNode());
1184 }
1185 
1186 SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) {
1187   bool IsStrict = Op.getNode()->isStrictFPOpcode();
1188   unsigned OpNo = IsStrict ? 1 : 0;
1189   SDValue Src = Op.getOperand(OpNo);
1190   EVT VT = Src.getValueType();
1191   SDLoc DL(Op);
1192 
1193   // Attempt to expand using TargetLowering.
1194   SDValue Result;
1195   SDValue Chain;
1196   if (TLI.expandUINT_TO_FP(Op.getNode(), Result, Chain, DAG)) {
1197     if (IsStrict)
1198       // Relink the chain
1199       DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Chain);
1200     return Result;
1201   }
1202 
1203   // Make sure that the SINT_TO_FP and SRL instructions are available.
1204   if (((!IsStrict && TLI.getOperationAction(ISD::SINT_TO_FP, VT) ==
1205                          TargetLowering::Expand) ||
1206        (IsStrict && TLI.getOperationAction(ISD::STRICT_SINT_TO_FP, VT) ==
1207                         TargetLowering::Expand)) ||
1208       TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Expand)
1209     return IsStrict ? SDValue() : DAG.UnrollVectorOp(Op.getNode());
1210 
1211   unsigned BW = VT.getScalarSizeInBits();
1212   assert((BW == 64 || BW == 32) &&
1213          "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
1214 
1215   SDValue HalfWord = DAG.getConstant(BW / 2, DL, VT);
1216 
1217   // Constants to clear the upper part of the word.
1218   // Notice that we can also use SHL+SHR, but using a constant is slightly
1219   // faster on x86.
1220   uint64_t HWMask = (BW == 64) ? 0x00000000FFFFFFFF : 0x0000FFFF;
1221   SDValue HalfWordMask = DAG.getConstant(HWMask, DL, VT);
1222 
1223   // Two to the power of half-word-size.
1224   SDValue TWOHW = DAG.getConstantFP(1ULL << (BW / 2), DL, Op.getValueType());
1225 
1226   // Clear upper part of LO, lower HI
1227   SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Src, HalfWord);
1228   SDValue LO = DAG.getNode(ISD::AND, DL, VT, Src, HalfWordMask);
1229 
1230   if (IsStrict) {
1231     // Convert hi and lo to floats
1232     // Convert the hi part back to the upper values
1233     // TODO: Can any fast-math-flags be set on these nodes?
1234     SDValue fHI =
1235         DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {Op.getValueType(), MVT::Other},
1236                     {Op.getOperand(0), HI});
1237     fHI = DAG.getNode(ISD::STRICT_FMUL, DL, {Op.getValueType(), MVT::Other},
1238                       {SDValue(fHI.getNode(), 1), fHI, TWOHW});
1239     SDValue fLO =
1240         DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {Op.getValueType(), MVT::Other},
1241                     {SDValue(fHI.getNode(), 1), LO});
1242 
1243     // Add the two halves
1244     SDValue Result =
1245         DAG.getNode(ISD::STRICT_FADD, DL, {Op.getValueType(), MVT::Other},
1246                     {SDValue(fLO.getNode(), 1), fHI, fLO});
1247 
1248     // Relink the chain
1249     DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), SDValue(Result.getNode(), 1));
1250     return Result;
1251   }
1252 
1253   // Convert hi and lo to floats
1254   // Convert the hi part back to the upper values
1255   // TODO: Can any fast-math-flags be set on these nodes?
1256   SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI);
1257           fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW);
1258   SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO);
1259 
1260   // Add the two halves
1261   return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO);
1262 }
1263 
1264 SDValue VectorLegalizer::ExpandFNEG(SDValue Op) {
1265   if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) {
1266     SDLoc DL(Op);
1267     SDValue Zero = DAG.getConstantFP(-0.0, DL, Op.getValueType());
1268     // TODO: If FNEG had fast-math-flags, they'd get propagated to this FSUB.
1269     return DAG.getNode(ISD::FSUB, DL, Op.getValueType(),
1270                        Zero, Op.getOperand(0));
1271   }
1272   return DAG.UnrollVectorOp(Op.getNode());
1273 }
1274 
1275 SDValue VectorLegalizer::ExpandFSUB(SDValue Op) {
1276   // For floating-point values, (a-b) is the same as a+(-b). If FNEG is legal,
1277   // we can defer this to operation legalization where it will be lowered as
1278   // a+(-b).
1279   EVT VT = Op.getValueType();
1280   if (TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
1281       TLI.isOperationLegalOrCustom(ISD::FADD, VT))
1282     return Op; // Defer to LegalizeDAG
1283 
1284   return DAG.UnrollVectorOp(Op.getNode());
1285 }
1286 
1287 SDValue VectorLegalizer::ExpandCTPOP(SDValue Op) {
1288   SDValue Result;
1289   if (TLI.expandCTPOP(Op.getNode(), Result, DAG))
1290     return Result;
1291 
1292   return DAG.UnrollVectorOp(Op.getNode());
1293 }
1294 
1295 SDValue VectorLegalizer::ExpandCTLZ(SDValue Op) {
1296   SDValue Result;
1297   if (TLI.expandCTLZ(Op.getNode(), Result, DAG))
1298     return Result;
1299 
1300   return DAG.UnrollVectorOp(Op.getNode());
1301 }
1302 
1303 SDValue VectorLegalizer::ExpandCTTZ(SDValue Op) {
1304   SDValue Result;
1305   if (TLI.expandCTTZ(Op.getNode(), Result, DAG))
1306     return Result;
1307 
1308   return DAG.UnrollVectorOp(Op.getNode());
1309 }
1310 
1311 SDValue VectorLegalizer::ExpandFunnelShift(SDValue Op) {
1312   SDValue Result;
1313   if (TLI.expandFunnelShift(Op.getNode(), Result, DAG))
1314     return Result;
1315 
1316   return DAG.UnrollVectorOp(Op.getNode());
1317 }
1318 
1319 SDValue VectorLegalizer::ExpandROT(SDValue Op) {
1320   SDValue Result;
1321   if (TLI.expandROT(Op.getNode(), Result, DAG))
1322     return Result;
1323 
1324   return DAG.UnrollVectorOp(Op.getNode());
1325 }
1326 
1327 SDValue VectorLegalizer::ExpandFMINNUM_FMAXNUM(SDValue Op) {
1328   if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Op.getNode(), DAG))
1329     return Expanded;
1330   return DAG.UnrollVectorOp(Op.getNode());
1331 }
1332 
1333 SDValue VectorLegalizer::ExpandUADDSUBO(SDValue Op) {
1334   SDValue Result, Overflow;
1335   TLI.expandUADDSUBO(Op.getNode(), Result, Overflow, DAG);
1336 
1337   if (Op.getResNo() == 0) {
1338     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Overflow));
1339     return Result;
1340   } else {
1341     AddLegalizedOperand(Op.getValue(0), LegalizeOp(Result));
1342     return Overflow;
1343   }
1344 }
1345 
1346 SDValue VectorLegalizer::ExpandSADDSUBO(SDValue Op) {
1347   SDValue Result, Overflow;
1348   TLI.expandSADDSUBO(Op.getNode(), Result, Overflow, DAG);
1349 
1350   if (Op.getResNo() == 0) {
1351     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Overflow));
1352     return Result;
1353   } else {
1354     AddLegalizedOperand(Op.getValue(0), LegalizeOp(Result));
1355     return Overflow;
1356   }
1357 }
1358 
1359 SDValue VectorLegalizer::ExpandMULO(SDValue Op) {
1360   SDValue Result, Overflow;
1361   if (!TLI.expandMULO(Op.getNode(), Result, Overflow, DAG))
1362     std::tie(Result, Overflow) = DAG.UnrollVectorOverflowOp(Op.getNode());
1363 
1364   if (Op.getResNo() == 0) {
1365     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Overflow));
1366     return Result;
1367   } else {
1368     AddLegalizedOperand(Op.getValue(0), LegalizeOp(Result));
1369     return Overflow;
1370   }
1371 }
1372 
1373 SDValue VectorLegalizer::ExpandAddSubSat(SDValue Op) {
1374   if (SDValue Expanded = TLI.expandAddSubSat(Op.getNode(), DAG))
1375     return Expanded;
1376   return DAG.UnrollVectorOp(Op.getNode());
1377 }
1378 
1379 SDValue VectorLegalizer::ExpandFixedPointMul(SDValue Op) {
1380   if (SDValue Expanded = TLI.expandFixedPointMul(Op.getNode(), DAG))
1381     return Expanded;
1382   return DAG.UnrollVectorOp(Op.getNode());
1383 }
1384 
1385 SDValue VectorLegalizer::ExpandStrictFPOp(SDValue Op) {
1386   if (Op.getOpcode() == ISD::STRICT_UINT_TO_FP) {
1387     if (SDValue Res = ExpandUINT_TO_FLOAT(Op))
1388       return Res;
1389   }
1390 
1391   EVT VT = Op.getValue(0).getValueType();
1392   EVT EltVT = VT.getVectorElementType();
1393   unsigned NumElems = VT.getVectorNumElements();
1394   unsigned NumOpers = Op.getNumOperands();
1395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1396 
1397   EVT TmpEltVT = EltVT;
1398   if (Op->getOpcode() == ISD::STRICT_FSETCC ||
1399       Op->getOpcode() == ISD::STRICT_FSETCCS)
1400     TmpEltVT = TLI.getSetCCResultType(DAG.getDataLayout(),
1401                                       *DAG.getContext(), TmpEltVT);
1402 
1403   EVT ValueVTs[] = {TmpEltVT, MVT::Other};
1404   SDValue Chain = Op.getOperand(0);
1405   SDLoc dl(Op);
1406 
1407   SmallVector<SDValue, 32> OpValues;
1408   SmallVector<SDValue, 32> OpChains;
1409   for (unsigned i = 0; i < NumElems; ++i) {
1410     SmallVector<SDValue, 4> Opers;
1411     SDValue Idx = DAG.getConstant(i, dl,
1412                                   TLI.getVectorIdxTy(DAG.getDataLayout()));
1413 
1414     // The Chain is the first operand.
1415     Opers.push_back(Chain);
1416 
1417     // Now process the remaining operands.
1418     for (unsigned j = 1; j < NumOpers; ++j) {
1419       SDValue Oper = Op.getOperand(j);
1420       EVT OperVT = Oper.getValueType();
1421 
1422       if (OperVT.isVector())
1423         Oper = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1424                            OperVT.getVectorElementType(), Oper, Idx);
1425 
1426       Opers.push_back(Oper);
1427     }
1428 
1429     SDValue ScalarOp = DAG.getNode(Op->getOpcode(), dl, ValueVTs, Opers);
1430     SDValue ScalarResult = ScalarOp.getValue(0);
1431     SDValue ScalarChain = ScalarOp.getValue(1);
1432 
1433     if (Op->getOpcode() == ISD::STRICT_FSETCC ||
1434         Op->getOpcode() == ISD::STRICT_FSETCCS)
1435       ScalarResult = DAG.getSelect(dl, EltVT, ScalarResult,
1436                            DAG.getConstant(APInt::getAllOnesValue
1437                                            (EltVT.getSizeInBits()), dl, EltVT),
1438                            DAG.getConstant(0, dl, EltVT));
1439 
1440     OpValues.push_back(ScalarResult);
1441     OpChains.push_back(ScalarChain);
1442   }
1443 
1444   SDValue Result = DAG.getBuildVector(VT, dl, OpValues);
1445   SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OpChains);
1446 
1447   AddLegalizedOperand(Op.getValue(0), Result);
1448   AddLegalizedOperand(Op.getValue(1), NewChain);
1449 
1450   return Op.getResNo() ? NewChain : Result;
1451 }
1452 
1453 SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) {
1454   EVT VT = Op.getValueType();
1455   unsigned NumElems = VT.getVectorNumElements();
1456   EVT EltVT = VT.getVectorElementType();
1457   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2);
1458   EVT TmpEltVT = LHS.getValueType().getVectorElementType();
1459   SDLoc dl(Op);
1460   SmallVector<SDValue, 8> Ops(NumElems);
1461   for (unsigned i = 0; i < NumElems; ++i) {
1462     SDValue LHSElem = DAG.getNode(
1463         ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
1464         DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
1465     SDValue RHSElem = DAG.getNode(
1466         ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
1467         DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
1468     Ops[i] = DAG.getNode(ISD::SETCC, dl,
1469                          TLI.getSetCCResultType(DAG.getDataLayout(),
1470                                                 *DAG.getContext(), TmpEltVT),
1471                          LHSElem, RHSElem, CC);
1472     Ops[i] = DAG.getSelect(dl, EltVT, Ops[i],
1473                            DAG.getConstant(APInt::getAllOnesValue
1474                                            (EltVT.getSizeInBits()), dl, EltVT),
1475                            DAG.getConstant(0, dl, EltVT));
1476   }
1477   return DAG.getBuildVector(VT, dl, Ops);
1478 }
1479 
1480 bool SelectionDAG::LegalizeVectors() {
1481   return VectorLegalizer(*this).Run();
1482 }
1483