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