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