[cleanup] Nuke the 'VectorOp' bit of the promote method names.
[oota-llvm.git] / 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/CodeGen/SelectionDAG.h"
31 #include "llvm/Target/TargetLowering.h"
32 using namespace llvm;
33
34 namespace {
35 class VectorLegalizer {
36   SelectionDAG& DAG;
37   const TargetLowering &TLI;
38   bool Changed; // Keep track of whether anything changed
39
40   /// For nodes that are of legal width, and that have more than one use, this
41   /// map indicates what regularized operand to use.  This allows us to avoid
42   /// legalizing the same thing more than once.
43   SmallDenseMap<SDValue, SDValue, 64> LegalizedNodes;
44
45   /// \brief Adds a node to the translation cache.
46   void AddLegalizedOperand(SDValue From, SDValue To) {
47     LegalizedNodes.insert(std::make_pair(From, To));
48     // If someone requests legalization of the new node, return itself.
49     if (From != To)
50       LegalizedNodes.insert(std::make_pair(To, To));
51   }
52
53   /// \brief Legalizes the given node.
54   SDValue LegalizeOp(SDValue Op);
55
56   /// \brief Assuming the node is legal, "legalize" the results.
57   SDValue TranslateLegalizeResults(SDValue Op, SDValue Result);
58
59   /// \brief Implements unrolling a VSETCC.
60   SDValue UnrollVSETCC(SDValue Op);
61
62   /// \brief Implements expansion for FNEG; falls back to UnrollVectorOp if
63   /// FSUB isn't legal.
64   ///
65   /// Implements expansion for UINT_TO_FLOAT; falls back to UnrollVectorOp if
66   /// SINT_TO_FLOAT and SHR on vectors isn't legal.
67   SDValue ExpandUINT_TO_FLOAT(SDValue Op);
68
69   /// \brief Implement expansion for SIGN_EXTEND_INREG using SRL and SRA.
70   SDValue ExpandSEXTINREG(SDValue Op);
71
72   /// \brief Expand bswap of vectors into a shuffle if legal.
73   SDValue ExpandBSWAP(SDValue Op);
74
75   /// \brief Implement vselect in terms of XOR, AND, OR when blend is not
76   /// supported by the target.
77   SDValue ExpandVSELECT(SDValue Op);
78   SDValue ExpandSELECT(SDValue Op);
79   SDValue ExpandLoad(SDValue Op);
80   SDValue ExpandStore(SDValue Op);
81   SDValue ExpandFNEG(SDValue Op);
82
83   /// \brief Implements vector promotion.
84   ///
85   /// This is essentially just bitcasting the operands to a different type and
86   /// bitcasting the result back to the original type.
87   SDValue Promote(SDValue Op);
88
89   /// \brief Implements [SU]INT_TO_FP vector promotion.
90   ///
91   /// This is a [zs]ext of the input operand to the next size up.
92   SDValue PromoteINT_TO_FP(SDValue Op);
93
94   /// \brief Implements FP_TO_[SU]INT vector promotion of the result type.
95   ///
96   /// It is promoted to the next size up integer type.  The result is then
97   /// truncated back to the original type.
98   SDValue PromoteFP_TO_INT(SDValue Op, bool isSigned);
99
100 public:
101   /// \brief Begin legalizer the vector operations in the DAG.
102   bool Run();
103   VectorLegalizer(SelectionDAG& dag) :
104       DAG(dag), TLI(dag.getTargetLoweringInfo()), Changed(false) {}
105 };
106
107 bool VectorLegalizer::Run() {
108   // Before we start legalizing vector nodes, check if there are any vectors.
109   bool HasVectors = false;
110   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
111        E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I) {
112     // Check if the values of the nodes contain vectors. We don't need to check
113     // the operands because we are going to check their values at some point.
114     for (SDNode::value_iterator J = I->value_begin(), E = I->value_end();
115          J != E; ++J)
116       HasVectors |= J->isVector();
117
118     // If we found a vector node we can start the legalization.
119     if (HasVectors)
120       break;
121   }
122
123   // If this basic block has no vectors then no need to legalize vectors.
124   if (!HasVectors)
125     return false;
126
127   // The legalize process is inherently a bottom-up recursive process (users
128   // legalize their uses before themselves).  Given infinite stack space, we
129   // could just start legalizing on the root and traverse the whole graph.  In
130   // practice however, this causes us to run out of stack space on large basic
131   // blocks.  To avoid this problem, compute an ordering of the nodes where each
132   // node is only legalized after all of its operands are legalized.
133   DAG.AssignTopologicalOrder();
134   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
135        E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I)
136     LegalizeOp(SDValue(I, 0));
137
138   // Finally, it's possible the root changed.  Get the new root.
139   SDValue OldRoot = DAG.getRoot();
140   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
141   DAG.setRoot(LegalizedNodes[OldRoot]);
142
143   LegalizedNodes.clear();
144
145   // Remove dead nodes now.
146   DAG.RemoveDeadNodes();
147
148   return Changed;
149 }
150
151 SDValue VectorLegalizer::TranslateLegalizeResults(SDValue Op, SDValue Result) {
152   // Generic legalization: just pass the operand through.
153   for (unsigned i = 0, e = Op.getNode()->getNumValues(); i != e; ++i)
154     AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
155   return Result.getValue(Op.getResNo());
156 }
157
158 SDValue VectorLegalizer::LegalizeOp(SDValue Op) {
159   // Note that LegalizeOp may be reentered even from single-use nodes, which
160   // means that we always must cache transformed nodes.
161   DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
162   if (I != LegalizedNodes.end()) return I->second;
163
164   SDNode* Node = Op.getNode();
165
166   // Legalize the operands
167   SmallVector<SDValue, 8> Ops;
168   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
169     Ops.push_back(LegalizeOp(Node->getOperand(i)));
170
171   SDValue Result = SDValue(DAG.UpdateNodeOperands(Op.getNode(), Ops), 0);
172
173   if (Op.getOpcode() == ISD::LOAD) {
174     LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
175     ISD::LoadExtType ExtType = LD->getExtensionType();
176     if (LD->getMemoryVT().isVector() && ExtType != ISD::NON_EXTLOAD) {
177       if (TLI.isLoadExtLegal(LD->getExtensionType(), LD->getMemoryVT()))
178         return TranslateLegalizeResults(Op, Result);
179       Changed = true;
180       return LegalizeOp(ExpandLoad(Op));
181     }
182   } else if (Op.getOpcode() == ISD::STORE) {
183     StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
184     EVT StVT = ST->getMemoryVT();
185     MVT ValVT = ST->getValue().getSimpleValueType();
186     if (StVT.isVector() && ST->isTruncatingStore())
187       switch (TLI.getTruncStoreAction(ValVT, StVT.getSimpleVT())) {
188       default: llvm_unreachable("This action is not supported yet!");
189       case TargetLowering::Legal:
190         return TranslateLegalizeResults(Op, Result);
191       case TargetLowering::Custom:
192         Changed = true;
193         return TranslateLegalizeResults(Op, TLI.LowerOperation(Result, DAG));
194       case TargetLowering::Expand:
195         Changed = true;
196         return LegalizeOp(ExpandStore(Op));
197       }
198   }
199
200   bool HasVectorValue = false;
201   for (SDNode::value_iterator J = Node->value_begin(), E = Node->value_end();
202        J != E;
203        ++J)
204     HasVectorValue |= J->isVector();
205   if (!HasVectorValue)
206     return TranslateLegalizeResults(Op, Result);
207
208   EVT QueryType;
209   switch (Op.getOpcode()) {
210   default:
211     return TranslateLegalizeResults(Op, Result);
212   case ISD::ADD:
213   case ISD::SUB:
214   case ISD::MUL:
215   case ISD::SDIV:
216   case ISD::UDIV:
217   case ISD::SREM:
218   case ISD::UREM:
219   case ISD::FADD:
220   case ISD::FSUB:
221   case ISD::FMUL:
222   case ISD::FDIV:
223   case ISD::FREM:
224   case ISD::AND:
225   case ISD::OR:
226   case ISD::XOR:
227   case ISD::SHL:
228   case ISD::SRA:
229   case ISD::SRL:
230   case ISD::ROTL:
231   case ISD::ROTR:
232   case ISD::BSWAP:
233   case ISD::CTLZ:
234   case ISD::CTTZ:
235   case ISD::CTLZ_ZERO_UNDEF:
236   case ISD::CTTZ_ZERO_UNDEF:
237   case ISD::CTPOP:
238   case ISD::SELECT:
239   case ISD::VSELECT:
240   case ISD::SELECT_CC:
241   case ISD::SETCC:
242   case ISD::ZERO_EXTEND:
243   case ISD::ANY_EXTEND:
244   case ISD::TRUNCATE:
245   case ISD::SIGN_EXTEND:
246   case ISD::FP_TO_SINT:
247   case ISD::FP_TO_UINT:
248   case ISD::FNEG:
249   case ISD::FABS:
250   case ISD::FCOPYSIGN:
251   case ISD::FSQRT:
252   case ISD::FSIN:
253   case ISD::FCOS:
254   case ISD::FPOWI:
255   case ISD::FPOW:
256   case ISD::FLOG:
257   case ISD::FLOG2:
258   case ISD::FLOG10:
259   case ISD::FEXP:
260   case ISD::FEXP2:
261   case ISD::FCEIL:
262   case ISD::FTRUNC:
263   case ISD::FRINT:
264   case ISD::FNEARBYINT:
265   case ISD::FROUND:
266   case ISD::FFLOOR:
267   case ISD::FP_ROUND:
268   case ISD::FP_EXTEND:
269   case ISD::FMA:
270   case ISD::SIGN_EXTEND_INREG:
271     QueryType = Node->getValueType(0);
272     break;
273   case ISD::FP_ROUND_INREG:
274     QueryType = cast<VTSDNode>(Node->getOperand(1))->getVT();
275     break;
276   case ISD::SINT_TO_FP:
277   case ISD::UINT_TO_FP:
278     QueryType = Node->getOperand(0).getValueType();
279     break;
280   }
281
282   switch (TLI.getOperationAction(Node->getOpcode(), QueryType)) {
283   case TargetLowering::Promote:
284     switch (Op.getOpcode()) {
285     default:
286       // "Promote" the operation by bitcasting
287       Result = Promote(Op);
288       Changed = true;
289       break;
290     case ISD::SINT_TO_FP:
291     case ISD::UINT_TO_FP:
292       // "Promote" the operation by extending the operand.
293       Result = PromoteINT_TO_FP(Op);
294       Changed = true;
295       break;
296     case ISD::FP_TO_UINT:
297     case ISD::FP_TO_SINT:
298       // Promote the operation by extending the operand.
299       Result = PromoteFP_TO_INT(Op, Op->getOpcode() == ISD::FP_TO_SINT);
300       Changed = true;
301       break;
302     }
303     break;
304   case TargetLowering::Legal: break;
305   case TargetLowering::Custom: {
306     SDValue Tmp1 = TLI.LowerOperation(Op, DAG);
307     if (Tmp1.getNode()) {
308       Result = Tmp1;
309       break;
310     }
311     // FALL THROUGH
312   }
313   case TargetLowering::Expand:
314     if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG)
315       Result = ExpandSEXTINREG(Op);
316     else if (Node->getOpcode() == ISD::BSWAP)
317       Result = ExpandBSWAP(Op);
318     else if (Node->getOpcode() == ISD::VSELECT)
319       Result = ExpandVSELECT(Op);
320     else if (Node->getOpcode() == ISD::SELECT)
321       Result = ExpandSELECT(Op);
322     else if (Node->getOpcode() == ISD::UINT_TO_FP)
323       Result = ExpandUINT_TO_FLOAT(Op);
324     else if (Node->getOpcode() == ISD::FNEG)
325       Result = ExpandFNEG(Op);
326     else if (Node->getOpcode() == ISD::SETCC)
327       Result = UnrollVSETCC(Op);
328     else
329       Result = DAG.UnrollVectorOp(Op.getNode());
330     break;
331   }
332
333   // Make sure that the generated code is itself legal.
334   if (Result != Op) {
335     Result = LegalizeOp(Result);
336     Changed = true;
337   }
338
339   // Note that LegalizeOp may be reentered even from single-use nodes, which
340   // means that we always must cache transformed nodes.
341   AddLegalizedOperand(Op, Result);
342   return Result;
343 }
344
345 SDValue VectorLegalizer::Promote(SDValue Op) {
346   // Vector "promotion" is basically just bitcasting and doing the operation
347   // in a different type.  For example, x86 promotes ISD::AND on v2i32 to
348   // v1i64.
349   MVT VT = Op.getSimpleValueType();
350   assert(Op.getNode()->getNumValues() == 1 &&
351          "Can't promote a vector with multiple results!");
352   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
353   SDLoc dl(Op);
354   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
355
356   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
357     if (Op.getOperand(j).getValueType().isVector())
358       Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Op.getOperand(j));
359     else
360       Operands[j] = Op.getOperand(j);
361   }
362
363   Op = DAG.getNode(Op.getOpcode(), dl, NVT, Operands);
364
365   return DAG.getNode(ISD::BITCAST, dl, VT, Op);
366 }
367
368 SDValue VectorLegalizer::PromoteINT_TO_FP(SDValue Op) {
369   // INT_TO_FP operations may require the input operand be promoted even
370   // when the type is otherwise legal.
371   EVT VT = Op.getOperand(0).getValueType();
372   assert(Op.getNode()->getNumValues() == 1 &&
373          "Can't promote a vector with multiple results!");
374
375   // Normal getTypeToPromoteTo() doesn't work here, as that will promote
376   // by widening the vector w/ the same element width and twice the number
377   // of elements. We want the other way around, the same number of elements,
378   // each twice the width.
379   //
380   // Increase the bitwidth of the element to the next pow-of-two
381   // (which is greater than 8 bits).
382
383   EVT NVT = VT.widenIntegerVectorElementType(*DAG.getContext());
384   assert(NVT.isSimple() && "Promoting to a non-simple vector type!");
385   SDLoc dl(Op);
386   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
387
388   unsigned Opc = Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND :
389     ISD::SIGN_EXTEND;
390   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
391     if (Op.getOperand(j).getValueType().isVector())
392       Operands[j] = DAG.getNode(Opc, dl, NVT, Op.getOperand(j));
393     else
394       Operands[j] = Op.getOperand(j);
395   }
396
397   return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Operands);
398 }
399
400 // For FP_TO_INT we promote the result type to a vector type with wider
401 // elements and then truncate the result.  This is different from the default
402 // PromoteVector which uses bitcast to promote thus assumning that the
403 // promoted vector type has the same overall size.
404 SDValue VectorLegalizer::PromoteFP_TO_INT(SDValue Op, bool isSigned) {
405   assert(Op.getNode()->getNumValues() == 1 &&
406          "Can't promote a vector with multiple results!");
407   EVT VT = Op.getValueType();
408
409   EVT NewVT;
410   unsigned NewOpc;
411   while (1) {
412     NewVT = VT.widenIntegerVectorElementType(*DAG.getContext());
413     assert(NewVT.isSimple() && "Promoting to a non-simple vector type!");
414     if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewVT)) {
415       NewOpc = ISD::FP_TO_SINT;
416       break;
417     }
418     if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewVT)) {
419       NewOpc = ISD::FP_TO_UINT;
420       break;
421     }
422   }
423
424   SDLoc loc(Op);
425   SDValue promoted  = DAG.getNode(NewOpc, SDLoc(Op), NewVT, Op.getOperand(0));
426   return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT, promoted);
427 }
428
429
430 SDValue VectorLegalizer::ExpandLoad(SDValue Op) {
431   SDLoc dl(Op);
432   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
433   SDValue Chain = LD->getChain();
434   SDValue BasePTR = LD->getBasePtr();
435   EVT SrcVT = LD->getMemoryVT();
436   ISD::LoadExtType ExtType = LD->getExtensionType();
437
438   SmallVector<SDValue, 8> Vals;
439   SmallVector<SDValue, 8> LoadChains;
440   unsigned NumElem = SrcVT.getVectorNumElements();
441
442   EVT SrcEltVT = SrcVT.getScalarType();
443   EVT DstEltVT = Op.getNode()->getValueType(0).getScalarType();
444
445   if (SrcVT.getVectorNumElements() > 1 && !SrcEltVT.isByteSized()) {
446     // When elements in a vector is not byte-addressable, we cannot directly
447     // load each element by advancing pointer, which could only address bytes.
448     // Instead, we load all significant words, mask bits off, and concatenate
449     // them to form each element. Finally, they are extended to destination
450     // scalar type to build the destination vector.
451     EVT WideVT = TLI.getPointerTy();
452
453     assert(WideVT.isRound() &&
454            "Could not handle the sophisticated case when the widest integer is"
455            " not power of 2.");
456     assert(WideVT.bitsGE(SrcEltVT) &&
457            "Type is not legalized?");
458
459     unsigned WideBytes = WideVT.getStoreSize();
460     unsigned Offset = 0;
461     unsigned RemainingBytes = SrcVT.getStoreSize();
462     SmallVector<SDValue, 8> LoadVals;
463
464     while (RemainingBytes > 0) {
465       SDValue ScalarLoad;
466       unsigned LoadBytes = WideBytes;
467
468       if (RemainingBytes >= LoadBytes) {
469         ScalarLoad = DAG.getLoad(WideVT, dl, Chain, BasePTR,
470                                  LD->getPointerInfo().getWithOffset(Offset),
471                                  LD->isVolatile(), LD->isNonTemporal(),
472                                  LD->isInvariant(), LD->getAlignment(),
473                                  LD->getTBAAInfo());
474       } else {
475         EVT LoadVT = WideVT;
476         while (RemainingBytes < LoadBytes) {
477           LoadBytes >>= 1; // Reduce the load size by half.
478           LoadVT = EVT::getIntegerVT(*DAG.getContext(), LoadBytes << 3);
479         }
480         ScalarLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, WideVT, Chain, BasePTR,
481                                     LD->getPointerInfo().getWithOffset(Offset),
482                                     LoadVT, LD->isVolatile(),
483                                     LD->isNonTemporal(), LD->getAlignment(),
484                                     LD->getTBAAInfo());
485       }
486
487       RemainingBytes -= LoadBytes;
488       Offset += LoadBytes;
489       BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
490                             DAG.getConstant(LoadBytes, BasePTR.getValueType()));
491
492       LoadVals.push_back(ScalarLoad.getValue(0));
493       LoadChains.push_back(ScalarLoad.getValue(1));
494     }
495
496     // Extract bits, pack and extend/trunc them into destination type.
497     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
498     SDValue SrcEltBitMask = DAG.getConstant((1U << SrcEltBits) - 1, WideVT);
499
500     unsigned BitOffset = 0;
501     unsigned WideIdx = 0;
502     unsigned WideBits = WideVT.getSizeInBits();
503
504     for (unsigned Idx = 0; Idx != NumElem; ++Idx) {
505       SDValue Lo, Hi, ShAmt;
506
507       if (BitOffset < WideBits) {
508         ShAmt = DAG.getConstant(BitOffset, TLI.getShiftAmountTy(WideVT));
509         Lo = DAG.getNode(ISD::SRL, dl, WideVT, LoadVals[WideIdx], ShAmt);
510         Lo = DAG.getNode(ISD::AND, dl, WideVT, Lo, SrcEltBitMask);
511       }
512
513       BitOffset += SrcEltBits;
514       if (BitOffset >= WideBits) {
515         WideIdx++;
516         Offset -= WideBits;
517         if (Offset > 0) {
518           ShAmt = DAG.getConstant(SrcEltBits - Offset,
519                                   TLI.getShiftAmountTy(WideVT));
520           Hi = DAG.getNode(ISD::SHL, dl, WideVT, LoadVals[WideIdx], ShAmt);
521           Hi = DAG.getNode(ISD::AND, dl, WideVT, Hi, SrcEltBitMask);
522         }
523       }
524
525       if (Hi.getNode())
526         Lo = DAG.getNode(ISD::OR, dl, WideVT, Lo, Hi);
527
528       switch (ExtType) {
529       default: llvm_unreachable("Unknown extended-load op!");
530       case ISD::EXTLOAD:
531         Lo = DAG.getAnyExtOrTrunc(Lo, dl, DstEltVT);
532         break;
533       case ISD::ZEXTLOAD:
534         Lo = DAG.getZExtOrTrunc(Lo, dl, DstEltVT);
535         break;
536       case ISD::SEXTLOAD:
537         ShAmt = DAG.getConstant(WideBits - SrcEltBits,
538                                 TLI.getShiftAmountTy(WideVT));
539         Lo = DAG.getNode(ISD::SHL, dl, WideVT, Lo, ShAmt);
540         Lo = DAG.getNode(ISD::SRA, dl, WideVT, Lo, ShAmt);
541         Lo = DAG.getSExtOrTrunc(Lo, dl, DstEltVT);
542         break;
543       }
544       Vals.push_back(Lo);
545     }
546   } else {
547     unsigned Stride = SrcVT.getScalarType().getSizeInBits()/8;
548
549     for (unsigned Idx=0; Idx<NumElem; Idx++) {
550       SDValue ScalarLoad = DAG.getExtLoad(ExtType, dl,
551                 Op.getNode()->getValueType(0).getScalarType(),
552                 Chain, BasePTR, LD->getPointerInfo().getWithOffset(Idx * Stride),
553                 SrcVT.getScalarType(),
554                 LD->isVolatile(), LD->isNonTemporal(),
555                 LD->getAlignment(), LD->getTBAAInfo());
556
557       BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
558                          DAG.getConstant(Stride, BasePTR.getValueType()));
559
560       Vals.push_back(ScalarLoad.getValue(0));
561       LoadChains.push_back(ScalarLoad.getValue(1));
562     }
563   }
564
565   SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
566   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
567                               Op.getNode()->getValueType(0), Vals);
568
569   AddLegalizedOperand(Op.getValue(0), Value);
570   AddLegalizedOperand(Op.getValue(1), NewChain);
571
572   return (Op.getResNo() ? NewChain : Value);
573 }
574
575 SDValue VectorLegalizer::ExpandStore(SDValue Op) {
576   SDLoc dl(Op);
577   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
578   SDValue Chain = ST->getChain();
579   SDValue BasePTR = ST->getBasePtr();
580   SDValue Value = ST->getValue();
581   EVT StVT = ST->getMemoryVT();
582
583   unsigned Alignment = ST->getAlignment();
584   bool isVolatile = ST->isVolatile();
585   bool isNonTemporal = ST->isNonTemporal();
586   const MDNode *TBAAInfo = ST->getTBAAInfo();
587
588   unsigned NumElem = StVT.getVectorNumElements();
589   // The type of the data we want to save
590   EVT RegVT = Value.getValueType();
591   EVT RegSclVT = RegVT.getScalarType();
592   // The type of data as saved in memory.
593   EVT MemSclVT = StVT.getScalarType();
594
595   // Cast floats into integers
596   unsigned ScalarSize = MemSclVT.getSizeInBits();
597
598   // Round odd types to the next pow of two.
599   if (!isPowerOf2_32(ScalarSize))
600     ScalarSize = NextPowerOf2(ScalarSize);
601
602   // Store Stride in bytes
603   unsigned Stride = ScalarSize/8;
604   // Extract each of the elements from the original vector
605   // and save them into memory individually.
606   SmallVector<SDValue, 8> Stores;
607   for (unsigned Idx = 0; Idx < NumElem; Idx++) {
608     SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
609                RegSclVT, Value, DAG.getConstant(Idx, TLI.getVectorIdxTy()));
610
611     // This scalar TruncStore may be illegal, but we legalize it later.
612     SDValue Store = DAG.getTruncStore(Chain, dl, Ex, BasePTR,
613                ST->getPointerInfo().getWithOffset(Idx*Stride), MemSclVT,
614                isVolatile, isNonTemporal, Alignment, TBAAInfo);
615
616     BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
617                                DAG.getConstant(Stride, BasePTR.getValueType()));
618
619     Stores.push_back(Store);
620   }
621   SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
622   AddLegalizedOperand(Op, TF);
623   return TF;
624 }
625
626 SDValue VectorLegalizer::ExpandSELECT(SDValue Op) {
627   // Lower a select instruction where the condition is a scalar and the
628   // operands are vectors. Lower this select to VSELECT and implement it
629   // using XOR AND OR. The selector bit is broadcasted.
630   EVT VT = Op.getValueType();
631   SDLoc DL(Op);
632
633   SDValue Mask = Op.getOperand(0);
634   SDValue Op1 = Op.getOperand(1);
635   SDValue Op2 = Op.getOperand(2);
636
637   assert(VT.isVector() && !Mask.getValueType().isVector()
638          && Op1.getValueType() == Op2.getValueType() && "Invalid type");
639
640   unsigned NumElem = VT.getVectorNumElements();
641
642   // If we can't even use the basic vector operations of
643   // AND,OR,XOR, we will have to scalarize the op.
644   // Notice that the operation may be 'promoted' which means that it is
645   // 'bitcasted' to another type which is handled.
646   // Also, we need to be able to construct a splat vector using BUILD_VECTOR.
647   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
648       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
649       TLI.getOperationAction(ISD::OR,  VT) == TargetLowering::Expand ||
650       TLI.getOperationAction(ISD::BUILD_VECTOR,  VT) == TargetLowering::Expand)
651     return DAG.UnrollVectorOp(Op.getNode());
652
653   // Generate a mask operand.
654   EVT MaskTy = VT.changeVectorElementTypeToInteger();
655
656   // What is the size of each element in the vector mask.
657   EVT BitTy = MaskTy.getScalarType();
658
659   Mask = DAG.getSelect(DL, BitTy, Mask,
660           DAG.getConstant(APInt::getAllOnesValue(BitTy.getSizeInBits()), BitTy),
661           DAG.getConstant(0, BitTy));
662
663   // Broadcast the mask so that the entire vector is all-one or all zero.
664   SmallVector<SDValue, 8> Ops(NumElem, Mask);
665   Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskTy, Ops);
666
667   // Bitcast the operands to be the same type as the mask.
668   // This is needed when we select between FP types because
669   // the mask is a vector of integers.
670   Op1 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op1);
671   Op2 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op2);
672
673   SDValue AllOnes = DAG.getConstant(
674             APInt::getAllOnesValue(BitTy.getSizeInBits()), MaskTy);
675   SDValue NotMask = DAG.getNode(ISD::XOR, DL, MaskTy, Mask, AllOnes);
676
677   Op1 = DAG.getNode(ISD::AND, DL, MaskTy, Op1, Mask);
678   Op2 = DAG.getNode(ISD::AND, DL, MaskTy, Op2, NotMask);
679   SDValue Val = DAG.getNode(ISD::OR, DL, MaskTy, Op1, Op2);
680   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
681 }
682
683 SDValue VectorLegalizer::ExpandSEXTINREG(SDValue Op) {
684   EVT VT = Op.getValueType();
685
686   // Make sure that the SRA and SHL instructions are available.
687   if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Expand ||
688       TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Expand)
689     return DAG.UnrollVectorOp(Op.getNode());
690
691   SDLoc DL(Op);
692   EVT OrigTy = cast<VTSDNode>(Op->getOperand(1))->getVT();
693
694   unsigned BW = VT.getScalarType().getSizeInBits();
695   unsigned OrigBW = OrigTy.getScalarType().getSizeInBits();
696   SDValue ShiftSz = DAG.getConstant(BW - OrigBW, VT);
697
698   Op = Op.getOperand(0);
699   Op =   DAG.getNode(ISD::SHL, DL, VT, Op, ShiftSz);
700   return DAG.getNode(ISD::SRA, DL, VT, Op, ShiftSz);
701 }
702
703 SDValue VectorLegalizer::ExpandBSWAP(SDValue Op) {
704   EVT VT = Op.getValueType();
705
706   // Generate a byte wise shuffle mask for the BSWAP.
707   SmallVector<int, 16> ShuffleMask;
708   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
709   for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I)
710     for (int J = ScalarSizeInBytes - 1; J >= 0; --J)
711       ShuffleMask.push_back((I * ScalarSizeInBytes) + J);
712
713   EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, ShuffleMask.size());
714
715   // Only emit a shuffle if the mask is legal.
716   if (!TLI.isShuffleMaskLegal(ShuffleMask, ByteVT))
717     return DAG.UnrollVectorOp(Op.getNode());
718
719   SDLoc DL(Op);
720   Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
721   Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT),
722                             ShuffleMask.data());
723   return DAG.getNode(ISD::BITCAST, DL, VT, Op);
724 }
725
726 SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) {
727   // Implement VSELECT in terms of XOR, AND, OR
728   // on platforms which do not support blend natively.
729   SDLoc DL(Op);
730
731   SDValue Mask = Op.getOperand(0);
732   SDValue Op1 = Op.getOperand(1);
733   SDValue Op2 = Op.getOperand(2);
734
735   EVT VT = Mask.getValueType();
736
737   // If we can't even use the basic vector operations of
738   // AND,OR,XOR, we will have to scalarize the op.
739   // Notice that the operation may be 'promoted' which means that it is
740   // 'bitcasted' to another type which is handled.
741   // This operation also isn't safe with AND, OR, XOR when the boolean
742   // type is 0/1 as we need an all ones vector constant to mask with.
743   // FIXME: Sign extend 1 to all ones if thats legal on the target.
744   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
745       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
746       TLI.getOperationAction(ISD::OR,  VT) == TargetLowering::Expand ||
747       TLI.getBooleanContents(true) !=
748       TargetLowering::ZeroOrNegativeOneBooleanContent)
749     return DAG.UnrollVectorOp(Op.getNode());
750
751   // If the mask and the type are different sizes, unroll the vector op. This
752   // can occur when getSetCCResultType returns something that is different in
753   // size from the operand types. For example, v4i8 = select v4i32, v4i8, v4i8.
754   if (VT.getSizeInBits() != Op1.getValueType().getSizeInBits())
755     return DAG.UnrollVectorOp(Op.getNode());
756
757   // Bitcast the operands to be the same type as the mask.
758   // This is needed when we select between FP types because
759   // the mask is a vector of integers.
760   Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
761   Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
762
763   SDValue AllOnes = DAG.getConstant(
764     APInt::getAllOnesValue(VT.getScalarType().getSizeInBits()), VT);
765   SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
766
767   Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
768   Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
769   SDValue Val = DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
770   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
771 }
772
773 SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) {
774   EVT VT = Op.getOperand(0).getValueType();
775   SDLoc DL(Op);
776
777   // Make sure that the SINT_TO_FP and SRL instructions are available.
778   if (TLI.getOperationAction(ISD::SINT_TO_FP, VT) == TargetLowering::Expand ||
779       TLI.getOperationAction(ISD::SRL,        VT) == TargetLowering::Expand)
780     return DAG.UnrollVectorOp(Op.getNode());
781
782  EVT SVT = VT.getScalarType();
783   assert((SVT.getSizeInBits() == 64 || SVT.getSizeInBits() == 32) &&
784       "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
785
786   unsigned BW = SVT.getSizeInBits();
787   SDValue HalfWord = DAG.getConstant(BW/2, VT);
788
789   // Constants to clear the upper part of the word.
790   // Notice that we can also use SHL+SHR, but using a constant is slightly
791   // faster on x86.
792   uint64_t HWMask = (SVT.getSizeInBits()==64)?0x00000000FFFFFFFF:0x0000FFFF;
793   SDValue HalfWordMask = DAG.getConstant(HWMask, VT);
794
795   // Two to the power of half-word-size.
796   SDValue TWOHW = DAG.getConstantFP((1<<(BW/2)), Op.getValueType());
797
798   // Clear upper part of LO, lower HI
799   SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Op.getOperand(0), HalfWord);
800   SDValue LO = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), HalfWordMask);
801
802   // Convert hi and lo to floats
803   // Convert the hi part back to the upper values
804   SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI);
805           fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW);
806   SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO);
807
808   // Add the two halves
809   return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO);
810 }
811
812
813 SDValue VectorLegalizer::ExpandFNEG(SDValue Op) {
814   if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) {
815     SDValue Zero = DAG.getConstantFP(-0.0, Op.getValueType());
816     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
817                        Zero, Op.getOperand(0));
818   }
819   return DAG.UnrollVectorOp(Op.getNode());
820 }
821
822 SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) {
823   EVT VT = Op.getValueType();
824   unsigned NumElems = VT.getVectorNumElements();
825   EVT EltVT = VT.getVectorElementType();
826   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2);
827   EVT TmpEltVT = LHS.getValueType().getVectorElementType();
828   SDLoc dl(Op);
829   SmallVector<SDValue, 8> Ops(NumElems);
830   for (unsigned i = 0; i < NumElems; ++i) {
831     SDValue LHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
832                                   DAG.getConstant(i, TLI.getVectorIdxTy()));
833     SDValue RHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
834                                   DAG.getConstant(i, TLI.getVectorIdxTy()));
835     Ops[i] = DAG.getNode(ISD::SETCC, dl,
836                          TLI.getSetCCResultType(*DAG.getContext(), TmpEltVT),
837                          LHSElem, RHSElem, CC);
838     Ops[i] = DAG.getSelect(dl, EltVT, Ops[i],
839                            DAG.getConstant(APInt::getAllOnesValue
840                                            (EltVT.getSizeInBits()), EltVT),
841                            DAG.getConstant(0, EltVT));
842   }
843   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
844 }
845
846 }
847
848 bool SelectionDAG::LegalizeVectors() {
849   return VectorLegalizer(*this).Run();
850 }