1 //===-- LegalizeVectorOps.cpp - Implement SelectionDAG::LegalizeVectors ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SelectionDAG::LegalizeVectors method.
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.
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.
28 //===----------------------------------------------------------------------===//
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/Target/TargetLowering.h"
35 class VectorLegalizer {
37 const TargetLowering &TLI;
38 bool Changed; // Keep track of whether anything changed
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;
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.
50 LegalizedNodes.insert(std::make_pair(To, To));
53 /// \brief Legalizes the given node.
54 SDValue LegalizeOp(SDValue Op);
56 /// \brief Assuming the node is legal, "legalize" the results.
57 SDValue TranslateLegalizeResults(SDValue Op, SDValue Result);
59 /// \brief Implements unrolling a VSETCC.
60 SDValue UnrollVSETCC(SDValue Op);
62 /// \brief Implements expansion for FNEG; falls back to UnrollVectorOp if
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);
69 /// \brief Implement expansion for SIGN_EXTEND_INREG using SRL and SRA.
70 SDValue ExpandSEXTINREG(SDValue Op);
72 /// \brief Expand bswap of vectors into a shuffle if legal.
73 SDValue ExpandBSWAP(SDValue Op);
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);
83 /// \brief Implements vector promotion.
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);
89 /// \brief Implements [SU]INT_TO_FP vector promotion.
91 /// This is a [zs]ext of the input operand to the next size up.
92 SDValue PromoteINT_TO_FP(SDValue Op);
94 /// \brief Implements FP_TO_[SU]INT vector promotion of the result type.
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);
101 /// \brief Begin legalizer the vector operations in the DAG.
103 VectorLegalizer(SelectionDAG& dag) :
104 DAG(dag), TLI(dag.getTargetLoweringInfo()), Changed(false) {}
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();
116 HasVectors |= J->isVector();
118 // If we found a vector node we can start the legalization.
123 // If this basic block has no vectors then no need to legalize vectors.
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));
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]);
143 LegalizedNodes.clear();
145 // Remove dead nodes now.
146 DAG.RemoveDeadNodes();
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());
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;
164 SDNode* Node = Op.getNode();
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)));
171 SDValue Result = SDValue(DAG.UpdateNodeOperands(Op.getNode(), Ops), 0);
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);
180 return LegalizeOp(ExpandLoad(Op));
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:
193 return TranslateLegalizeResults(Op, TLI.LowerOperation(Result, DAG));
194 case TargetLowering::Expand:
196 return LegalizeOp(ExpandStore(Op));
200 bool HasVectorValue = false;
201 for (SDNode::value_iterator J = Node->value_begin(), E = Node->value_end();
204 HasVectorValue |= J->isVector();
206 return TranslateLegalizeResults(Op, Result);
209 switch (Op.getOpcode()) {
211 return TranslateLegalizeResults(Op, Result);
235 case ISD::CTLZ_ZERO_UNDEF:
236 case ISD::CTTZ_ZERO_UNDEF:
242 case ISD::ZERO_EXTEND:
243 case ISD::ANY_EXTEND:
245 case ISD::SIGN_EXTEND:
246 case ISD::FP_TO_SINT:
247 case ISD::FP_TO_UINT:
264 case ISD::FNEARBYINT:
270 case ISD::SIGN_EXTEND_INREG:
271 QueryType = Node->getValueType(0);
273 case ISD::FP_ROUND_INREG:
274 QueryType = cast<VTSDNode>(Node->getOperand(1))->getVT();
276 case ISD::SINT_TO_FP:
277 case ISD::UINT_TO_FP:
278 QueryType = Node->getOperand(0).getValueType();
282 switch (TLI.getOperationAction(Node->getOpcode(), QueryType)) {
283 case TargetLowering::Promote:
284 Result = Promote(Op);
287 case TargetLowering::Legal:
289 case TargetLowering::Custom: {
290 SDValue Tmp1 = TLI.LowerOperation(Op, DAG);
291 if (Tmp1.getNode()) {
297 case TargetLowering::Expand:
298 if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG)
299 Result = ExpandSEXTINREG(Op);
300 else if (Node->getOpcode() == ISD::BSWAP)
301 Result = ExpandBSWAP(Op);
302 else if (Node->getOpcode() == ISD::VSELECT)
303 Result = ExpandVSELECT(Op);
304 else if (Node->getOpcode() == ISD::SELECT)
305 Result = ExpandSELECT(Op);
306 else if (Node->getOpcode() == ISD::UINT_TO_FP)
307 Result = ExpandUINT_TO_FLOAT(Op);
308 else if (Node->getOpcode() == ISD::FNEG)
309 Result = ExpandFNEG(Op);
310 else if (Node->getOpcode() == ISD::SETCC)
311 Result = UnrollVSETCC(Op);
313 Result = DAG.UnrollVectorOp(Op.getNode());
317 // Make sure that the generated code is itself legal.
319 Result = LegalizeOp(Result);
323 // Note that LegalizeOp may be reentered even from single-use nodes, which
324 // means that we always must cache transformed nodes.
325 AddLegalizedOperand(Op, Result);
329 SDValue VectorLegalizer::Promote(SDValue Op) {
330 // For a few operations there is a specific concept for promotion based on
331 // the operand's type.
332 switch (Op.getOpcode()) {
333 case ISD::SINT_TO_FP:
334 case ISD::UINT_TO_FP:
335 // "Promote" the operation by extending the operand.
336 return PromoteINT_TO_FP(Op);
338 case ISD::FP_TO_UINT:
339 case ISD::FP_TO_SINT:
340 // Promote the operation by extending the operand.
341 return PromoteFP_TO_INT(Op, Op->getOpcode() == ISD::FP_TO_SINT);
345 // The rest of the time, vector "promotion" is basically just bitcasting and
346 // doing the operation in a different type. For example, x86 promotes
347 // ISD::AND on v2i32 to v1i64.
348 MVT VT = Op.getSimpleValueType();
349 assert(Op.getNode()->getNumValues() == 1 &&
350 "Can't promote a vector with multiple results!");
351 MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
353 SmallVector<SDValue, 4> Operands(Op.getNumOperands());
355 for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
356 if (Op.getOperand(j).getValueType().isVector())
357 Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Op.getOperand(j));
359 Operands[j] = Op.getOperand(j);
362 Op = DAG.getNode(Op.getOpcode(), dl, NVT, Operands);
364 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
367 SDValue VectorLegalizer::PromoteINT_TO_FP(SDValue Op) {
368 // INT_TO_FP operations may require the input operand be promoted even
369 // when the type is otherwise legal.
370 EVT VT = Op.getOperand(0).getValueType();
371 assert(Op.getNode()->getNumValues() == 1 &&
372 "Can't promote a vector with multiple results!");
374 // Normal getTypeToPromoteTo() doesn't work here, as that will promote
375 // by widening the vector w/ the same element width and twice the number
376 // of elements. We want the other way around, the same number of elements,
377 // each twice the width.
379 // Increase the bitwidth of the element to the next pow-of-two
380 // (which is greater than 8 bits).
382 EVT NVT = VT.widenIntegerVectorElementType(*DAG.getContext());
383 assert(NVT.isSimple() && "Promoting to a non-simple vector type!");
385 SmallVector<SDValue, 4> Operands(Op.getNumOperands());
387 unsigned Opc = Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND :
389 for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
390 if (Op.getOperand(j).getValueType().isVector())
391 Operands[j] = DAG.getNode(Opc, dl, NVT, Op.getOperand(j));
393 Operands[j] = Op.getOperand(j);
396 return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Operands);
399 // For FP_TO_INT we promote the result type to a vector type with wider
400 // elements and then truncate the result. This is different from the default
401 // PromoteVector which uses bitcast to promote thus assumning that the
402 // promoted vector type has the same overall size.
403 SDValue VectorLegalizer::PromoteFP_TO_INT(SDValue Op, bool isSigned) {
404 assert(Op.getNode()->getNumValues() == 1 &&
405 "Can't promote a vector with multiple results!");
406 EVT VT = Op.getValueType();
411 NewVT = VT.widenIntegerVectorElementType(*DAG.getContext());
412 assert(NewVT.isSimple() && "Promoting to a non-simple vector type!");
413 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewVT)) {
414 NewOpc = ISD::FP_TO_SINT;
417 if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewVT)) {
418 NewOpc = ISD::FP_TO_UINT;
424 SDValue promoted = DAG.getNode(NewOpc, SDLoc(Op), NewVT, Op.getOperand(0));
425 return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT, promoted);
429 SDValue VectorLegalizer::ExpandLoad(SDValue Op) {
431 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
432 SDValue Chain = LD->getChain();
433 SDValue BasePTR = LD->getBasePtr();
434 EVT SrcVT = LD->getMemoryVT();
435 ISD::LoadExtType ExtType = LD->getExtensionType();
437 SmallVector<SDValue, 8> Vals;
438 SmallVector<SDValue, 8> LoadChains;
439 unsigned NumElem = SrcVT.getVectorNumElements();
441 EVT SrcEltVT = SrcVT.getScalarType();
442 EVT DstEltVT = Op.getNode()->getValueType(0).getScalarType();
444 if (SrcVT.getVectorNumElements() > 1 && !SrcEltVT.isByteSized()) {
445 // When elements in a vector is not byte-addressable, we cannot directly
446 // load each element by advancing pointer, which could only address bytes.
447 // Instead, we load all significant words, mask bits off, and concatenate
448 // them to form each element. Finally, they are extended to destination
449 // scalar type to build the destination vector.
450 EVT WideVT = TLI.getPointerTy();
452 assert(WideVT.isRound() &&
453 "Could not handle the sophisticated case when the widest integer is"
455 assert(WideVT.bitsGE(SrcEltVT) &&
456 "Type is not legalized?");
458 unsigned WideBytes = WideVT.getStoreSize();
460 unsigned RemainingBytes = SrcVT.getStoreSize();
461 SmallVector<SDValue, 8> LoadVals;
463 while (RemainingBytes > 0) {
465 unsigned LoadBytes = WideBytes;
467 if (RemainingBytes >= LoadBytes) {
468 ScalarLoad = DAG.getLoad(WideVT, dl, Chain, BasePTR,
469 LD->getPointerInfo().getWithOffset(Offset),
470 LD->isVolatile(), LD->isNonTemporal(),
471 LD->isInvariant(), LD->getAlignment(),
475 while (RemainingBytes < LoadBytes) {
476 LoadBytes >>= 1; // Reduce the load size by half.
477 LoadVT = EVT::getIntegerVT(*DAG.getContext(), LoadBytes << 3);
479 ScalarLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, WideVT, Chain, BasePTR,
480 LD->getPointerInfo().getWithOffset(Offset),
481 LoadVT, LD->isVolatile(),
482 LD->isNonTemporal(), LD->getAlignment(),
486 RemainingBytes -= LoadBytes;
488 BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
489 DAG.getConstant(LoadBytes, BasePTR.getValueType()));
491 LoadVals.push_back(ScalarLoad.getValue(0));
492 LoadChains.push_back(ScalarLoad.getValue(1));
495 // Extract bits, pack and extend/trunc them into destination type.
496 unsigned SrcEltBits = SrcEltVT.getSizeInBits();
497 SDValue SrcEltBitMask = DAG.getConstant((1U << SrcEltBits) - 1, WideVT);
499 unsigned BitOffset = 0;
500 unsigned WideIdx = 0;
501 unsigned WideBits = WideVT.getSizeInBits();
503 for (unsigned Idx = 0; Idx != NumElem; ++Idx) {
504 SDValue Lo, Hi, ShAmt;
506 if (BitOffset < WideBits) {
507 ShAmt = DAG.getConstant(BitOffset, TLI.getShiftAmountTy(WideVT));
508 Lo = DAG.getNode(ISD::SRL, dl, WideVT, LoadVals[WideIdx], ShAmt);
509 Lo = DAG.getNode(ISD::AND, dl, WideVT, Lo, SrcEltBitMask);
512 BitOffset += SrcEltBits;
513 if (BitOffset >= WideBits) {
517 ShAmt = DAG.getConstant(SrcEltBits - Offset,
518 TLI.getShiftAmountTy(WideVT));
519 Hi = DAG.getNode(ISD::SHL, dl, WideVT, LoadVals[WideIdx], ShAmt);
520 Hi = DAG.getNode(ISD::AND, dl, WideVT, Hi, SrcEltBitMask);
525 Lo = DAG.getNode(ISD::OR, dl, WideVT, Lo, Hi);
528 default: llvm_unreachable("Unknown extended-load op!");
530 Lo = DAG.getAnyExtOrTrunc(Lo, dl, DstEltVT);
533 Lo = DAG.getZExtOrTrunc(Lo, dl, DstEltVT);
536 ShAmt = DAG.getConstant(WideBits - SrcEltBits,
537 TLI.getShiftAmountTy(WideVT));
538 Lo = DAG.getNode(ISD::SHL, dl, WideVT, Lo, ShAmt);
539 Lo = DAG.getNode(ISD::SRA, dl, WideVT, Lo, ShAmt);
540 Lo = DAG.getSExtOrTrunc(Lo, dl, DstEltVT);
546 unsigned Stride = SrcVT.getScalarType().getSizeInBits()/8;
548 for (unsigned Idx=0; Idx<NumElem; Idx++) {
549 SDValue ScalarLoad = DAG.getExtLoad(ExtType, dl,
550 Op.getNode()->getValueType(0).getScalarType(),
551 Chain, BasePTR, LD->getPointerInfo().getWithOffset(Idx * Stride),
552 SrcVT.getScalarType(),
553 LD->isVolatile(), LD->isNonTemporal(),
554 LD->getAlignment(), LD->getTBAAInfo());
556 BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
557 DAG.getConstant(Stride, BasePTR.getValueType()));
559 Vals.push_back(ScalarLoad.getValue(0));
560 LoadChains.push_back(ScalarLoad.getValue(1));
564 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
565 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
566 Op.getNode()->getValueType(0), Vals);
568 AddLegalizedOperand(Op.getValue(0), Value);
569 AddLegalizedOperand(Op.getValue(1), NewChain);
571 return (Op.getResNo() ? NewChain : Value);
574 SDValue VectorLegalizer::ExpandStore(SDValue Op) {
576 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
577 SDValue Chain = ST->getChain();
578 SDValue BasePTR = ST->getBasePtr();
579 SDValue Value = ST->getValue();
580 EVT StVT = ST->getMemoryVT();
582 unsigned Alignment = ST->getAlignment();
583 bool isVolatile = ST->isVolatile();
584 bool isNonTemporal = ST->isNonTemporal();
585 const MDNode *TBAAInfo = ST->getTBAAInfo();
587 unsigned NumElem = StVT.getVectorNumElements();
588 // The type of the data we want to save
589 EVT RegVT = Value.getValueType();
590 EVT RegSclVT = RegVT.getScalarType();
591 // The type of data as saved in memory.
592 EVT MemSclVT = StVT.getScalarType();
594 // Cast floats into integers
595 unsigned ScalarSize = MemSclVT.getSizeInBits();
597 // Round odd types to the next pow of two.
598 if (!isPowerOf2_32(ScalarSize))
599 ScalarSize = NextPowerOf2(ScalarSize);
601 // Store Stride in bytes
602 unsigned Stride = ScalarSize/8;
603 // Extract each of the elements from the original vector
604 // and save them into memory individually.
605 SmallVector<SDValue, 8> Stores;
606 for (unsigned Idx = 0; Idx < NumElem; Idx++) {
607 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
608 RegSclVT, Value, DAG.getConstant(Idx, TLI.getVectorIdxTy()));
610 // This scalar TruncStore may be illegal, but we legalize it later.
611 SDValue Store = DAG.getTruncStore(Chain, dl, Ex, BasePTR,
612 ST->getPointerInfo().getWithOffset(Idx*Stride), MemSclVT,
613 isVolatile, isNonTemporal, Alignment, TBAAInfo);
615 BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
616 DAG.getConstant(Stride, BasePTR.getValueType()));
618 Stores.push_back(Store);
620 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
621 AddLegalizedOperand(Op, TF);
625 SDValue VectorLegalizer::ExpandSELECT(SDValue Op) {
626 // Lower a select instruction where the condition is a scalar and the
627 // operands are vectors. Lower this select to VSELECT and implement it
628 // using XOR AND OR. The selector bit is broadcasted.
629 EVT VT = Op.getValueType();
632 SDValue Mask = Op.getOperand(0);
633 SDValue Op1 = Op.getOperand(1);
634 SDValue Op2 = Op.getOperand(2);
636 assert(VT.isVector() && !Mask.getValueType().isVector()
637 && Op1.getValueType() == Op2.getValueType() && "Invalid type");
639 unsigned NumElem = VT.getVectorNumElements();
641 // If we can't even use the basic vector operations of
642 // AND,OR,XOR, we will have to scalarize the op.
643 // Notice that the operation may be 'promoted' which means that it is
644 // 'bitcasted' to another type which is handled.
645 // Also, we need to be able to construct a splat vector using BUILD_VECTOR.
646 if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
647 TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
648 TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand ||
649 TLI.getOperationAction(ISD::BUILD_VECTOR, VT) == TargetLowering::Expand)
650 return DAG.UnrollVectorOp(Op.getNode());
652 // Generate a mask operand.
653 EVT MaskTy = VT.changeVectorElementTypeToInteger();
655 // What is the size of each element in the vector mask.
656 EVT BitTy = MaskTy.getScalarType();
658 Mask = DAG.getSelect(DL, BitTy, Mask,
659 DAG.getConstant(APInt::getAllOnesValue(BitTy.getSizeInBits()), BitTy),
660 DAG.getConstant(0, BitTy));
662 // Broadcast the mask so that the entire vector is all-one or all zero.
663 SmallVector<SDValue, 8> Ops(NumElem, Mask);
664 Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskTy, Ops);
666 // Bitcast the operands to be the same type as the mask.
667 // This is needed when we select between FP types because
668 // the mask is a vector of integers.
669 Op1 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op1);
670 Op2 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op2);
672 SDValue AllOnes = DAG.getConstant(
673 APInt::getAllOnesValue(BitTy.getSizeInBits()), MaskTy);
674 SDValue NotMask = DAG.getNode(ISD::XOR, DL, MaskTy, Mask, AllOnes);
676 Op1 = DAG.getNode(ISD::AND, DL, MaskTy, Op1, Mask);
677 Op2 = DAG.getNode(ISD::AND, DL, MaskTy, Op2, NotMask);
678 SDValue Val = DAG.getNode(ISD::OR, DL, MaskTy, Op1, Op2);
679 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
682 SDValue VectorLegalizer::ExpandSEXTINREG(SDValue Op) {
683 EVT VT = Op.getValueType();
685 // Make sure that the SRA and SHL instructions are available.
686 if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Expand ||
687 TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Expand)
688 return DAG.UnrollVectorOp(Op.getNode());
691 EVT OrigTy = cast<VTSDNode>(Op->getOperand(1))->getVT();
693 unsigned BW = VT.getScalarType().getSizeInBits();
694 unsigned OrigBW = OrigTy.getScalarType().getSizeInBits();
695 SDValue ShiftSz = DAG.getConstant(BW - OrigBW, VT);
697 Op = Op.getOperand(0);
698 Op = DAG.getNode(ISD::SHL, DL, VT, Op, ShiftSz);
699 return DAG.getNode(ISD::SRA, DL, VT, Op, ShiftSz);
702 SDValue VectorLegalizer::ExpandBSWAP(SDValue Op) {
703 EVT VT = Op.getValueType();
705 // Generate a byte wise shuffle mask for the BSWAP.
706 SmallVector<int, 16> ShuffleMask;
707 int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
708 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I)
709 for (int J = ScalarSizeInBytes - 1; J >= 0; --J)
710 ShuffleMask.push_back((I * ScalarSizeInBytes) + J);
712 EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, ShuffleMask.size());
714 // Only emit a shuffle if the mask is legal.
715 if (!TLI.isShuffleMaskLegal(ShuffleMask, ByteVT))
716 return DAG.UnrollVectorOp(Op.getNode());
719 Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
720 Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT),
722 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
725 SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) {
726 // Implement VSELECT in terms of XOR, AND, OR
727 // on platforms which do not support blend natively.
730 SDValue Mask = Op.getOperand(0);
731 SDValue Op1 = Op.getOperand(1);
732 SDValue Op2 = Op.getOperand(2);
734 EVT VT = Mask.getValueType();
736 // If we can't even use the basic vector operations of
737 // AND,OR,XOR, we will have to scalarize the op.
738 // Notice that the operation may be 'promoted' which means that it is
739 // 'bitcasted' to another type which is handled.
740 // This operation also isn't safe with AND, OR, XOR when the boolean
741 // type is 0/1 as we need an all ones vector constant to mask with.
742 // FIXME: Sign extend 1 to all ones if thats legal on the target.
743 if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
744 TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
745 TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand ||
746 TLI.getBooleanContents(true) !=
747 TargetLowering::ZeroOrNegativeOneBooleanContent)
748 return DAG.UnrollVectorOp(Op.getNode());
750 // If the mask and the type are different sizes, unroll the vector op. This
751 // can occur when getSetCCResultType returns something that is different in
752 // size from the operand types. For example, v4i8 = select v4i32, v4i8, v4i8.
753 if (VT.getSizeInBits() != Op1.getValueType().getSizeInBits())
754 return DAG.UnrollVectorOp(Op.getNode());
756 // Bitcast the operands to be the same type as the mask.
757 // This is needed when we select between FP types because
758 // the mask is a vector of integers.
759 Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
760 Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
762 SDValue AllOnes = DAG.getConstant(
763 APInt::getAllOnesValue(VT.getScalarType().getSizeInBits()), VT);
764 SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
766 Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
767 Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
768 SDValue Val = DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
769 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
772 SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) {
773 EVT VT = Op.getOperand(0).getValueType();
776 // Make sure that the SINT_TO_FP and SRL instructions are available.
777 if (TLI.getOperationAction(ISD::SINT_TO_FP, VT) == TargetLowering::Expand ||
778 TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Expand)
779 return DAG.UnrollVectorOp(Op.getNode());
781 EVT SVT = VT.getScalarType();
782 assert((SVT.getSizeInBits() == 64 || SVT.getSizeInBits() == 32) &&
783 "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
785 unsigned BW = SVT.getSizeInBits();
786 SDValue HalfWord = DAG.getConstant(BW/2, VT);
788 // Constants to clear the upper part of the word.
789 // Notice that we can also use SHL+SHR, but using a constant is slightly
791 uint64_t HWMask = (SVT.getSizeInBits()==64)?0x00000000FFFFFFFF:0x0000FFFF;
792 SDValue HalfWordMask = DAG.getConstant(HWMask, VT);
794 // Two to the power of half-word-size.
795 SDValue TWOHW = DAG.getConstantFP((1<<(BW/2)), Op.getValueType());
797 // Clear upper part of LO, lower HI
798 SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Op.getOperand(0), HalfWord);
799 SDValue LO = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), HalfWordMask);
801 // Convert hi and lo to floats
802 // Convert the hi part back to the upper values
803 SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI);
804 fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW);
805 SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO);
807 // Add the two halves
808 return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO);
812 SDValue VectorLegalizer::ExpandFNEG(SDValue Op) {
813 if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) {
814 SDValue Zero = DAG.getConstantFP(-0.0, Op.getValueType());
815 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
816 Zero, Op.getOperand(0));
818 return DAG.UnrollVectorOp(Op.getNode());
821 SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) {
822 EVT VT = Op.getValueType();
823 unsigned NumElems = VT.getVectorNumElements();
824 EVT EltVT = VT.getVectorElementType();
825 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2);
826 EVT TmpEltVT = LHS.getValueType().getVectorElementType();
828 SmallVector<SDValue, 8> Ops(NumElems);
829 for (unsigned i = 0; i < NumElems; ++i) {
830 SDValue LHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
831 DAG.getConstant(i, TLI.getVectorIdxTy()));
832 SDValue RHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
833 DAG.getConstant(i, TLI.getVectorIdxTy()));
834 Ops[i] = DAG.getNode(ISD::SETCC, dl,
835 TLI.getSetCCResultType(*DAG.getContext(), TmpEltVT),
836 LHSElem, RHSElem, CC);
837 Ops[i] = DAG.getSelect(dl, EltVT, Ops[i],
838 DAG.getConstant(APInt::getAllOnesValue
839 (EltVT.getSizeInBits()), EltVT),
840 DAG.getConstant(0, EltVT));
842 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
847 bool SelectionDAG::LegalizeVectors() {
848 return VectorLegalizer(*this).Run();