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