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