xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp (revision a7dea1671b87c07d2d266f836bfa8b58efc7c134)
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   switch (Op.getOpcode()) {
311   default:
312     return TranslateLegalizeResults(Op, Result);
313   case ISD::STRICT_FADD:
314   case ISD::STRICT_FSUB:
315   case ISD::STRICT_FMUL:
316   case ISD::STRICT_FDIV:
317   case ISD::STRICT_FREM:
318   case ISD::STRICT_FSQRT:
319   case ISD::STRICT_FMA:
320   case ISD::STRICT_FPOW:
321   case ISD::STRICT_FPOWI:
322   case ISD::STRICT_FSIN:
323   case ISD::STRICT_FCOS:
324   case ISD::STRICT_FEXP:
325   case ISD::STRICT_FEXP2:
326   case ISD::STRICT_FLOG:
327   case ISD::STRICT_FLOG10:
328   case ISD::STRICT_FLOG2:
329   case ISD::STRICT_FRINT:
330   case ISD::STRICT_FNEARBYINT:
331   case ISD::STRICT_FMAXNUM:
332   case ISD::STRICT_FMINNUM:
333   case ISD::STRICT_FCEIL:
334   case ISD::STRICT_FFLOOR:
335   case ISD::STRICT_FROUND:
336   case ISD::STRICT_FTRUNC:
337   case ISD::STRICT_FP_TO_SINT:
338   case ISD::STRICT_FP_TO_UINT:
339   case ISD::STRICT_FP_ROUND:
340   case ISD::STRICT_FP_EXTEND:
341     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
342     // If we're asked to expand a strict vector floating-point operation,
343     // by default we're going to simply unroll it.  That is usually the
344     // best approach, except in the case where the resulting strict (scalar)
345     // operations would themselves use the fallback mutation to non-strict.
346     // In that specific case, just do the fallback on the vector op.
347     if (Action == TargetLowering::Expand &&
348         TLI.getStrictFPOperationAction(Node->getOpcode(),
349                                        Node->getValueType(0))
350         == TargetLowering::Legal) {
351       EVT EltVT = Node->getValueType(0).getVectorElementType();
352       if (TLI.getOperationAction(Node->getOpcode(), EltVT)
353           == TargetLowering::Expand &&
354           TLI.getStrictFPOperationAction(Node->getOpcode(), EltVT)
355           == TargetLowering::Legal)
356         Action = TargetLowering::Legal;
357     }
358     break;
359   case ISD::ADD:
360   case ISD::SUB:
361   case ISD::MUL:
362   case ISD::MULHS:
363   case ISD::MULHU:
364   case ISD::SDIV:
365   case ISD::UDIV:
366   case ISD::SREM:
367   case ISD::UREM:
368   case ISD::SDIVREM:
369   case ISD::UDIVREM:
370   case ISD::FADD:
371   case ISD::FSUB:
372   case ISD::FMUL:
373   case ISD::FDIV:
374   case ISD::FREM:
375   case ISD::AND:
376   case ISD::OR:
377   case ISD::XOR:
378   case ISD::SHL:
379   case ISD::SRA:
380   case ISD::SRL:
381   case ISD::FSHL:
382   case ISD::FSHR:
383   case ISD::ROTL:
384   case ISD::ROTR:
385   case ISD::ABS:
386   case ISD::BSWAP:
387   case ISD::BITREVERSE:
388   case ISD::CTLZ:
389   case ISD::CTTZ:
390   case ISD::CTLZ_ZERO_UNDEF:
391   case ISD::CTTZ_ZERO_UNDEF:
392   case ISD::CTPOP:
393   case ISD::SELECT:
394   case ISD::VSELECT:
395   case ISD::SELECT_CC:
396   case ISD::SETCC:
397   case ISD::ZERO_EXTEND:
398   case ISD::ANY_EXTEND:
399   case ISD::TRUNCATE:
400   case ISD::SIGN_EXTEND:
401   case ISD::FP_TO_SINT:
402   case ISD::FP_TO_UINT:
403   case ISD::FNEG:
404   case ISD::FABS:
405   case ISD::FMINNUM:
406   case ISD::FMAXNUM:
407   case ISD::FMINNUM_IEEE:
408   case ISD::FMAXNUM_IEEE:
409   case ISD::FMINIMUM:
410   case ISD::FMAXIMUM:
411   case ISD::FCOPYSIGN:
412   case ISD::FSQRT:
413   case ISD::FSIN:
414   case ISD::FCOS:
415   case ISD::FPOWI:
416   case ISD::FPOW:
417   case ISD::FLOG:
418   case ISD::FLOG2:
419   case ISD::FLOG10:
420   case ISD::FEXP:
421   case ISD::FEXP2:
422   case ISD::FCEIL:
423   case ISD::FTRUNC:
424   case ISD::FRINT:
425   case ISD::FNEARBYINT:
426   case ISD::FROUND:
427   case ISD::FFLOOR:
428   case ISD::FP_ROUND:
429   case ISD::FP_EXTEND:
430   case ISD::FMA:
431   case ISD::SIGN_EXTEND_INREG:
432   case ISD::ANY_EXTEND_VECTOR_INREG:
433   case ISD::SIGN_EXTEND_VECTOR_INREG:
434   case ISD::ZERO_EXTEND_VECTOR_INREG:
435   case ISD::SMIN:
436   case ISD::SMAX:
437   case ISD::UMIN:
438   case ISD::UMAX:
439   case ISD::SMUL_LOHI:
440   case ISD::UMUL_LOHI:
441   case ISD::SADDO:
442   case ISD::UADDO:
443   case ISD::SSUBO:
444   case ISD::USUBO:
445   case ISD::SMULO:
446   case ISD::UMULO:
447   case ISD::FCANONICALIZE:
448   case ISD::SADDSAT:
449   case ISD::UADDSAT:
450   case ISD::SSUBSAT:
451   case ISD::USUBSAT:
452     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
453     break;
454   case ISD::SMULFIX:
455   case ISD::SMULFIXSAT:
456   case ISD::UMULFIX:
457   case ISD::UMULFIXSAT: {
458     unsigned Scale = Node->getConstantOperandVal(2);
459     Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
460                                               Node->getValueType(0), Scale);
461     break;
462   }
463   case ISD::SINT_TO_FP:
464   case ISD::UINT_TO_FP:
465   case ISD::VECREDUCE_ADD:
466   case ISD::VECREDUCE_MUL:
467   case ISD::VECREDUCE_AND:
468   case ISD::VECREDUCE_OR:
469   case ISD::VECREDUCE_XOR:
470   case ISD::VECREDUCE_SMAX:
471   case ISD::VECREDUCE_SMIN:
472   case ISD::VECREDUCE_UMAX:
473   case ISD::VECREDUCE_UMIN:
474   case ISD::VECREDUCE_FADD:
475   case ISD::VECREDUCE_FMUL:
476   case ISD::VECREDUCE_FMAX:
477   case ISD::VECREDUCE_FMIN:
478     Action = TLI.getOperationAction(Node->getOpcode(),
479                                     Node->getOperand(0).getValueType());
480     break;
481   }
482 
483   LLVM_DEBUG(dbgs() << "\nLegalizing vector op: "; Node->dump(&DAG));
484 
485   switch (Action) {
486   default: llvm_unreachable("This action is not supported yet!");
487   case TargetLowering::Promote:
488     Result = Promote(Op);
489     Changed = true;
490     break;
491   case TargetLowering::Legal:
492     LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
493     break;
494   case TargetLowering::Custom: {
495     LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
496     if (SDValue Tmp1 = TLI.LowerOperation(Op, DAG)) {
497       LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
498       Result = Tmp1;
499       break;
500     }
501     LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
502     LLVM_FALLTHROUGH;
503   }
504   case TargetLowering::Expand:
505     Result = Expand(Op);
506   }
507 
508   // Make sure that the generated code is itself legal.
509   if (Result != Op) {
510     Result = LegalizeOp(Result);
511     Changed = true;
512   }
513 
514   // Note that LegalizeOp may be reentered even from single-use nodes, which
515   // means that we always must cache transformed nodes.
516   AddLegalizedOperand(Op, Result);
517   return Result;
518 }
519 
520 SDValue VectorLegalizer::Promote(SDValue Op) {
521   // For a few operations there is a specific concept for promotion based on
522   // the operand's type.
523   switch (Op.getOpcode()) {
524   case ISD::SINT_TO_FP:
525   case ISD::UINT_TO_FP:
526     // "Promote" the operation by extending the operand.
527     return PromoteINT_TO_FP(Op);
528   case ISD::FP_TO_UINT:
529   case ISD::FP_TO_SINT:
530     // Promote the operation by extending the operand.
531     return PromoteFP_TO_INT(Op);
532   }
533 
534   // There are currently two cases of vector promotion:
535   // 1) Bitcasting a vector of integers to a different type to a vector of the
536   //    same overall length. For example, x86 promotes ISD::AND v2i32 to v1i64.
537   // 2) Extending a vector of floats to a vector of the same number of larger
538   //    floats. For example, AArch64 promotes ISD::FADD on v4f16 to v4f32.
539   MVT VT = Op.getSimpleValueType();
540   assert(Op.getNode()->getNumValues() == 1 &&
541          "Can't promote a vector with multiple results!");
542   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
543   SDLoc dl(Op);
544   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
545 
546   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
547     if (Op.getOperand(j).getValueType().isVector())
548       if (Op.getOperand(j)
549               .getValueType()
550               .getVectorElementType()
551               .isFloatingPoint() &&
552           NVT.isVector() && NVT.getVectorElementType().isFloatingPoint())
553         Operands[j] = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Op.getOperand(j));
554       else
555         Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Op.getOperand(j));
556     else
557       Operands[j] = Op.getOperand(j);
558   }
559 
560   Op = DAG.getNode(Op.getOpcode(), dl, NVT, Operands, Op.getNode()->getFlags());
561   if ((VT.isFloatingPoint() && NVT.isFloatingPoint()) ||
562       (VT.isVector() && VT.getVectorElementType().isFloatingPoint() &&
563        NVT.isVector() && NVT.getVectorElementType().isFloatingPoint()))
564     return DAG.getNode(ISD::FP_ROUND, dl, VT, Op, DAG.getIntPtrConstant(0, dl));
565   else
566     return DAG.getNode(ISD::BITCAST, dl, VT, Op);
567 }
568 
569 SDValue VectorLegalizer::PromoteINT_TO_FP(SDValue Op) {
570   // INT_TO_FP operations may require the input operand be promoted even
571   // when the type is otherwise legal.
572   MVT VT = Op.getOperand(0).getSimpleValueType();
573   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
574   assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
575          "Vectors have different number of elements!");
576 
577   SDLoc dl(Op);
578   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
579 
580   unsigned Opc = Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND :
581     ISD::SIGN_EXTEND;
582   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
583     if (Op.getOperand(j).getValueType().isVector())
584       Operands[j] = DAG.getNode(Opc, dl, NVT, Op.getOperand(j));
585     else
586       Operands[j] = Op.getOperand(j);
587   }
588 
589   return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Operands);
590 }
591 
592 // For FP_TO_INT we promote the result type to a vector type with wider
593 // elements and then truncate the result.  This is different from the default
594 // PromoteVector which uses bitcast to promote thus assumning that the
595 // promoted vector type has the same overall size.
596 SDValue VectorLegalizer::PromoteFP_TO_INT(SDValue Op) {
597   MVT VT = Op.getSimpleValueType();
598   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
599   assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
600          "Vectors have different number of elements!");
601 
602   unsigned NewOpc = Op->getOpcode();
603   // Change FP_TO_UINT to FP_TO_SINT if possible.
604   // TODO: Should we only do this if FP_TO_UINT itself isn't legal?
605   if (NewOpc == ISD::FP_TO_UINT &&
606       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
607     NewOpc = ISD::FP_TO_SINT;
608 
609   SDLoc dl(Op);
610   SDValue Promoted  = DAG.getNode(NewOpc, dl, NVT, Op.getOperand(0));
611 
612   // Assert that the converted value fits in the original type.  If it doesn't
613   // (eg: because the value being converted is too big), then the result of the
614   // original operation was undefined anyway, so the assert is still correct.
615   Promoted = DAG.getNode(Op->getOpcode() == ISD::FP_TO_UINT ? ISD::AssertZext
616                                                             : ISD::AssertSext,
617                          dl, NVT, Promoted,
618                          DAG.getValueType(VT.getScalarType()));
619   return DAG.getNode(ISD::TRUNCATE, dl, VT, Promoted);
620 }
621 
622 SDValue VectorLegalizer::ExpandLoad(SDValue Op) {
623   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
624 
625   EVT SrcVT = LD->getMemoryVT();
626   EVT SrcEltVT = SrcVT.getScalarType();
627   unsigned NumElem = SrcVT.getVectorNumElements();
628 
629   SDValue NewChain;
630   SDValue Value;
631   if (SrcVT.getVectorNumElements() > 1 && !SrcEltVT.isByteSized()) {
632     SDLoc dl(Op);
633 
634     SmallVector<SDValue, 8> Vals;
635     SmallVector<SDValue, 8> LoadChains;
636 
637     EVT DstEltVT = LD->getValueType(0).getScalarType();
638     SDValue Chain = LD->getChain();
639     SDValue BasePTR = LD->getBasePtr();
640     ISD::LoadExtType ExtType = LD->getExtensionType();
641 
642     // When elements in a vector is not byte-addressable, we cannot directly
643     // load each element by advancing pointer, which could only address bytes.
644     // Instead, we load all significant words, mask bits off, and concatenate
645     // them to form each element. Finally, they are extended to destination
646     // scalar type to build the destination vector.
647     EVT WideVT = TLI.getPointerTy(DAG.getDataLayout());
648 
649     assert(WideVT.isRound() &&
650            "Could not handle the sophisticated case when the widest integer is"
651            " not power of 2.");
652     assert(WideVT.bitsGE(SrcEltVT) &&
653            "Type is not legalized?");
654 
655     unsigned WideBytes = WideVT.getStoreSize();
656     unsigned Offset = 0;
657     unsigned RemainingBytes = SrcVT.getStoreSize();
658     SmallVector<SDValue, 8> LoadVals;
659     while (RemainingBytes > 0) {
660       SDValue ScalarLoad;
661       unsigned LoadBytes = WideBytes;
662 
663       if (RemainingBytes >= LoadBytes) {
664         ScalarLoad =
665             DAG.getLoad(WideVT, dl, Chain, BasePTR,
666                         LD->getPointerInfo().getWithOffset(Offset),
667                         MinAlign(LD->getAlignment(), Offset),
668                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
669       } else {
670         EVT LoadVT = WideVT;
671         while (RemainingBytes < LoadBytes) {
672           LoadBytes >>= 1; // Reduce the load size by half.
673           LoadVT = EVT::getIntegerVT(*DAG.getContext(), LoadBytes << 3);
674         }
675         ScalarLoad =
676             DAG.getExtLoad(ISD::EXTLOAD, dl, WideVT, Chain, BasePTR,
677                            LD->getPointerInfo().getWithOffset(Offset), LoadVT,
678                            MinAlign(LD->getAlignment(), Offset),
679                            LD->getMemOperand()->getFlags(), LD->getAAInfo());
680       }
681 
682       RemainingBytes -= LoadBytes;
683       Offset += LoadBytes;
684 
685       BasePTR = DAG.getObjectPtrOffset(dl, BasePTR, LoadBytes);
686 
687       LoadVals.push_back(ScalarLoad.getValue(0));
688       LoadChains.push_back(ScalarLoad.getValue(1));
689     }
690 
691     unsigned BitOffset = 0;
692     unsigned WideIdx = 0;
693     unsigned WideBits = WideVT.getSizeInBits();
694 
695     // Extract bits, pack and extend/trunc them into destination type.
696     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
697     SDValue SrcEltBitMask = DAG.getConstant(
698         APInt::getLowBitsSet(WideBits, SrcEltBits), dl, WideVT);
699 
700     for (unsigned Idx = 0; Idx != NumElem; ++Idx) {
701       assert(BitOffset < WideBits && "Unexpected offset!");
702 
703       SDValue ShAmt = DAG.getConstant(
704           BitOffset, dl, TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
705       SDValue Lo = DAG.getNode(ISD::SRL, dl, WideVT, LoadVals[WideIdx], ShAmt);
706 
707       BitOffset += SrcEltBits;
708       if (BitOffset >= WideBits) {
709         WideIdx++;
710         BitOffset -= WideBits;
711         if (BitOffset > 0) {
712           ShAmt = DAG.getConstant(
713               SrcEltBits - BitOffset, dl,
714               TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
715           SDValue Hi =
716               DAG.getNode(ISD::SHL, dl, WideVT, LoadVals[WideIdx], ShAmt);
717           Lo = DAG.getNode(ISD::OR, dl, WideVT, Lo, Hi);
718         }
719       }
720 
721       Lo = DAG.getNode(ISD::AND, dl, WideVT, Lo, SrcEltBitMask);
722 
723       switch (ExtType) {
724       default: llvm_unreachable("Unknown extended-load op!");
725       case ISD::EXTLOAD:
726         Lo = DAG.getAnyExtOrTrunc(Lo, dl, DstEltVT);
727         break;
728       case ISD::ZEXTLOAD:
729         Lo = DAG.getZExtOrTrunc(Lo, dl, DstEltVT);
730         break;
731       case ISD::SEXTLOAD:
732         ShAmt =
733             DAG.getConstant(WideBits - SrcEltBits, dl,
734                             TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
735         Lo = DAG.getNode(ISD::SHL, dl, WideVT, Lo, ShAmt);
736         Lo = DAG.getNode(ISD::SRA, dl, WideVT, Lo, ShAmt);
737         Lo = DAG.getSExtOrTrunc(Lo, dl, DstEltVT);
738         break;
739       }
740       Vals.push_back(Lo);
741     }
742 
743     NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
744     Value = DAG.getBuildVector(Op.getNode()->getValueType(0), dl, Vals);
745   } else {
746     SDValue Scalarized = TLI.scalarizeVectorLoad(LD, DAG);
747     // Skip past MERGE_VALUE node if known.
748     if (Scalarized->getOpcode() == ISD::MERGE_VALUES) {
749       NewChain = Scalarized.getOperand(1);
750       Value = Scalarized.getOperand(0);
751     } else {
752       NewChain = Scalarized.getValue(1);
753       Value = Scalarized.getValue(0);
754     }
755   }
756 
757   AddLegalizedOperand(Op.getValue(0), Value);
758   AddLegalizedOperand(Op.getValue(1), NewChain);
759 
760   return (Op.getResNo() ? NewChain : Value);
761 }
762 
763 SDValue VectorLegalizer::ExpandStore(SDValue Op) {
764   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
765   SDValue TF = TLI.scalarizeVectorStore(ST, DAG);
766   AddLegalizedOperand(Op, TF);
767   return TF;
768 }
769 
770 SDValue VectorLegalizer::Expand(SDValue Op) {
771   switch (Op->getOpcode()) {
772   case ISD::SIGN_EXTEND_INREG:
773     return ExpandSEXTINREG(Op);
774   case ISD::ANY_EXTEND_VECTOR_INREG:
775     return ExpandANY_EXTEND_VECTOR_INREG(Op);
776   case ISD::SIGN_EXTEND_VECTOR_INREG:
777     return ExpandSIGN_EXTEND_VECTOR_INREG(Op);
778   case ISD::ZERO_EXTEND_VECTOR_INREG:
779     return ExpandZERO_EXTEND_VECTOR_INREG(Op);
780   case ISD::BSWAP:
781     return ExpandBSWAP(Op);
782   case ISD::VSELECT:
783     return ExpandVSELECT(Op);
784   case ISD::SELECT:
785     return ExpandSELECT(Op);
786   case ISD::FP_TO_UINT:
787     return ExpandFP_TO_UINT(Op);
788   case ISD::UINT_TO_FP:
789     return ExpandUINT_TO_FLOAT(Op);
790   case ISD::FNEG:
791     return ExpandFNEG(Op);
792   case ISD::FSUB:
793     return ExpandFSUB(Op);
794   case ISD::SETCC:
795     return UnrollVSETCC(Op);
796   case ISD::ABS:
797     return ExpandABS(Op);
798   case ISD::BITREVERSE:
799     return ExpandBITREVERSE(Op);
800   case ISD::CTPOP:
801     return ExpandCTPOP(Op);
802   case ISD::CTLZ:
803   case ISD::CTLZ_ZERO_UNDEF:
804     return ExpandCTLZ(Op);
805   case ISD::CTTZ:
806   case ISD::CTTZ_ZERO_UNDEF:
807     return ExpandCTTZ(Op);
808   case ISD::FSHL:
809   case ISD::FSHR:
810     return ExpandFunnelShift(Op);
811   case ISD::ROTL:
812   case ISD::ROTR:
813     return ExpandROT(Op);
814   case ISD::FMINNUM:
815   case ISD::FMAXNUM:
816     return ExpandFMINNUM_FMAXNUM(Op);
817   case ISD::UADDO:
818   case ISD::USUBO:
819     return ExpandUADDSUBO(Op);
820   case ISD::SADDO:
821   case ISD::SSUBO:
822     return ExpandSADDSUBO(Op);
823   case ISD::UMULO:
824   case ISD::SMULO:
825     return ExpandMULO(Op);
826   case ISD::USUBSAT:
827   case ISD::SSUBSAT:
828   case ISD::UADDSAT:
829   case ISD::SADDSAT:
830     return ExpandAddSubSat(Op);
831   case ISD::SMULFIX:
832   case ISD::UMULFIX:
833     return ExpandFixedPointMul(Op);
834   case ISD::SMULFIXSAT:
835   case ISD::UMULFIXSAT:
836     // FIXME: We do not expand SMULFIXSAT/UMULFIXSAT here yet, not sure exactly
837     // why. Maybe it results in worse codegen compared to the unroll for some
838     // targets? This should probably be investigated. And if we still prefer to
839     // unroll an explanation could be helpful.
840     return DAG.UnrollVectorOp(Op.getNode());
841   case ISD::STRICT_FADD:
842   case ISD::STRICT_FSUB:
843   case ISD::STRICT_FMUL:
844   case ISD::STRICT_FDIV:
845   case ISD::STRICT_FREM:
846   case ISD::STRICT_FSQRT:
847   case ISD::STRICT_FMA:
848   case ISD::STRICT_FPOW:
849   case ISD::STRICT_FPOWI:
850   case ISD::STRICT_FSIN:
851   case ISD::STRICT_FCOS:
852   case ISD::STRICT_FEXP:
853   case ISD::STRICT_FEXP2:
854   case ISD::STRICT_FLOG:
855   case ISD::STRICT_FLOG10:
856   case ISD::STRICT_FLOG2:
857   case ISD::STRICT_FRINT:
858   case ISD::STRICT_FNEARBYINT:
859   case ISD::STRICT_FMAXNUM:
860   case ISD::STRICT_FMINNUM:
861   case ISD::STRICT_FCEIL:
862   case ISD::STRICT_FFLOOR:
863   case ISD::STRICT_FROUND:
864   case ISD::STRICT_FTRUNC:
865   case ISD::STRICT_FP_TO_SINT:
866   case ISD::STRICT_FP_TO_UINT:
867     return ExpandStrictFPOp(Op);
868   case ISD::VECREDUCE_ADD:
869   case ISD::VECREDUCE_MUL:
870   case ISD::VECREDUCE_AND:
871   case ISD::VECREDUCE_OR:
872   case ISD::VECREDUCE_XOR:
873   case ISD::VECREDUCE_SMAX:
874   case ISD::VECREDUCE_SMIN:
875   case ISD::VECREDUCE_UMAX:
876   case ISD::VECREDUCE_UMIN:
877   case ISD::VECREDUCE_FADD:
878   case ISD::VECREDUCE_FMUL:
879   case ISD::VECREDUCE_FMAX:
880   case ISD::VECREDUCE_FMIN:
881     return TLI.expandVecReduce(Op.getNode(), DAG);
882   default:
883     return DAG.UnrollVectorOp(Op.getNode());
884   }
885 }
886 
887 SDValue VectorLegalizer::ExpandSELECT(SDValue Op) {
888   // Lower a select instruction where the condition is a scalar and the
889   // operands are vectors. Lower this select to VSELECT and implement it
890   // using XOR AND OR. The selector bit is broadcasted.
891   EVT VT = Op.getValueType();
892   SDLoc DL(Op);
893 
894   SDValue Mask = Op.getOperand(0);
895   SDValue Op1 = Op.getOperand(1);
896   SDValue Op2 = Op.getOperand(2);
897 
898   assert(VT.isVector() && !Mask.getValueType().isVector()
899          && Op1.getValueType() == Op2.getValueType() && "Invalid type");
900 
901   // If we can't even use the basic vector operations of
902   // AND,OR,XOR, we will have to scalarize the op.
903   // Notice that the operation may be 'promoted' which means that it is
904   // 'bitcasted' to another type which is handled.
905   // Also, we need to be able to construct a splat vector using BUILD_VECTOR.
906   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
907       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
908       TLI.getOperationAction(ISD::OR,  VT) == TargetLowering::Expand ||
909       TLI.getOperationAction(ISD::BUILD_VECTOR,  VT) == TargetLowering::Expand)
910     return DAG.UnrollVectorOp(Op.getNode());
911 
912   // Generate a mask operand.
913   EVT MaskTy = VT.changeVectorElementTypeToInteger();
914 
915   // What is the size of each element in the vector mask.
916   EVT BitTy = MaskTy.getScalarType();
917 
918   Mask = DAG.getSelect(DL, BitTy, Mask,
919           DAG.getConstant(APInt::getAllOnesValue(BitTy.getSizeInBits()), DL,
920                           BitTy),
921           DAG.getConstant(0, DL, BitTy));
922 
923   // Broadcast the mask so that the entire vector is all-one or all zero.
924   Mask = DAG.getSplatBuildVector(MaskTy, DL, Mask);
925 
926   // Bitcast the operands to be the same type as the mask.
927   // This is needed when we select between FP types because
928   // the mask is a vector of integers.
929   Op1 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op1);
930   Op2 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op2);
931 
932   SDValue AllOnes = DAG.getConstant(
933             APInt::getAllOnesValue(BitTy.getSizeInBits()), DL, MaskTy);
934   SDValue NotMask = DAG.getNode(ISD::XOR, DL, MaskTy, Mask, AllOnes);
935 
936   Op1 = DAG.getNode(ISD::AND, DL, MaskTy, Op1, Mask);
937   Op2 = DAG.getNode(ISD::AND, DL, MaskTy, Op2, NotMask);
938   SDValue Val = DAG.getNode(ISD::OR, DL, MaskTy, Op1, Op2);
939   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
940 }
941 
942 SDValue VectorLegalizer::ExpandSEXTINREG(SDValue Op) {
943   EVT VT = Op.getValueType();
944 
945   // Make sure that the SRA and SHL instructions are available.
946   if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Expand ||
947       TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Expand)
948     return DAG.UnrollVectorOp(Op.getNode());
949 
950   SDLoc DL(Op);
951   EVT OrigTy = cast<VTSDNode>(Op->getOperand(1))->getVT();
952 
953   unsigned BW = VT.getScalarSizeInBits();
954   unsigned OrigBW = OrigTy.getScalarSizeInBits();
955   SDValue ShiftSz = DAG.getConstant(BW - OrigBW, DL, VT);
956 
957   Op = Op.getOperand(0);
958   Op =   DAG.getNode(ISD::SHL, DL, VT, Op, ShiftSz);
959   return DAG.getNode(ISD::SRA, DL, VT, Op, ShiftSz);
960 }
961 
962 // Generically expand a vector anyext in register to a shuffle of the relevant
963 // lanes into the appropriate locations, with other lanes left undef.
964 SDValue VectorLegalizer::ExpandANY_EXTEND_VECTOR_INREG(SDValue Op) {
965   SDLoc DL(Op);
966   EVT VT = Op.getValueType();
967   int NumElements = VT.getVectorNumElements();
968   SDValue Src = Op.getOperand(0);
969   EVT SrcVT = Src.getValueType();
970   int NumSrcElements = SrcVT.getVectorNumElements();
971 
972   // *_EXTEND_VECTOR_INREG SrcVT can be smaller than VT - so insert the vector
973   // into a larger vector type.
974   if (SrcVT.bitsLE(VT)) {
975     assert((VT.getSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
976            "ANY_EXTEND_VECTOR_INREG vector size mismatch");
977     NumSrcElements = VT.getSizeInBits() / SrcVT.getScalarSizeInBits();
978     SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
979                              NumSrcElements);
980     Src = DAG.getNode(
981         ISD::INSERT_SUBVECTOR, DL, SrcVT, DAG.getUNDEF(SrcVT), Src,
982         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
983   }
984 
985   // Build a base mask of undef shuffles.
986   SmallVector<int, 16> ShuffleMask;
987   ShuffleMask.resize(NumSrcElements, -1);
988 
989   // Place the extended lanes into the correct locations.
990   int ExtLaneScale = NumSrcElements / NumElements;
991   int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
992   for (int i = 0; i < NumElements; ++i)
993     ShuffleMask[i * ExtLaneScale + EndianOffset] = i;
994 
995   return DAG.getNode(
996       ISD::BITCAST, DL, VT,
997       DAG.getVectorShuffle(SrcVT, DL, Src, DAG.getUNDEF(SrcVT), ShuffleMask));
998 }
999 
1000 SDValue VectorLegalizer::ExpandSIGN_EXTEND_VECTOR_INREG(SDValue Op) {
1001   SDLoc DL(Op);
1002   EVT VT = Op.getValueType();
1003   SDValue Src = Op.getOperand(0);
1004   EVT SrcVT = Src.getValueType();
1005 
1006   // First build an any-extend node which can be legalized above when we
1007   // recurse through it.
1008   Op = DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Src);
1009 
1010   // Now we need sign extend. Do this by shifting the elements. Even if these
1011   // aren't legal operations, they have a better chance of being legalized
1012   // without full scalarization than the sign extension does.
1013   unsigned EltWidth = VT.getScalarSizeInBits();
1014   unsigned SrcEltWidth = SrcVT.getScalarSizeInBits();
1015   SDValue ShiftAmount = DAG.getConstant(EltWidth - SrcEltWidth, DL, VT);
1016   return DAG.getNode(ISD::SRA, DL, VT,
1017                      DAG.getNode(ISD::SHL, DL, VT, Op, ShiftAmount),
1018                      ShiftAmount);
1019 }
1020 
1021 // Generically expand a vector zext in register to a shuffle of the relevant
1022 // lanes into the appropriate locations, a blend of zero into the high bits,
1023 // and a bitcast to the wider element type.
1024 SDValue VectorLegalizer::ExpandZERO_EXTEND_VECTOR_INREG(SDValue Op) {
1025   SDLoc DL(Op);
1026   EVT VT = Op.getValueType();
1027   int NumElements = VT.getVectorNumElements();
1028   SDValue Src = Op.getOperand(0);
1029   EVT SrcVT = Src.getValueType();
1030   int NumSrcElements = SrcVT.getVectorNumElements();
1031 
1032   // *_EXTEND_VECTOR_INREG SrcVT can be smaller than VT - so insert the vector
1033   // into a larger vector type.
1034   if (SrcVT.bitsLE(VT)) {
1035     assert((VT.getSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
1036            "ZERO_EXTEND_VECTOR_INREG vector size mismatch");
1037     NumSrcElements = VT.getSizeInBits() / SrcVT.getScalarSizeInBits();
1038     SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
1039                              NumSrcElements);
1040     Src = DAG.getNode(
1041         ISD::INSERT_SUBVECTOR, DL, SrcVT, DAG.getUNDEF(SrcVT), Src,
1042         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
1043   }
1044 
1045   // Build up a zero vector to blend into this one.
1046   SDValue Zero = DAG.getConstant(0, DL, SrcVT);
1047 
1048   // Shuffle the incoming lanes into the correct position, and pull all other
1049   // lanes from the zero vector.
1050   SmallVector<int, 16> ShuffleMask;
1051   ShuffleMask.reserve(NumSrcElements);
1052   for (int i = 0; i < NumSrcElements; ++i)
1053     ShuffleMask.push_back(i);
1054 
1055   int ExtLaneScale = NumSrcElements / NumElements;
1056   int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
1057   for (int i = 0; i < NumElements; ++i)
1058     ShuffleMask[i * ExtLaneScale + EndianOffset] = NumSrcElements + i;
1059 
1060   return DAG.getNode(ISD::BITCAST, DL, VT,
1061                      DAG.getVectorShuffle(SrcVT, DL, Zero, Src, ShuffleMask));
1062 }
1063 
1064 static void createBSWAPShuffleMask(EVT VT, SmallVectorImpl<int> &ShuffleMask) {
1065   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
1066   for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I)
1067     for (int J = ScalarSizeInBytes - 1; J >= 0; --J)
1068       ShuffleMask.push_back((I * ScalarSizeInBytes) + J);
1069 }
1070 
1071 SDValue VectorLegalizer::ExpandBSWAP(SDValue Op) {
1072   EVT VT = Op.getValueType();
1073 
1074   // Generate a byte wise shuffle mask for the BSWAP.
1075   SmallVector<int, 16> ShuffleMask;
1076   createBSWAPShuffleMask(VT, ShuffleMask);
1077   EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, ShuffleMask.size());
1078 
1079   // Only emit a shuffle if the mask is legal.
1080   if (!TLI.isShuffleMaskLegal(ShuffleMask, ByteVT))
1081     return DAG.UnrollVectorOp(Op.getNode());
1082 
1083   SDLoc DL(Op);
1084   Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
1085   Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT), ShuffleMask);
1086   return DAG.getNode(ISD::BITCAST, DL, VT, Op);
1087 }
1088 
1089 SDValue VectorLegalizer::ExpandBITREVERSE(SDValue Op) {
1090   EVT VT = Op.getValueType();
1091 
1092   // If we have the scalar operation, it's probably cheaper to unroll it.
1093   if (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, VT.getScalarType()))
1094     return DAG.UnrollVectorOp(Op.getNode());
1095 
1096   // If the vector element width is a whole number of bytes, test if its legal
1097   // to BSWAP shuffle the bytes and then perform the BITREVERSE on the byte
1098   // vector. This greatly reduces the number of bit shifts necessary.
1099   unsigned ScalarSizeInBits = VT.getScalarSizeInBits();
1100   if (ScalarSizeInBits > 8 && (ScalarSizeInBits % 8) == 0) {
1101     SmallVector<int, 16> BSWAPMask;
1102     createBSWAPShuffleMask(VT, BSWAPMask);
1103 
1104     EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, BSWAPMask.size());
1105     if (TLI.isShuffleMaskLegal(BSWAPMask, ByteVT) &&
1106         (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, ByteVT) ||
1107          (TLI.isOperationLegalOrCustom(ISD::SHL, ByteVT) &&
1108           TLI.isOperationLegalOrCustom(ISD::SRL, ByteVT) &&
1109           TLI.isOperationLegalOrCustomOrPromote(ISD::AND, ByteVT) &&
1110           TLI.isOperationLegalOrCustomOrPromote(ISD::OR, ByteVT)))) {
1111       SDLoc DL(Op);
1112       Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
1113       Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT),
1114                                 BSWAPMask);
1115       Op = DAG.getNode(ISD::BITREVERSE, DL, ByteVT, Op);
1116       return DAG.getNode(ISD::BITCAST, DL, VT, Op);
1117     }
1118   }
1119 
1120   // If we have the appropriate vector bit operations, it is better to use them
1121   // than unrolling and expanding each component.
1122   if (!TLI.isOperationLegalOrCustom(ISD::SHL, VT) ||
1123       !TLI.isOperationLegalOrCustom(ISD::SRL, VT) ||
1124       !TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
1125       !TLI.isOperationLegalOrCustomOrPromote(ISD::OR, VT))
1126     return DAG.UnrollVectorOp(Op.getNode());
1127 
1128   // Let LegalizeDAG handle this later.
1129   return Op;
1130 }
1131 
1132 SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) {
1133   // Implement VSELECT in terms of XOR, AND, OR
1134   // on platforms which do not support blend natively.
1135   SDLoc DL(Op);
1136 
1137   SDValue Mask = Op.getOperand(0);
1138   SDValue Op1 = Op.getOperand(1);
1139   SDValue Op2 = Op.getOperand(2);
1140 
1141   EVT VT = Mask.getValueType();
1142 
1143   // If we can't even use the basic vector operations of
1144   // AND,OR,XOR, we will have to scalarize the op.
1145   // Notice that the operation may be 'promoted' which means that it is
1146   // 'bitcasted' to another type which is handled.
1147   // This operation also isn't safe with AND, OR, XOR when the boolean
1148   // type is 0/1 as we need an all ones vector constant to mask with.
1149   // FIXME: Sign extend 1 to all ones if thats legal on the target.
1150   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
1151       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
1152       TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand ||
1153       TLI.getBooleanContents(Op1.getValueType()) !=
1154           TargetLowering::ZeroOrNegativeOneBooleanContent)
1155     return DAG.UnrollVectorOp(Op.getNode());
1156 
1157   // If the mask and the type are different sizes, unroll the vector op. This
1158   // can occur when getSetCCResultType returns something that is different in
1159   // size from the operand types. For example, v4i8 = select v4i32, v4i8, v4i8.
1160   if (VT.getSizeInBits() != Op1.getValueSizeInBits())
1161     return DAG.UnrollVectorOp(Op.getNode());
1162 
1163   // Bitcast the operands to be the same type as the mask.
1164   // This is needed when we select between FP types because
1165   // the mask is a vector of integers.
1166   Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
1167   Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
1168 
1169   SDValue AllOnes = DAG.getConstant(
1170     APInt::getAllOnesValue(VT.getScalarSizeInBits()), DL, VT);
1171   SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
1172 
1173   Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
1174   Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
1175   SDValue Val = DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
1176   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
1177 }
1178 
1179 SDValue VectorLegalizer::ExpandABS(SDValue Op) {
1180   // Attempt to expand using TargetLowering.
1181   SDValue Result;
1182   if (TLI.expandABS(Op.getNode(), Result, DAG))
1183     return Result;
1184 
1185   // Otherwise go ahead and unroll.
1186   return DAG.UnrollVectorOp(Op.getNode());
1187 }
1188 
1189 SDValue VectorLegalizer::ExpandFP_TO_UINT(SDValue Op) {
1190   // Attempt to expand using TargetLowering.
1191   SDValue Result, Chain;
1192   if (TLI.expandFP_TO_UINT(Op.getNode(), Result, Chain, DAG)) {
1193     if (Op.getNode()->isStrictFPOpcode())
1194       // Relink the chain
1195       DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Chain);
1196     return Result;
1197   }
1198 
1199   // Otherwise go ahead and unroll.
1200   return DAG.UnrollVectorOp(Op.getNode());
1201 }
1202 
1203 SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) {
1204   EVT VT = Op.getOperand(0).getValueType();
1205   SDLoc DL(Op);
1206 
1207   // Attempt to expand using TargetLowering.
1208   SDValue Result;
1209   if (TLI.expandUINT_TO_FP(Op.getNode(), Result, DAG))
1210     return Result;
1211 
1212   // Make sure that the SINT_TO_FP and SRL instructions are available.
1213   if (TLI.getOperationAction(ISD::SINT_TO_FP, VT) == TargetLowering::Expand ||
1214       TLI.getOperationAction(ISD::SRL,        VT) == TargetLowering::Expand)
1215     return DAG.UnrollVectorOp(Op.getNode());
1216 
1217   unsigned BW = VT.getScalarSizeInBits();
1218   assert((BW == 64 || BW == 32) &&
1219          "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
1220 
1221   SDValue HalfWord = DAG.getConstant(BW / 2, DL, VT);
1222 
1223   // Constants to clear the upper part of the word.
1224   // Notice that we can also use SHL+SHR, but using a constant is slightly
1225   // faster on x86.
1226   uint64_t HWMask = (BW == 64) ? 0x00000000FFFFFFFF : 0x0000FFFF;
1227   SDValue HalfWordMask = DAG.getConstant(HWMask, DL, VT);
1228 
1229   // Two to the power of half-word-size.
1230   SDValue TWOHW = DAG.getConstantFP(1ULL << (BW / 2), DL, Op.getValueType());
1231 
1232   // Clear upper part of LO, lower HI
1233   SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Op.getOperand(0), HalfWord);
1234   SDValue LO = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), HalfWordMask);
1235 
1236   // Convert hi and lo to floats
1237   // Convert the hi part back to the upper values
1238   // TODO: Can any fast-math-flags be set on these nodes?
1239   SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI);
1240           fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW);
1241   SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO);
1242 
1243   // Add the two halves
1244   return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO);
1245 }
1246 
1247 SDValue VectorLegalizer::ExpandFNEG(SDValue Op) {
1248   if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) {
1249     SDLoc DL(Op);
1250     SDValue Zero = DAG.getConstantFP(-0.0, DL, Op.getValueType());
1251     // TODO: If FNEG had fast-math-flags, they'd get propagated to this FSUB.
1252     return DAG.getNode(ISD::FSUB, DL, Op.getValueType(),
1253                        Zero, Op.getOperand(0));
1254   }
1255   return DAG.UnrollVectorOp(Op.getNode());
1256 }
1257 
1258 SDValue VectorLegalizer::ExpandFSUB(SDValue Op) {
1259   // For floating-point values, (a-b) is the same as a+(-b). If FNEG is legal,
1260   // we can defer this to operation legalization where it will be lowered as
1261   // a+(-b).
1262   EVT VT = Op.getValueType();
1263   if (TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
1264       TLI.isOperationLegalOrCustom(ISD::FADD, VT))
1265     return Op; // Defer to LegalizeDAG
1266 
1267   return DAG.UnrollVectorOp(Op.getNode());
1268 }
1269 
1270 SDValue VectorLegalizer::ExpandCTPOP(SDValue Op) {
1271   SDValue Result;
1272   if (TLI.expandCTPOP(Op.getNode(), Result, DAG))
1273     return Result;
1274 
1275   return DAG.UnrollVectorOp(Op.getNode());
1276 }
1277 
1278 SDValue VectorLegalizer::ExpandCTLZ(SDValue Op) {
1279   SDValue Result;
1280   if (TLI.expandCTLZ(Op.getNode(), Result, DAG))
1281     return Result;
1282 
1283   return DAG.UnrollVectorOp(Op.getNode());
1284 }
1285 
1286 SDValue VectorLegalizer::ExpandCTTZ(SDValue Op) {
1287   SDValue Result;
1288   if (TLI.expandCTTZ(Op.getNode(), Result, DAG))
1289     return Result;
1290 
1291   return DAG.UnrollVectorOp(Op.getNode());
1292 }
1293 
1294 SDValue VectorLegalizer::ExpandFunnelShift(SDValue Op) {
1295   SDValue Result;
1296   if (TLI.expandFunnelShift(Op.getNode(), Result, DAG))
1297     return Result;
1298 
1299   return DAG.UnrollVectorOp(Op.getNode());
1300 }
1301 
1302 SDValue VectorLegalizer::ExpandROT(SDValue Op) {
1303   SDValue Result;
1304   if (TLI.expandROT(Op.getNode(), Result, DAG))
1305     return Result;
1306 
1307   return DAG.UnrollVectorOp(Op.getNode());
1308 }
1309 
1310 SDValue VectorLegalizer::ExpandFMINNUM_FMAXNUM(SDValue Op) {
1311   if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Op.getNode(), DAG))
1312     return Expanded;
1313   return DAG.UnrollVectorOp(Op.getNode());
1314 }
1315 
1316 SDValue VectorLegalizer::ExpandUADDSUBO(SDValue Op) {
1317   SDValue Result, Overflow;
1318   TLI.expandUADDSUBO(Op.getNode(), Result, Overflow, DAG);
1319 
1320   if (Op.getResNo() == 0) {
1321     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Overflow));
1322     return Result;
1323   } else {
1324     AddLegalizedOperand(Op.getValue(0), LegalizeOp(Result));
1325     return Overflow;
1326   }
1327 }
1328 
1329 SDValue VectorLegalizer::ExpandSADDSUBO(SDValue Op) {
1330   SDValue Result, Overflow;
1331   TLI.expandSADDSUBO(Op.getNode(), Result, Overflow, DAG);
1332 
1333   if (Op.getResNo() == 0) {
1334     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Overflow));
1335     return Result;
1336   } else {
1337     AddLegalizedOperand(Op.getValue(0), LegalizeOp(Result));
1338     return Overflow;
1339   }
1340 }
1341 
1342 SDValue VectorLegalizer::ExpandMULO(SDValue Op) {
1343   SDValue Result, Overflow;
1344   if (!TLI.expandMULO(Op.getNode(), Result, Overflow, DAG))
1345     std::tie(Result, Overflow) = DAG.UnrollVectorOverflowOp(Op.getNode());
1346 
1347   if (Op.getResNo() == 0) {
1348     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Overflow));
1349     return Result;
1350   } else {
1351     AddLegalizedOperand(Op.getValue(0), LegalizeOp(Result));
1352     return Overflow;
1353   }
1354 }
1355 
1356 SDValue VectorLegalizer::ExpandAddSubSat(SDValue Op) {
1357   if (SDValue Expanded = TLI.expandAddSubSat(Op.getNode(), DAG))
1358     return Expanded;
1359   return DAG.UnrollVectorOp(Op.getNode());
1360 }
1361 
1362 SDValue VectorLegalizer::ExpandFixedPointMul(SDValue Op) {
1363   if (SDValue Expanded = TLI.expandFixedPointMul(Op.getNode(), DAG))
1364     return Expanded;
1365   return DAG.UnrollVectorOp(Op.getNode());
1366 }
1367 
1368 SDValue VectorLegalizer::ExpandStrictFPOp(SDValue Op) {
1369   EVT VT = Op.getValueType();
1370   EVT EltVT = VT.getVectorElementType();
1371   unsigned NumElems = VT.getVectorNumElements();
1372   unsigned NumOpers = Op.getNumOperands();
1373   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1374   EVT ValueVTs[] = {EltVT, MVT::Other};
1375   SDValue Chain = Op.getOperand(0);
1376   SDLoc dl(Op);
1377 
1378   SmallVector<SDValue, 32> OpValues;
1379   SmallVector<SDValue, 32> OpChains;
1380   for (unsigned i = 0; i < NumElems; ++i) {
1381     SmallVector<SDValue, 4> Opers;
1382     SDValue Idx = DAG.getConstant(i, dl,
1383                                   TLI.getVectorIdxTy(DAG.getDataLayout()));
1384 
1385     // The Chain is the first operand.
1386     Opers.push_back(Chain);
1387 
1388     // Now process the remaining operands.
1389     for (unsigned j = 1; j < NumOpers; ++j) {
1390       SDValue Oper = Op.getOperand(j);
1391       EVT OperVT = Oper.getValueType();
1392 
1393       if (OperVT.isVector())
1394         Oper = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1395                            OperVT.getVectorElementType(), Oper, Idx);
1396 
1397       Opers.push_back(Oper);
1398     }
1399 
1400     SDValue ScalarOp = DAG.getNode(Op->getOpcode(), dl, ValueVTs, Opers);
1401 
1402     OpValues.push_back(ScalarOp.getValue(0));
1403     OpChains.push_back(ScalarOp.getValue(1));
1404   }
1405 
1406   SDValue Result = DAG.getBuildVector(VT, dl, OpValues);
1407   SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OpChains);
1408 
1409   AddLegalizedOperand(Op.getValue(0), Result);
1410   AddLegalizedOperand(Op.getValue(1), NewChain);
1411 
1412   return Op.getResNo() ? NewChain : Result;
1413 }
1414 
1415 SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) {
1416   EVT VT = Op.getValueType();
1417   unsigned NumElems = VT.getVectorNumElements();
1418   EVT EltVT = VT.getVectorElementType();
1419   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2);
1420   EVT TmpEltVT = LHS.getValueType().getVectorElementType();
1421   SDLoc dl(Op);
1422   SmallVector<SDValue, 8> Ops(NumElems);
1423   for (unsigned i = 0; i < NumElems; ++i) {
1424     SDValue LHSElem = DAG.getNode(
1425         ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
1426         DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
1427     SDValue RHSElem = DAG.getNode(
1428         ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
1429         DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
1430     Ops[i] = DAG.getNode(ISD::SETCC, dl,
1431                          TLI.getSetCCResultType(DAG.getDataLayout(),
1432                                                 *DAG.getContext(), TmpEltVT),
1433                          LHSElem, RHSElem, CC);
1434     Ops[i] = DAG.getSelect(dl, EltVT, Ops[i],
1435                            DAG.getConstant(APInt::getAllOnesValue
1436                                            (EltVT.getSizeInBits()), dl, EltVT),
1437                            DAG.getConstant(0, dl, EltVT));
1438   }
1439   return DAG.getBuildVector(VT, dl, Ops);
1440 }
1441 
1442 bool SelectionDAG::LegalizeVectors() {
1443   return VectorLegalizer(*this).Run();
1444 }
1445