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