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