xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp (revision 1492c8c0d825d1dcd8a2b2975fe35e4269b0b7de)
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   case ISD::FP_TO_SINT_SAT:
459   case ISD::FP_TO_UINT_SAT:
460     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
461     break;
462   case ISD::SMULFIX:
463   case ISD::SMULFIXSAT:
464   case ISD::UMULFIX:
465   case ISD::UMULFIXSAT:
466   case ISD::SDIVFIX:
467   case ISD::SDIVFIXSAT:
468   case ISD::UDIVFIX:
469   case ISD::UDIVFIXSAT: {
470     unsigned Scale = Node->getConstantOperandVal(2);
471     Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
472                                               Node->getValueType(0), Scale);
473     break;
474   }
475   case ISD::SINT_TO_FP:
476   case ISD::UINT_TO_FP:
477   case ISD::VECREDUCE_ADD:
478   case ISD::VECREDUCE_MUL:
479   case ISD::VECREDUCE_AND:
480   case ISD::VECREDUCE_OR:
481   case ISD::VECREDUCE_XOR:
482   case ISD::VECREDUCE_SMAX:
483   case ISD::VECREDUCE_SMIN:
484   case ISD::VECREDUCE_UMAX:
485   case ISD::VECREDUCE_UMIN:
486   case ISD::VECREDUCE_FADD:
487   case ISD::VECREDUCE_FMUL:
488   case ISD::VECREDUCE_FMAX:
489   case ISD::VECREDUCE_FMIN:
490     Action = TLI.getOperationAction(Node->getOpcode(),
491                                     Node->getOperand(0).getValueType());
492     break;
493   case ISD::VECREDUCE_SEQ_FADD:
494   case ISD::VECREDUCE_SEQ_FMUL:
495     Action = TLI.getOperationAction(Node->getOpcode(),
496                                     Node->getOperand(1).getValueType());
497     break;
498   }
499 
500   LLVM_DEBUG(dbgs() << "\nLegalizing vector op: "; Node->dump(&DAG));
501 
502   SmallVector<SDValue, 8> ResultVals;
503   switch (Action) {
504   default: llvm_unreachable("This action is not supported yet!");
505   case TargetLowering::Promote:
506     LLVM_DEBUG(dbgs() << "Promoting\n");
507     Promote(Node, ResultVals);
508     assert(!ResultVals.empty() && "No results for promotion?");
509     break;
510   case TargetLowering::Legal:
511     LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
512     break;
513   case TargetLowering::Custom:
514     LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
515     if (LowerOperationWrapper(Node, ResultVals))
516       break;
517     LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
518     LLVM_FALLTHROUGH;
519   case TargetLowering::Expand:
520     LLVM_DEBUG(dbgs() << "Expanding\n");
521     Expand(Node, ResultVals);
522     break;
523   }
524 
525   if (ResultVals.empty())
526     return TranslateLegalizeResults(Op, Node);
527 
528   Changed = true;
529   return RecursivelyLegalizeResults(Op, ResultVals);
530 }
531 
532 // FIME: This is very similar to the X86 override of
533 // TargetLowering::LowerOperationWrapper. Can we merge them somehow?
534 bool VectorLegalizer::LowerOperationWrapper(SDNode *Node,
535                                             SmallVectorImpl<SDValue> &Results) {
536   SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
537 
538   if (!Res.getNode())
539     return false;
540 
541   if (Res == SDValue(Node, 0))
542     return true;
543 
544   // If the original node has one result, take the return value from
545   // LowerOperation as is. It might not be result number 0.
546   if (Node->getNumValues() == 1) {
547     Results.push_back(Res);
548     return true;
549   }
550 
551   // If the original node has multiple results, then the return node should
552   // have the same number of results.
553   assert((Node->getNumValues() == Res->getNumValues()) &&
554          "Lowering returned the wrong number of results!");
555 
556   // Places new result values base on N result number.
557   for (unsigned I = 0, E = Node->getNumValues(); I != E; ++I)
558     Results.push_back(Res.getValue(I));
559 
560   return true;
561 }
562 
563 void VectorLegalizer::Promote(SDNode *Node, SmallVectorImpl<SDValue> &Results) {
564   // For a few operations there is a specific concept for promotion based on
565   // the operand's type.
566   switch (Node->getOpcode()) {
567   case ISD::SINT_TO_FP:
568   case ISD::UINT_TO_FP:
569   case ISD::STRICT_SINT_TO_FP:
570   case ISD::STRICT_UINT_TO_FP:
571     // "Promote" the operation by extending the operand.
572     PromoteINT_TO_FP(Node, Results);
573     return;
574   case ISD::FP_TO_UINT:
575   case ISD::FP_TO_SINT:
576   case ISD::STRICT_FP_TO_UINT:
577   case ISD::STRICT_FP_TO_SINT:
578     // Promote the operation by extending the operand.
579     PromoteFP_TO_INT(Node, Results);
580     return;
581   case ISD::FP_ROUND:
582   case ISD::FP_EXTEND:
583     // These operations are used to do promotion so they can't be promoted
584     // themselves.
585     llvm_unreachable("Don't know how to promote this operation!");
586   }
587 
588   // There are currently two cases of vector promotion:
589   // 1) Bitcasting a vector of integers to a different type to a vector of the
590   //    same overall length. For example, x86 promotes ISD::AND v2i32 to v1i64.
591   // 2) Extending a vector of floats to a vector of the same number of larger
592   //    floats. For example, AArch64 promotes ISD::FADD on v4f16 to v4f32.
593   assert(Node->getNumValues() == 1 &&
594          "Can't promote a vector with multiple results!");
595   MVT VT = Node->getSimpleValueType(0);
596   MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
597   SDLoc dl(Node);
598   SmallVector<SDValue, 4> Operands(Node->getNumOperands());
599 
600   for (unsigned j = 0; j != Node->getNumOperands(); ++j) {
601     if (Node->getOperand(j).getValueType().isVector())
602       if (Node->getOperand(j)
603               .getValueType()
604               .getVectorElementType()
605               .isFloatingPoint() &&
606           NVT.isVector() && NVT.getVectorElementType().isFloatingPoint())
607         Operands[j] = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(j));
608       else
609         Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(j));
610     else
611       Operands[j] = Node->getOperand(j);
612   }
613 
614   SDValue Res =
615       DAG.getNode(Node->getOpcode(), dl, NVT, Operands, Node->getFlags());
616 
617   if ((VT.isFloatingPoint() && NVT.isFloatingPoint()) ||
618       (VT.isVector() && VT.getVectorElementType().isFloatingPoint() &&
619        NVT.isVector() && NVT.getVectorElementType().isFloatingPoint()))
620     Res = DAG.getNode(ISD::FP_ROUND, dl, VT, Res, DAG.getIntPtrConstant(0, dl));
621   else
622     Res = DAG.getNode(ISD::BITCAST, dl, VT, Res);
623 
624   Results.push_back(Res);
625 }
626 
627 void VectorLegalizer::PromoteINT_TO_FP(SDNode *Node,
628                                        SmallVectorImpl<SDValue> &Results) {
629   // INT_TO_FP operations may require the input operand be promoted even
630   // when the type is otherwise legal.
631   bool IsStrict = Node->isStrictFPOpcode();
632   MVT VT = Node->getOperand(IsStrict ? 1 : 0).getSimpleValueType();
633   MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
634   assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
635          "Vectors have different number of elements!");
636 
637   SDLoc dl(Node);
638   SmallVector<SDValue, 4> Operands(Node->getNumOperands());
639 
640   unsigned Opc = (Node->getOpcode() == ISD::UINT_TO_FP ||
641                   Node->getOpcode() == ISD::STRICT_UINT_TO_FP)
642                      ? ISD::ZERO_EXTEND
643                      : ISD::SIGN_EXTEND;
644   for (unsigned j = 0; j != Node->getNumOperands(); ++j) {
645     if (Node->getOperand(j).getValueType().isVector())
646       Operands[j] = DAG.getNode(Opc, dl, NVT, Node->getOperand(j));
647     else
648       Operands[j] = Node->getOperand(j);
649   }
650 
651   if (IsStrict) {
652     SDValue Res = DAG.getNode(Node->getOpcode(), dl,
653                               {Node->getValueType(0), MVT::Other}, Operands);
654     Results.push_back(Res);
655     Results.push_back(Res.getValue(1));
656     return;
657   }
658 
659   SDValue Res =
660       DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Operands);
661   Results.push_back(Res);
662 }
663 
664 // For FP_TO_INT we promote the result type to a vector type with wider
665 // elements and then truncate the result.  This is different from the default
666 // PromoteVector which uses bitcast to promote thus assumning that the
667 // promoted vector type has the same overall size.
668 void VectorLegalizer::PromoteFP_TO_INT(SDNode *Node,
669                                        SmallVectorImpl<SDValue> &Results) {
670   MVT VT = Node->getSimpleValueType(0);
671   MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
672   bool IsStrict = Node->isStrictFPOpcode();
673   assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
674          "Vectors have different number of elements!");
675 
676   unsigned NewOpc = Node->getOpcode();
677   // Change FP_TO_UINT to FP_TO_SINT if possible.
678   // TODO: Should we only do this if FP_TO_UINT itself isn't legal?
679   if (NewOpc == ISD::FP_TO_UINT &&
680       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
681     NewOpc = ISD::FP_TO_SINT;
682 
683   if (NewOpc == ISD::STRICT_FP_TO_UINT &&
684       TLI.isOperationLegalOrCustom(ISD::STRICT_FP_TO_SINT, NVT))
685     NewOpc = ISD::STRICT_FP_TO_SINT;
686 
687   SDLoc dl(Node);
688   SDValue Promoted, Chain;
689   if (IsStrict) {
690     Promoted = DAG.getNode(NewOpc, dl, {NVT, MVT::Other},
691                            {Node->getOperand(0), Node->getOperand(1)});
692     Chain = Promoted.getValue(1);
693   } else
694     Promoted = DAG.getNode(NewOpc, dl, NVT, Node->getOperand(0));
695 
696   // Assert that the converted value fits in the original type.  If it doesn't
697   // (eg: because the value being converted is too big), then the result of the
698   // original operation was undefined anyway, so the assert is still correct.
699   if (Node->getOpcode() == ISD::FP_TO_UINT ||
700       Node->getOpcode() == ISD::STRICT_FP_TO_UINT)
701     NewOpc = ISD::AssertZext;
702   else
703     NewOpc = ISD::AssertSext;
704 
705   Promoted = DAG.getNode(NewOpc, dl, NVT, Promoted,
706                          DAG.getValueType(VT.getScalarType()));
707   Promoted = DAG.getNode(ISD::TRUNCATE, dl, VT, Promoted);
708   Results.push_back(Promoted);
709   if (IsStrict)
710     Results.push_back(Chain);
711 }
712 
713 std::pair<SDValue, SDValue> VectorLegalizer::ExpandLoad(SDNode *N) {
714   LoadSDNode *LD = cast<LoadSDNode>(N);
715   return TLI.scalarizeVectorLoad(LD, DAG);
716 }
717 
718 SDValue VectorLegalizer::ExpandStore(SDNode *N) {
719   StoreSDNode *ST = cast<StoreSDNode>(N);
720   SDValue TF = TLI.scalarizeVectorStore(ST, DAG);
721   return TF;
722 }
723 
724 void VectorLegalizer::Expand(SDNode *Node, SmallVectorImpl<SDValue> &Results) {
725   SDValue Tmp;
726   switch (Node->getOpcode()) {
727   case ISD::MERGE_VALUES:
728     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
729       Results.push_back(Node->getOperand(i));
730     return;
731   case ISD::SIGN_EXTEND_INREG:
732     Results.push_back(ExpandSEXTINREG(Node));
733     return;
734   case ISD::ANY_EXTEND_VECTOR_INREG:
735     Results.push_back(ExpandANY_EXTEND_VECTOR_INREG(Node));
736     return;
737   case ISD::SIGN_EXTEND_VECTOR_INREG:
738     Results.push_back(ExpandSIGN_EXTEND_VECTOR_INREG(Node));
739     return;
740   case ISD::ZERO_EXTEND_VECTOR_INREG:
741     Results.push_back(ExpandZERO_EXTEND_VECTOR_INREG(Node));
742     return;
743   case ISD::BSWAP:
744     Results.push_back(ExpandBSWAP(Node));
745     return;
746   case ISD::VSELECT:
747     Results.push_back(ExpandVSELECT(Node));
748     return;
749   case ISD::SELECT:
750     Results.push_back(ExpandSELECT(Node));
751     return;
752   case ISD::FP_TO_UINT:
753     ExpandFP_TO_UINT(Node, Results);
754     return;
755   case ISD::UINT_TO_FP:
756     ExpandUINT_TO_FLOAT(Node, Results);
757     return;
758   case ISD::FNEG:
759     Results.push_back(ExpandFNEG(Node));
760     return;
761   case ISD::FSUB:
762     ExpandFSUB(Node, Results);
763     return;
764   case ISD::SETCC:
765     Results.push_back(UnrollVSETCC(Node));
766     return;
767   case ISD::ABS:
768     if (TLI.expandABS(Node, Tmp, DAG)) {
769       Results.push_back(Tmp);
770       return;
771     }
772     break;
773   case ISD::BITREVERSE:
774     ExpandBITREVERSE(Node, Results);
775     return;
776   case ISD::CTPOP:
777     if (TLI.expandCTPOP(Node, Tmp, DAG)) {
778       Results.push_back(Tmp);
779       return;
780     }
781     break;
782   case ISD::CTLZ:
783   case ISD::CTLZ_ZERO_UNDEF:
784     if (TLI.expandCTLZ(Node, Tmp, DAG)) {
785       Results.push_back(Tmp);
786       return;
787     }
788     break;
789   case ISD::CTTZ:
790   case ISD::CTTZ_ZERO_UNDEF:
791     if (TLI.expandCTTZ(Node, Tmp, DAG)) {
792       Results.push_back(Tmp);
793       return;
794     }
795     break;
796   case ISD::FSHL:
797   case ISD::FSHR:
798     if (TLI.expandFunnelShift(Node, Tmp, DAG)) {
799       Results.push_back(Tmp);
800       return;
801     }
802     break;
803   case ISD::ROTL:
804   case ISD::ROTR:
805     if (TLI.expandROT(Node, false /*AllowVectorOps*/, Tmp, DAG)) {
806       Results.push_back(Tmp);
807       return;
808     }
809     break;
810   case ISD::FMINNUM:
811   case ISD::FMAXNUM:
812     if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Node, DAG)) {
813       Results.push_back(Expanded);
814       return;
815     }
816     break;
817   case ISD::SMIN:
818   case ISD::SMAX:
819   case ISD::UMIN:
820   case ISD::UMAX:
821     if (SDValue Expanded = TLI.expandIntMINMAX(Node, DAG)) {
822       Results.push_back(Expanded);
823       return;
824     }
825     break;
826   case ISD::UADDO:
827   case ISD::USUBO:
828     ExpandUADDSUBO(Node, Results);
829     return;
830   case ISD::SADDO:
831   case ISD::SSUBO:
832     ExpandSADDSUBO(Node, Results);
833     return;
834   case ISD::UMULO:
835   case ISD::SMULO:
836     ExpandMULO(Node, Results);
837     return;
838   case ISD::USUBSAT:
839   case ISD::SSUBSAT:
840   case ISD::UADDSAT:
841   case ISD::SADDSAT:
842     if (SDValue Expanded = TLI.expandAddSubSat(Node, DAG)) {
843       Results.push_back(Expanded);
844       return;
845     }
846     break;
847   case ISD::SMULFIX:
848   case ISD::UMULFIX:
849     if (SDValue Expanded = TLI.expandFixedPointMul(Node, DAG)) {
850       Results.push_back(Expanded);
851       return;
852     }
853     break;
854   case ISD::SMULFIXSAT:
855   case ISD::UMULFIXSAT:
856     // FIXME: We do not expand SMULFIXSAT/UMULFIXSAT here yet, not sure exactly
857     // why. Maybe it results in worse codegen compared to the unroll for some
858     // targets? This should probably be investigated. And if we still prefer to
859     // unroll an explanation could be helpful.
860     break;
861   case ISD::SDIVFIX:
862   case ISD::UDIVFIX:
863     ExpandFixedPointDiv(Node, Results);
864     return;
865   case ISD::SDIVFIXSAT:
866   case ISD::UDIVFIXSAT:
867     break;
868 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
869   case ISD::STRICT_##DAGN:
870 #include "llvm/IR/ConstrainedOps.def"
871     ExpandStrictFPOp(Node, Results);
872     return;
873   case ISD::VECREDUCE_ADD:
874   case ISD::VECREDUCE_MUL:
875   case ISD::VECREDUCE_AND:
876   case ISD::VECREDUCE_OR:
877   case ISD::VECREDUCE_XOR:
878   case ISD::VECREDUCE_SMAX:
879   case ISD::VECREDUCE_SMIN:
880   case ISD::VECREDUCE_UMAX:
881   case ISD::VECREDUCE_UMIN:
882   case ISD::VECREDUCE_FADD:
883   case ISD::VECREDUCE_FMUL:
884   case ISD::VECREDUCE_FMAX:
885   case ISD::VECREDUCE_FMIN:
886     Results.push_back(TLI.expandVecReduce(Node, DAG));
887     return;
888   case ISD::VECREDUCE_SEQ_FADD:
889   case ISD::VECREDUCE_SEQ_FMUL:
890     Results.push_back(TLI.expandVecReduceSeq(Node, DAG));
891     return;
892   case ISD::SREM:
893   case ISD::UREM:
894     ExpandREM(Node, Results);
895     return;
896   }
897 
898   Results.push_back(DAG.UnrollVectorOp(Node));
899 }
900 
901 SDValue VectorLegalizer::ExpandSELECT(SDNode *Node) {
902   // Lower a select instruction where the condition is a scalar and the
903   // operands are vectors. Lower this select to VSELECT and implement it
904   // using XOR AND OR. The selector bit is broadcasted.
905   EVT VT = Node->getValueType(0);
906   SDLoc DL(Node);
907 
908   SDValue Mask = Node->getOperand(0);
909   SDValue Op1 = Node->getOperand(1);
910   SDValue Op2 = Node->getOperand(2);
911 
912   assert(VT.isVector() && !Mask.getValueType().isVector()
913          && Op1.getValueType() == Op2.getValueType() && "Invalid type");
914 
915   // If we can't even use the basic vector operations of
916   // AND,OR,XOR, we will have to scalarize the op.
917   // Notice that the operation may be 'promoted' which means that it is
918   // 'bitcasted' to another type which is handled.
919   // Also, we need to be able to construct a splat vector using BUILD_VECTOR.
920   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
921       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
922       TLI.getOperationAction(ISD::OR,  VT) == TargetLowering::Expand ||
923       TLI.getOperationAction(ISD::BUILD_VECTOR,  VT) == TargetLowering::Expand)
924     return DAG.UnrollVectorOp(Node);
925 
926   // Generate a mask operand.
927   EVT MaskTy = VT.changeVectorElementTypeToInteger();
928 
929   // What is the size of each element in the vector mask.
930   EVT BitTy = MaskTy.getScalarType();
931 
932   Mask = DAG.getSelect(DL, BitTy, Mask,
933           DAG.getConstant(APInt::getAllOnesValue(BitTy.getSizeInBits()), DL,
934                           BitTy),
935           DAG.getConstant(0, DL, BitTy));
936 
937   // Broadcast the mask so that the entire vector is all-one or all zero.
938   Mask = DAG.getSplatBuildVector(MaskTy, DL, Mask);
939 
940   // Bitcast the operands to be the same type as the mask.
941   // This is needed when we select between FP types because
942   // the mask is a vector of integers.
943   Op1 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op1);
944   Op2 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op2);
945 
946   SDValue AllOnes = DAG.getConstant(
947             APInt::getAllOnesValue(BitTy.getSizeInBits()), DL, MaskTy);
948   SDValue NotMask = DAG.getNode(ISD::XOR, DL, MaskTy, Mask, AllOnes);
949 
950   Op1 = DAG.getNode(ISD::AND, DL, MaskTy, Op1, Mask);
951   Op2 = DAG.getNode(ISD::AND, DL, MaskTy, Op2, NotMask);
952   SDValue Val = DAG.getNode(ISD::OR, DL, MaskTy, Op1, Op2);
953   return DAG.getNode(ISD::BITCAST, DL, Node->getValueType(0), Val);
954 }
955 
956 SDValue VectorLegalizer::ExpandSEXTINREG(SDNode *Node) {
957   EVT VT = Node->getValueType(0);
958 
959   // Make sure that the SRA and SHL instructions are available.
960   if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Expand ||
961       TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Expand)
962     return DAG.UnrollVectorOp(Node);
963 
964   SDLoc DL(Node);
965   EVT OrigTy = cast<VTSDNode>(Node->getOperand(1))->getVT();
966 
967   unsigned BW = VT.getScalarSizeInBits();
968   unsigned OrigBW = OrigTy.getScalarSizeInBits();
969   SDValue ShiftSz = DAG.getConstant(BW - OrigBW, DL, VT);
970 
971   SDValue Op = DAG.getNode(ISD::SHL, DL, VT, Node->getOperand(0), ShiftSz);
972   return DAG.getNode(ISD::SRA, DL, VT, Op, ShiftSz);
973 }
974 
975 // Generically expand a vector anyext in register to a shuffle of the relevant
976 // lanes into the appropriate locations, with other lanes left undef.
977 SDValue VectorLegalizer::ExpandANY_EXTEND_VECTOR_INREG(SDNode *Node) {
978   SDLoc DL(Node);
979   EVT VT = Node->getValueType(0);
980   int NumElements = VT.getVectorNumElements();
981   SDValue Src = Node->getOperand(0);
982   EVT SrcVT = Src.getValueType();
983   int NumSrcElements = SrcVT.getVectorNumElements();
984 
985   // *_EXTEND_VECTOR_INREG SrcVT can be smaller than VT - so insert the vector
986   // into a larger vector type.
987   if (SrcVT.bitsLE(VT)) {
988     assert((VT.getSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
989            "ANY_EXTEND_VECTOR_INREG vector size mismatch");
990     NumSrcElements = VT.getSizeInBits() / SrcVT.getScalarSizeInBits();
991     SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
992                              NumSrcElements);
993     Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcVT, DAG.getUNDEF(SrcVT),
994                       Src, DAG.getVectorIdxConstant(0, DL));
995   }
996 
997   // Build a base mask of undef shuffles.
998   SmallVector<int, 16> ShuffleMask;
999   ShuffleMask.resize(NumSrcElements, -1);
1000 
1001   // Place the extended lanes into the correct locations.
1002   int ExtLaneScale = NumSrcElements / NumElements;
1003   int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
1004   for (int i = 0; i < NumElements; ++i)
1005     ShuffleMask[i * ExtLaneScale + EndianOffset] = i;
1006 
1007   return DAG.getNode(
1008       ISD::BITCAST, DL, VT,
1009       DAG.getVectorShuffle(SrcVT, DL, Src, DAG.getUNDEF(SrcVT), ShuffleMask));
1010 }
1011 
1012 SDValue VectorLegalizer::ExpandSIGN_EXTEND_VECTOR_INREG(SDNode *Node) {
1013   SDLoc DL(Node);
1014   EVT VT = Node->getValueType(0);
1015   SDValue Src = Node->getOperand(0);
1016   EVT SrcVT = Src.getValueType();
1017 
1018   // First build an any-extend node which can be legalized above when we
1019   // recurse through it.
1020   SDValue Op = DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Src);
1021 
1022   // Now we need sign extend. Do this by shifting the elements. Even if these
1023   // aren't legal operations, they have a better chance of being legalized
1024   // without full scalarization than the sign extension does.
1025   unsigned EltWidth = VT.getScalarSizeInBits();
1026   unsigned SrcEltWidth = SrcVT.getScalarSizeInBits();
1027   SDValue ShiftAmount = DAG.getConstant(EltWidth - SrcEltWidth, DL, VT);
1028   return DAG.getNode(ISD::SRA, DL, VT,
1029                      DAG.getNode(ISD::SHL, DL, VT, Op, ShiftAmount),
1030                      ShiftAmount);
1031 }
1032 
1033 // Generically expand a vector zext in register to a shuffle of the relevant
1034 // lanes into the appropriate locations, a blend of zero into the high bits,
1035 // and a bitcast to the wider element type.
1036 SDValue VectorLegalizer::ExpandZERO_EXTEND_VECTOR_INREG(SDNode *Node) {
1037   SDLoc DL(Node);
1038   EVT VT = Node->getValueType(0);
1039   int NumElements = VT.getVectorNumElements();
1040   SDValue Src = Node->getOperand(0);
1041   EVT SrcVT = Src.getValueType();
1042   int NumSrcElements = SrcVT.getVectorNumElements();
1043 
1044   // *_EXTEND_VECTOR_INREG SrcVT can be smaller than VT - so insert the vector
1045   // into a larger vector type.
1046   if (SrcVT.bitsLE(VT)) {
1047     assert((VT.getSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
1048            "ZERO_EXTEND_VECTOR_INREG vector size mismatch");
1049     NumSrcElements = VT.getSizeInBits() / SrcVT.getScalarSizeInBits();
1050     SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
1051                              NumSrcElements);
1052     Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcVT, DAG.getUNDEF(SrcVT),
1053                       Src, DAG.getVectorIdxConstant(0, DL));
1054   }
1055 
1056   // Build up a zero vector to blend into this one.
1057   SDValue Zero = DAG.getConstant(0, DL, SrcVT);
1058 
1059   // Shuffle the incoming lanes into the correct position, and pull all other
1060   // lanes from the zero vector.
1061   SmallVector<int, 16> ShuffleMask;
1062   ShuffleMask.reserve(NumSrcElements);
1063   for (int i = 0; i < NumSrcElements; ++i)
1064     ShuffleMask.push_back(i);
1065 
1066   int ExtLaneScale = NumSrcElements / NumElements;
1067   int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
1068   for (int i = 0; i < NumElements; ++i)
1069     ShuffleMask[i * ExtLaneScale + EndianOffset] = NumSrcElements + i;
1070 
1071   return DAG.getNode(ISD::BITCAST, DL, VT,
1072                      DAG.getVectorShuffle(SrcVT, DL, Zero, Src, ShuffleMask));
1073 }
1074 
1075 static void createBSWAPShuffleMask(EVT VT, SmallVectorImpl<int> &ShuffleMask) {
1076   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
1077   for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I)
1078     for (int J = ScalarSizeInBytes - 1; J >= 0; --J)
1079       ShuffleMask.push_back((I * ScalarSizeInBytes) + J);
1080 }
1081 
1082 SDValue VectorLegalizer::ExpandBSWAP(SDNode *Node) {
1083   EVT VT = Node->getValueType(0);
1084 
1085   // Generate a byte wise shuffle mask for the BSWAP.
1086   SmallVector<int, 16> ShuffleMask;
1087   createBSWAPShuffleMask(VT, ShuffleMask);
1088   EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, ShuffleMask.size());
1089 
1090   // Only emit a shuffle if the mask is legal.
1091   if (!TLI.isShuffleMaskLegal(ShuffleMask, ByteVT))
1092     return DAG.UnrollVectorOp(Node);
1093 
1094   SDLoc DL(Node);
1095   SDValue Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Node->getOperand(0));
1096   Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT), ShuffleMask);
1097   return DAG.getNode(ISD::BITCAST, DL, VT, Op);
1098 }
1099 
1100 void VectorLegalizer::ExpandBITREVERSE(SDNode *Node,
1101                                        SmallVectorImpl<SDValue> &Results) {
1102   EVT VT = Node->getValueType(0);
1103 
1104   // If we have the scalar operation, it's probably cheaper to unroll it.
1105   if (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, VT.getScalarType())) {
1106     SDValue Tmp = DAG.UnrollVectorOp(Node);
1107     Results.push_back(Tmp);
1108     return;
1109   }
1110 
1111   // If the vector element width is a whole number of bytes, test if its legal
1112   // to BSWAP shuffle the bytes and then perform the BITREVERSE on the byte
1113   // vector. This greatly reduces the number of bit shifts necessary.
1114   unsigned ScalarSizeInBits = VT.getScalarSizeInBits();
1115   if (ScalarSizeInBits > 8 && (ScalarSizeInBits % 8) == 0) {
1116     SmallVector<int, 16> BSWAPMask;
1117     createBSWAPShuffleMask(VT, BSWAPMask);
1118 
1119     EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, BSWAPMask.size());
1120     if (TLI.isShuffleMaskLegal(BSWAPMask, ByteVT) &&
1121         (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, ByteVT) ||
1122          (TLI.isOperationLegalOrCustom(ISD::SHL, ByteVT) &&
1123           TLI.isOperationLegalOrCustom(ISD::SRL, ByteVT) &&
1124           TLI.isOperationLegalOrCustomOrPromote(ISD::AND, ByteVT) &&
1125           TLI.isOperationLegalOrCustomOrPromote(ISD::OR, ByteVT)))) {
1126       SDLoc DL(Node);
1127       SDValue Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Node->getOperand(0));
1128       Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT),
1129                                 BSWAPMask);
1130       Op = DAG.getNode(ISD::BITREVERSE, DL, ByteVT, Op);
1131       Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
1132       Results.push_back(Op);
1133       return;
1134     }
1135   }
1136 
1137   // If we have the appropriate vector bit operations, it is better to use them
1138   // than unrolling and expanding each component.
1139   if (TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
1140       TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
1141       TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT) &&
1142       TLI.isOperationLegalOrCustomOrPromote(ISD::OR, VT))
1143     // Let LegalizeDAG handle this later.
1144     return;
1145 
1146   // Otherwise unroll.
1147   SDValue Tmp = DAG.UnrollVectorOp(Node);
1148   Results.push_back(Tmp);
1149 }
1150 
1151 SDValue VectorLegalizer::ExpandVSELECT(SDNode *Node) {
1152   // Implement VSELECT in terms of XOR, AND, OR
1153   // on platforms which do not support blend natively.
1154   SDLoc DL(Node);
1155 
1156   SDValue Mask = Node->getOperand(0);
1157   SDValue Op1 = Node->getOperand(1);
1158   SDValue Op2 = Node->getOperand(2);
1159 
1160   EVT VT = Mask.getValueType();
1161 
1162   // If we can't even use the basic vector operations of
1163   // AND,OR,XOR, we will have to scalarize the op.
1164   // Notice that the operation may be 'promoted' which means that it is
1165   // 'bitcasted' to another type which is handled.
1166   // This operation also isn't safe with AND, OR, XOR when the boolean
1167   // type is 0/1 as we need an all ones vector constant to mask with.
1168   // FIXME: Sign extend 1 to all ones if thats legal on the target.
1169   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
1170       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
1171       TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand ||
1172       TLI.getBooleanContents(Op1.getValueType()) !=
1173           TargetLowering::ZeroOrNegativeOneBooleanContent)
1174     return DAG.UnrollVectorOp(Node);
1175 
1176   // If the mask and the type are different sizes, unroll the vector op. This
1177   // can occur when getSetCCResultType returns something that is different in
1178   // size from the operand types. For example, v4i8 = select v4i32, v4i8, v4i8.
1179   if (VT.getSizeInBits() != Op1.getValueSizeInBits())
1180     return DAG.UnrollVectorOp(Node);
1181 
1182   // Bitcast the operands to be the same type as the mask.
1183   // This is needed when we select between FP types because
1184   // the mask is a vector of integers.
1185   Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
1186   Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
1187 
1188   SDValue AllOnes = DAG.getConstant(
1189     APInt::getAllOnesValue(VT.getScalarSizeInBits()), DL, VT);
1190   SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
1191 
1192   Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
1193   Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
1194   SDValue Val = DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
1195   return DAG.getNode(ISD::BITCAST, DL, Node->getValueType(0), Val);
1196 }
1197 
1198 void VectorLegalizer::ExpandFP_TO_UINT(SDNode *Node,
1199                                        SmallVectorImpl<SDValue> &Results) {
1200   // Attempt to expand using TargetLowering.
1201   SDValue Result, Chain;
1202   if (TLI.expandFP_TO_UINT(Node, Result, Chain, DAG)) {
1203     Results.push_back(Result);
1204     if (Node->isStrictFPOpcode())
1205       Results.push_back(Chain);
1206     return;
1207   }
1208 
1209   // Otherwise go ahead and unroll.
1210   if (Node->isStrictFPOpcode()) {
1211     UnrollStrictFPOp(Node, Results);
1212     return;
1213   }
1214 
1215   Results.push_back(DAG.UnrollVectorOp(Node));
1216 }
1217 
1218 void VectorLegalizer::ExpandUINT_TO_FLOAT(SDNode *Node,
1219                                           SmallVectorImpl<SDValue> &Results) {
1220   bool IsStrict = Node->isStrictFPOpcode();
1221   unsigned OpNo = IsStrict ? 1 : 0;
1222   SDValue Src = Node->getOperand(OpNo);
1223   EVT VT = Src.getValueType();
1224   SDLoc DL(Node);
1225 
1226   // Attempt to expand using TargetLowering.
1227   SDValue Result;
1228   SDValue Chain;
1229   if (TLI.expandUINT_TO_FP(Node, Result, Chain, DAG)) {
1230     Results.push_back(Result);
1231     if (IsStrict)
1232       Results.push_back(Chain);
1233     return;
1234   }
1235 
1236   // Make sure that the SINT_TO_FP and SRL instructions are available.
1237   if (((!IsStrict && TLI.getOperationAction(ISD::SINT_TO_FP, VT) ==
1238                          TargetLowering::Expand) ||
1239        (IsStrict && TLI.getOperationAction(ISD::STRICT_SINT_TO_FP, VT) ==
1240                         TargetLowering::Expand)) ||
1241       TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Expand) {
1242     if (IsStrict) {
1243       UnrollStrictFPOp(Node, Results);
1244       return;
1245     }
1246 
1247     Results.push_back(DAG.UnrollVectorOp(Node));
1248     return;
1249   }
1250 
1251   unsigned BW = VT.getScalarSizeInBits();
1252   assert((BW == 64 || BW == 32) &&
1253          "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
1254 
1255   SDValue HalfWord = DAG.getConstant(BW / 2, DL, VT);
1256 
1257   // Constants to clear the upper part of the word.
1258   // Notice that we can also use SHL+SHR, but using a constant is slightly
1259   // faster on x86.
1260   uint64_t HWMask = (BW == 64) ? 0x00000000FFFFFFFF : 0x0000FFFF;
1261   SDValue HalfWordMask = DAG.getConstant(HWMask, DL, VT);
1262 
1263   // Two to the power of half-word-size.
1264   SDValue TWOHW =
1265       DAG.getConstantFP(1ULL << (BW / 2), DL, Node->getValueType(0));
1266 
1267   // Clear upper part of LO, lower HI
1268   SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Src, HalfWord);
1269   SDValue LO = DAG.getNode(ISD::AND, DL, VT, Src, HalfWordMask);
1270 
1271   if (IsStrict) {
1272     // Convert hi and lo to floats
1273     // Convert the hi part back to the upper values
1274     // TODO: Can any fast-math-flags be set on these nodes?
1275     SDValue fHI = DAG.getNode(ISD::STRICT_SINT_TO_FP, DL,
1276                               {Node->getValueType(0), MVT::Other},
1277                               {Node->getOperand(0), HI});
1278     fHI = DAG.getNode(ISD::STRICT_FMUL, DL, {Node->getValueType(0), MVT::Other},
1279                       {fHI.getValue(1), fHI, TWOHW});
1280     SDValue fLO = DAG.getNode(ISD::STRICT_SINT_TO_FP, DL,
1281                               {Node->getValueType(0), MVT::Other},
1282                               {Node->getOperand(0), LO});
1283 
1284     SDValue TF = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, fHI.getValue(1),
1285                              fLO.getValue(1));
1286 
1287     // Add the two halves
1288     SDValue Result =
1289         DAG.getNode(ISD::STRICT_FADD, DL, {Node->getValueType(0), MVT::Other},
1290                     {TF, fHI, fLO});
1291 
1292     Results.push_back(Result);
1293     Results.push_back(Result.getValue(1));
1294     return;
1295   }
1296 
1297   // Convert hi and lo to floats
1298   // Convert the hi part back to the upper values
1299   // TODO: Can any fast-math-flags be set on these nodes?
1300   SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Node->getValueType(0), HI);
1301   fHI = DAG.getNode(ISD::FMUL, DL, Node->getValueType(0), fHI, TWOHW);
1302   SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Node->getValueType(0), LO);
1303 
1304   // Add the two halves
1305   Results.push_back(
1306       DAG.getNode(ISD::FADD, DL, Node->getValueType(0), fHI, fLO));
1307 }
1308 
1309 SDValue VectorLegalizer::ExpandFNEG(SDNode *Node) {
1310   if (TLI.isOperationLegalOrCustom(ISD::FSUB, Node->getValueType(0))) {
1311     SDLoc DL(Node);
1312     SDValue Zero = DAG.getConstantFP(-0.0, DL, Node->getValueType(0));
1313     // TODO: If FNEG had fast-math-flags, they'd get propagated to this FSUB.
1314     return DAG.getNode(ISD::FSUB, DL, Node->getValueType(0), Zero,
1315                        Node->getOperand(0));
1316   }
1317   return DAG.UnrollVectorOp(Node);
1318 }
1319 
1320 void VectorLegalizer::ExpandFSUB(SDNode *Node,
1321                                  SmallVectorImpl<SDValue> &Results) {
1322   // For floating-point values, (a-b) is the same as a+(-b). If FNEG is legal,
1323   // we can defer this to operation legalization where it will be lowered as
1324   // a+(-b).
1325   EVT VT = Node->getValueType(0);
1326   if (TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
1327       TLI.isOperationLegalOrCustom(ISD::FADD, VT))
1328     return; // Defer to LegalizeDAG
1329 
1330   SDValue Tmp = DAG.UnrollVectorOp(Node);
1331   Results.push_back(Tmp);
1332 }
1333 
1334 void VectorLegalizer::ExpandUADDSUBO(SDNode *Node,
1335                                      SmallVectorImpl<SDValue> &Results) {
1336   SDValue Result, Overflow;
1337   TLI.expandUADDSUBO(Node, Result, Overflow, DAG);
1338   Results.push_back(Result);
1339   Results.push_back(Overflow);
1340 }
1341 
1342 void VectorLegalizer::ExpandSADDSUBO(SDNode *Node,
1343                                      SmallVectorImpl<SDValue> &Results) {
1344   SDValue Result, Overflow;
1345   TLI.expandSADDSUBO(Node, Result, Overflow, DAG);
1346   Results.push_back(Result);
1347   Results.push_back(Overflow);
1348 }
1349 
1350 void VectorLegalizer::ExpandMULO(SDNode *Node,
1351                                  SmallVectorImpl<SDValue> &Results) {
1352   SDValue Result, Overflow;
1353   if (!TLI.expandMULO(Node, Result, Overflow, DAG))
1354     std::tie(Result, Overflow) = DAG.UnrollVectorOverflowOp(Node);
1355 
1356   Results.push_back(Result);
1357   Results.push_back(Overflow);
1358 }
1359 
1360 void VectorLegalizer::ExpandFixedPointDiv(SDNode *Node,
1361                                           SmallVectorImpl<SDValue> &Results) {
1362   SDNode *N = Node;
1363   if (SDValue Expanded = TLI.expandFixedPointDiv(N->getOpcode(), SDLoc(N),
1364           N->getOperand(0), N->getOperand(1), N->getConstantOperandVal(2), DAG))
1365     Results.push_back(Expanded);
1366 }
1367 
1368 void VectorLegalizer::ExpandStrictFPOp(SDNode *Node,
1369                                        SmallVectorImpl<SDValue> &Results) {
1370   if (Node->getOpcode() == ISD::STRICT_UINT_TO_FP) {
1371     ExpandUINT_TO_FLOAT(Node, Results);
1372     return;
1373   }
1374   if (Node->getOpcode() == ISD::STRICT_FP_TO_UINT) {
1375     ExpandFP_TO_UINT(Node, Results);
1376     return;
1377   }
1378 
1379   UnrollStrictFPOp(Node, Results);
1380 }
1381 
1382 void VectorLegalizer::ExpandREM(SDNode *Node,
1383                                 SmallVectorImpl<SDValue> &Results) {
1384   assert((Node->getOpcode() == ISD::SREM || Node->getOpcode() == ISD::UREM) &&
1385          "Expected REM node");
1386 
1387   SDValue Result;
1388   if (!TLI.expandREM(Node, Result, DAG))
1389     Result = DAG.UnrollVectorOp(Node);
1390   Results.push_back(Result);
1391 }
1392 
1393 void VectorLegalizer::UnrollStrictFPOp(SDNode *Node,
1394                                        SmallVectorImpl<SDValue> &Results) {
1395   EVT VT = Node->getValueType(0);
1396   EVT EltVT = VT.getVectorElementType();
1397   unsigned NumElems = VT.getVectorNumElements();
1398   unsigned NumOpers = Node->getNumOperands();
1399   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1400 
1401   EVT TmpEltVT = EltVT;
1402   if (Node->getOpcode() == ISD::STRICT_FSETCC ||
1403       Node->getOpcode() == ISD::STRICT_FSETCCS)
1404     TmpEltVT = TLI.getSetCCResultType(DAG.getDataLayout(),
1405                                       *DAG.getContext(), TmpEltVT);
1406 
1407   EVT ValueVTs[] = {TmpEltVT, MVT::Other};
1408   SDValue Chain = Node->getOperand(0);
1409   SDLoc dl(Node);
1410 
1411   SmallVector<SDValue, 32> OpValues;
1412   SmallVector<SDValue, 32> OpChains;
1413   for (unsigned i = 0; i < NumElems; ++i) {
1414     SmallVector<SDValue, 4> Opers;
1415     SDValue Idx = DAG.getVectorIdxConstant(i, dl);
1416 
1417     // The Chain is the first operand.
1418     Opers.push_back(Chain);
1419 
1420     // Now process the remaining operands.
1421     for (unsigned j = 1; j < NumOpers; ++j) {
1422       SDValue Oper = Node->getOperand(j);
1423       EVT OperVT = Oper.getValueType();
1424 
1425       if (OperVT.isVector())
1426         Oper = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1427                            OperVT.getVectorElementType(), Oper, Idx);
1428 
1429       Opers.push_back(Oper);
1430     }
1431 
1432     SDValue ScalarOp = DAG.getNode(Node->getOpcode(), dl, ValueVTs, Opers);
1433     SDValue ScalarResult = ScalarOp.getValue(0);
1434     SDValue ScalarChain = ScalarOp.getValue(1);
1435 
1436     if (Node->getOpcode() == ISD::STRICT_FSETCC ||
1437         Node->getOpcode() == ISD::STRICT_FSETCCS)
1438       ScalarResult = DAG.getSelect(dl, EltVT, ScalarResult,
1439                            DAG.getConstant(APInt::getAllOnesValue
1440                                            (EltVT.getSizeInBits()), dl, EltVT),
1441                            DAG.getConstant(0, dl, EltVT));
1442 
1443     OpValues.push_back(ScalarResult);
1444     OpChains.push_back(ScalarChain);
1445   }
1446 
1447   SDValue Result = DAG.getBuildVector(VT, dl, OpValues);
1448   SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OpChains);
1449 
1450   Results.push_back(Result);
1451   Results.push_back(NewChain);
1452 }
1453 
1454 SDValue VectorLegalizer::UnrollVSETCC(SDNode *Node) {
1455   EVT VT = Node->getValueType(0);
1456   unsigned NumElems = VT.getVectorNumElements();
1457   EVT EltVT = VT.getVectorElementType();
1458   SDValue LHS = Node->getOperand(0);
1459   SDValue RHS = Node->getOperand(1);
1460   SDValue CC = Node->getOperand(2);
1461   EVT TmpEltVT = LHS.getValueType().getVectorElementType();
1462   SDLoc dl(Node);
1463   SmallVector<SDValue, 8> Ops(NumElems);
1464   for (unsigned i = 0; i < NumElems; ++i) {
1465     SDValue LHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
1466                                   DAG.getVectorIdxConstant(i, dl));
1467     SDValue RHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
1468                                   DAG.getVectorIdxConstant(i, dl));
1469     Ops[i] = DAG.getNode(ISD::SETCC, dl,
1470                          TLI.getSetCCResultType(DAG.getDataLayout(),
1471                                                 *DAG.getContext(), TmpEltVT),
1472                          LHSElem, RHSElem, CC);
1473     Ops[i] = DAG.getSelect(dl, EltVT, Ops[i],
1474                            DAG.getConstant(APInt::getAllOnesValue
1475                                            (EltVT.getSizeInBits()), dl, EltVT),
1476                            DAG.getConstant(0, dl, EltVT));
1477   }
1478   return DAG.getBuildVector(VT, dl, Ops);
1479 }
1480 
1481 bool SelectionDAG::LegalizeVectors() {
1482   return VectorLegalizer(*this).Run();
1483 }
1484