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 /// 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 DenseMap<SDValue, SDValue> LegalizedNodes;
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.
50 LegalizedNodes.insert(std::make_pair(To, To));
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
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 vselect in terms of XOR, AND, OR when blend is not supported
66 SDValue ExpandVSELECT(SDValue Op);
67 SDValue ExpandLoad(SDValue Op);
68 SDValue ExpandStore(SDValue Op);
69 SDValue ExpandFNEG(SDValue Op);
70 // Implements vector promotion; this is essentially just bitcasting the
71 // operands to a different type and bitcasting the result back to the
73 SDValue PromoteVectorOp(SDValue Op);
77 VectorLegalizer(SelectionDAG& dag) :
78 DAG(dag), TLI(dag.getTargetLoweringInfo()), Changed(false) {}
81 bool VectorLegalizer::Run() {
82 // The legalize process is inherently a bottom-up recursive process (users
83 // legalize their uses before themselves). Given infinite stack space, we
84 // could just start legalizing on the root and traverse the whole graph. In
85 // practice however, this causes us to run out of stack space on large basic
86 // blocks. To avoid this problem, compute an ordering of the nodes where each
87 // node is only legalized after all of its operands are legalized.
88 DAG.AssignTopologicalOrder();
89 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
90 E = prior(DAG.allnodes_end()); I != llvm::next(E); ++I)
91 LegalizeOp(SDValue(I, 0));
93 // Finally, it's possible the root changed. Get the new root.
94 SDValue OldRoot = DAG.getRoot();
95 assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
96 DAG.setRoot(LegalizedNodes[OldRoot]);
98 LegalizedNodes.clear();
100 // Remove dead nodes now.
101 DAG.RemoveDeadNodes();
106 SDValue VectorLegalizer::TranslateLegalizeResults(SDValue Op, SDValue Result) {
107 // Generic legalization: just pass the operand through.
108 for (unsigned i = 0, e = Op.getNode()->getNumValues(); i != e; ++i)
109 AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
110 return Result.getValue(Op.getResNo());
113 SDValue VectorLegalizer::LegalizeOp(SDValue Op) {
114 // Note that LegalizeOp may be reentered even from single-use nodes, which
115 // means that we always must cache transformed nodes.
116 DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
117 if (I != LegalizedNodes.end()) return I->second;
119 SDNode* Node = Op.getNode();
121 // Legalize the operands
122 SmallVector<SDValue, 8> Ops;
123 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
124 Ops.push_back(LegalizeOp(Node->getOperand(i)));
127 SDValue(DAG.UpdateNodeOperands(Op.getNode(), Ops.data(), Ops.size()), 0);
129 if (Op.getOpcode() == ISD::LOAD) {
130 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
131 ISD::LoadExtType ExtType = LD->getExtensionType();
132 if (LD->getMemoryVT().isVector() && ExtType != ISD::NON_EXTLOAD) {
133 if (TLI.isLoadExtLegal(LD->getExtensionType(), LD->getMemoryVT()))
134 return TranslateLegalizeResults(Op, Result);
136 return LegalizeOp(ExpandLoad(Op));
138 } else if (Op.getOpcode() == ISD::STORE) {
139 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
140 EVT StVT = ST->getMemoryVT();
141 EVT ValVT = ST->getValue().getValueType();
142 if (StVT.isVector() && ST->isTruncatingStore())
143 switch (TLI.getTruncStoreAction(ValVT, StVT)) {
144 default: llvm_unreachable("This action is not supported yet!");
145 case TargetLowering::Legal:
146 return TranslateLegalizeResults(Op, Result);
147 case TargetLowering::Custom:
149 return LegalizeOp(TLI.LowerOperation(Result, DAG));
150 case TargetLowering::Expand:
152 return LegalizeOp(ExpandStore(Op));
156 bool HasVectorValue = false;
157 for (SDNode::value_iterator J = Node->value_begin(), E = Node->value_end();
160 HasVectorValue |= J->isVector();
162 return TranslateLegalizeResults(Op, Result);
165 switch (Op.getOpcode()) {
167 return TranslateLegalizeResults(Op, Result);
190 case ISD::CTLZ_ZERO_UNDEF:
191 case ISD::CTTZ_ZERO_UNDEF:
197 case ISD::ZERO_EXTEND:
198 case ISD::ANY_EXTEND:
200 case ISD::SIGN_EXTEND:
201 case ISD::FP_TO_SINT:
202 case ISD::FP_TO_UINT:
218 case ISD::FNEARBYINT:
220 case ISD::SIGN_EXTEND_INREG:
221 QueryType = Node->getValueType(0);
223 case ISD::FP_ROUND_INREG:
224 QueryType = cast<VTSDNode>(Node->getOperand(1))->getVT();
226 case ISD::SINT_TO_FP:
227 case ISD::UINT_TO_FP:
228 QueryType = Node->getOperand(0).getValueType();
232 switch (TLI.getOperationAction(Node->getOpcode(), QueryType)) {
233 case TargetLowering::Promote:
234 // "Promote" the operation by bitcasting
235 Result = PromoteVectorOp(Op);
238 case TargetLowering::Legal: break;
239 case TargetLowering::Custom: {
240 SDValue Tmp1 = TLI.LowerOperation(Op, DAG);
241 if (Tmp1.getNode()) {
247 case TargetLowering::Expand:
248 if (Node->getOpcode() == ISD::VSELECT)
249 Result = ExpandVSELECT(Op);
250 else if (Node->getOpcode() == ISD::UINT_TO_FP)
251 Result = ExpandUINT_TO_FLOAT(Op);
252 else if (Node->getOpcode() == ISD::FNEG)
253 Result = ExpandFNEG(Op);
254 else if (Node->getOpcode() == ISD::SETCC)
255 Result = UnrollVSETCC(Op);
257 Result = DAG.UnrollVectorOp(Op.getNode());
261 // Make sure that the generated code is itself legal.
263 Result = LegalizeOp(Result);
267 // Note that LegalizeOp may be reentered even from single-use nodes, which
268 // means that we always must cache transformed nodes.
269 AddLegalizedOperand(Op, Result);
273 SDValue VectorLegalizer::PromoteVectorOp(SDValue Op) {
274 // Vector "promotion" is basically just bitcasting and doing the operation
275 // in a different type. For example, x86 promotes ISD::AND on v2i32 to
277 EVT VT = Op.getValueType();
278 assert(Op.getNode()->getNumValues() == 1 &&
279 "Can't promote a vector with multiple results!");
280 EVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
281 DebugLoc dl = Op.getDebugLoc();
282 SmallVector<SDValue, 4> Operands(Op.getNumOperands());
284 for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
285 if (Op.getOperand(j).getValueType().isVector())
286 Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Op.getOperand(j));
288 Operands[j] = Op.getOperand(j);
291 Op = DAG.getNode(Op.getOpcode(), dl, NVT, &Operands[0], Operands.size());
293 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
297 SDValue VectorLegalizer::ExpandLoad(SDValue Op) {
298 DebugLoc dl = Op.getDebugLoc();
299 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
300 SDValue Chain = LD->getChain();
301 SDValue BasePTR = LD->getBasePtr();
302 EVT SrcVT = LD->getMemoryVT();
303 ISD::LoadExtType ExtType = LD->getExtensionType();
305 SmallVector<SDValue, 8> LoadVals;
306 SmallVector<SDValue, 8> LoadChains;
307 unsigned NumElem = SrcVT.getVectorNumElements();
308 unsigned Stride = SrcVT.getScalarType().getSizeInBits()/8;
310 for (unsigned Idx=0; Idx<NumElem; Idx++) {
311 SDValue ScalarLoad = DAG.getExtLoad(ExtType, dl,
312 Op.getNode()->getValueType(0).getScalarType(),
313 Chain, BasePTR, LD->getPointerInfo().getWithOffset(Idx * Stride),
314 SrcVT.getScalarType(),
315 LD->isVolatile(), LD->isNonTemporal(),
318 BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
319 DAG.getIntPtrConstant(Stride));
321 LoadVals.push_back(ScalarLoad.getValue(0));
322 LoadChains.push_back(ScalarLoad.getValue(1));
325 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
326 &LoadChains[0], LoadChains.size());
327 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
328 Op.getNode()->getValueType(0), &LoadVals[0], LoadVals.size());
330 AddLegalizedOperand(Op.getValue(0), Value);
331 AddLegalizedOperand(Op.getValue(1), NewChain);
333 return (Op.getResNo() ? NewChain : Value);
336 SDValue VectorLegalizer::ExpandStore(SDValue Op) {
337 DebugLoc dl = Op.getDebugLoc();
338 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
339 SDValue Chain = ST->getChain();
340 SDValue BasePTR = ST->getBasePtr();
341 SDValue Value = ST->getValue();
342 EVT StVT = ST->getMemoryVT();
344 unsigned Alignment = ST->getAlignment();
345 bool isVolatile = ST->isVolatile();
346 bool isNonTemporal = ST->isNonTemporal();
348 unsigned NumElem = StVT.getVectorNumElements();
349 // The type of the data we want to save
350 EVT RegVT = Value.getValueType();
351 EVT RegSclVT = RegVT.getScalarType();
352 // The type of data as saved in memory.
353 EVT MemSclVT = StVT.getScalarType();
355 // Cast floats into integers
356 unsigned ScalarSize = MemSclVT.getSizeInBits();
358 // Round odd types to the next pow of two.
359 if (!isPowerOf2_32(ScalarSize))
360 ScalarSize = NextPowerOf2(ScalarSize);
362 // Store Stride in bytes
363 unsigned Stride = ScalarSize/8;
364 // Extract each of the elements from the original vector
365 // and save them into memory individually.
366 SmallVector<SDValue, 8> Stores;
367 for (unsigned Idx = 0; Idx < NumElem; Idx++) {
368 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
369 RegSclVT, Value, DAG.getIntPtrConstant(Idx));
371 // This scalar TruncStore may be illegal, but we legalize it later.
372 SDValue Store = DAG.getTruncStore(Chain, dl, Ex, BasePTR,
373 ST->getPointerInfo().getWithOffset(Idx*Stride), MemSclVT,
374 isVolatile, isNonTemporal, Alignment);
376 BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
377 DAG.getIntPtrConstant(Stride));
379 Stores.push_back(Store);
381 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
382 &Stores[0], Stores.size());
383 AddLegalizedOperand(Op, TF);
387 SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) {
388 // Implement VSELECT in terms of XOR, AND, OR
389 // on platforms which do not support blend natively.
390 EVT VT = Op.getOperand(0).getValueType();
391 DebugLoc DL = Op.getDebugLoc();
393 SDValue Mask = Op.getOperand(0);
394 SDValue Op1 = Op.getOperand(1);
395 SDValue Op2 = Op.getOperand(2);
397 // If we can't even use the basic vector operations of
398 // AND,OR,XOR, we will have to scalarize the op.
399 // Notice that the operation may be 'promoted' which means that it is
400 // 'bitcasted' to another type which is handled.
401 if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
402 TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
403 TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand)
404 return DAG.UnrollVectorOp(Op.getNode());
406 assert(VT.getSizeInBits() == Op.getOperand(1).getValueType().getSizeInBits()
407 && "Invalid mask size");
408 // Bitcast the operands to be the same type as the mask.
409 // This is needed when we select between FP types because
410 // the mask is a vector of integers.
411 Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
412 Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
414 SDValue AllOnes = DAG.getConstant(
415 APInt::getAllOnesValue(VT.getScalarType().getSizeInBits()), VT);
416 SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
418 Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
419 Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
420 return DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
423 SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) {
424 EVT VT = Op.getOperand(0).getValueType();
425 DebugLoc DL = Op.getDebugLoc();
427 // Make sure that the SINT_TO_FP and SRL instructions are available.
428 if (TLI.getOperationAction(ISD::SINT_TO_FP, VT) == TargetLowering::Expand ||
429 TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Expand)
430 return DAG.UnrollVectorOp(Op.getNode());
432 EVT SVT = VT.getScalarType();
433 assert((SVT.getSizeInBits() == 64 || SVT.getSizeInBits() == 32) &&
434 "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
436 unsigned BW = SVT.getSizeInBits();
437 SDValue HalfWord = DAG.getConstant(BW/2, VT);
439 // Constants to clear the upper part of the word.
440 // Notice that we can also use SHL+SHR, but using a constant is slightly
442 uint64_t HWMask = (SVT.getSizeInBits()==64)?0x00000000FFFFFFFF:0x0000FFFF;
443 SDValue HalfWordMask = DAG.getConstant(HWMask, VT);
445 // Two to the power of half-word-size.
446 SDValue TWOHW = DAG.getConstantFP((1<<(BW/2)), Op.getValueType());
448 // Clear upper part of LO, lower HI
449 SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Op.getOperand(0), HalfWord);
450 SDValue LO = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), HalfWordMask);
452 // Convert hi and lo to floats
453 // Convert the hi part back to the upper values
454 SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI);
455 fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW);
456 SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO);
458 // Add the two halves
459 return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO);
463 SDValue VectorLegalizer::ExpandFNEG(SDValue Op) {
464 if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) {
465 SDValue Zero = DAG.getConstantFP(-0.0, Op.getValueType());
466 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
467 Zero, Op.getOperand(0));
469 return DAG.UnrollVectorOp(Op.getNode());
472 SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) {
473 EVT VT = Op.getValueType();
474 unsigned NumElems = VT.getVectorNumElements();
475 EVT EltVT = VT.getVectorElementType();
476 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2);
477 EVT TmpEltVT = LHS.getValueType().getVectorElementType();
478 DebugLoc dl = Op.getDebugLoc();
479 SmallVector<SDValue, 8> Ops(NumElems);
480 for (unsigned i = 0; i < NumElems; ++i) {
481 SDValue LHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
482 DAG.getIntPtrConstant(i));
483 SDValue RHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
484 DAG.getIntPtrConstant(i));
485 Ops[i] = DAG.getNode(ISD::SETCC, dl, TLI.getSetCCResultType(TmpEltVT),
486 LHSElem, RHSElem, CC);
487 Ops[i] = DAG.getNode(ISD::SELECT, dl, EltVT, Ops[i],
488 DAG.getConstant(APInt::getAllOnesValue
489 (EltVT.getSizeInBits()), EltVT),
490 DAG.getConstant(0, EltVT));
492 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElems);
497 bool SelectionDAG::LegalizeVectors() {
498 return VectorLegalizer(*this).Run();