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