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