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 DenseMap<SDValue, SDValue> 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 vselect in terms of XOR, AND, OR when blend is not supported 65 // by the target. 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 72 // original type. 73 SDValue PromoteVectorOp(SDValue Op); 74 75 public: 76 bool Run(); 77 VectorLegalizer(SelectionDAG& dag) : 78 DAG(dag), TLI(dag.getTargetLoweringInfo()), Changed(false) {} 79 }; 80 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)); 92 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]); 97 98 LegalizedNodes.clear(); 99 100 // Remove dead nodes now. 101 DAG.RemoveDeadNodes(); 102 103 return Changed; 104 } 105 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()); 111 } 112 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; 118 119 SDNode* Node = Op.getNode(); 120 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))); 125 126 SDValue Result = 127 SDValue(DAG.UpdateNodeOperands(Op.getNode(), Ops.data(), Ops.size()), 0); 128 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); 135 Changed = true; 136 return LegalizeOp(ExpandLoad(Op)); 137 } 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: assert(0 && "This action is not supported yet!"); 145 case TargetLowering::Legal: 146 return TranslateLegalizeResults(Op, Result); 147 case TargetLowering::Custom: 148 Changed = true; 149 return LegalizeOp(TLI.LowerOperation(Result, DAG)); 150 case TargetLowering::Expand: 151 Changed = true; 152 return LegalizeOp(ExpandStore(Op)); 153 } 154 } 155 156 bool HasVectorValue = false; 157 for (SDNode::value_iterator J = Node->value_begin(), E = Node->value_end(); 158 J != E; 159 ++J) 160 HasVectorValue |= J->isVector(); 161 if (!HasVectorValue) 162 return TranslateLegalizeResults(Op, Result); 163 164 EVT QueryType; 165 switch (Op.getOpcode()) { 166 default: 167 return TranslateLegalizeResults(Op, Result); 168 case ISD::ADD: 169 case ISD::SUB: 170 case ISD::MUL: 171 case ISD::SDIV: 172 case ISD::UDIV: 173 case ISD::SREM: 174 case ISD::UREM: 175 case ISD::FADD: 176 case ISD::FSUB: 177 case ISD::FMUL: 178 case ISD::FDIV: 179 case ISD::FREM: 180 case ISD::AND: 181 case ISD::OR: 182 case ISD::XOR: 183 case ISD::SHL: 184 case ISD::SRA: 185 case ISD::SRL: 186 case ISD::ROTL: 187 case ISD::ROTR: 188 case ISD::CTTZ: 189 case ISD::CTLZ: 190 case ISD::CTPOP: 191 case ISD::SELECT: 192 case ISD::VSELECT: 193 case ISD::SELECT_CC: 194 case ISD::SETCC: 195 case ISD::ZERO_EXTEND: 196 case ISD::ANY_EXTEND: 197 case ISD::TRUNCATE: 198 case ISD::SIGN_EXTEND: 199 case ISD::FP_TO_SINT: 200 case ISD::FP_TO_UINT: 201 case ISD::FNEG: 202 case ISD::FABS: 203 case ISD::FSQRT: 204 case ISD::FSIN: 205 case ISD::FCOS: 206 case ISD::FPOWI: 207 case ISD::FPOW: 208 case ISD::FLOG: 209 case ISD::FLOG2: 210 case ISD::FLOG10: 211 case ISD::FEXP: 212 case ISD::FEXP2: 213 case ISD::FCEIL: 214 case ISD::FTRUNC: 215 case ISD::FRINT: 216 case ISD::FNEARBYINT: 217 case ISD::FFLOOR: 218 case ISD::SIGN_EXTEND_INREG: 219 QueryType = Node->getValueType(0); 220 break; 221 case ISD::FP_ROUND_INREG: 222 QueryType = cast<VTSDNode>(Node->getOperand(1))->getVT(); 223 break; 224 case ISD::SINT_TO_FP: 225 case ISD::UINT_TO_FP: 226 QueryType = Node->getOperand(0).getValueType(); 227 break; 228 } 229 230 switch (TLI.getOperationAction(Node->getOpcode(), QueryType)) { 231 case TargetLowering::Promote: 232 // "Promote" the operation by bitcasting 233 Result = PromoteVectorOp(Op); 234 Changed = true; 235 break; 236 case TargetLowering::Legal: break; 237 case TargetLowering::Custom: { 238 SDValue Tmp1 = TLI.LowerOperation(Op, DAG); 239 if (Tmp1.getNode()) { 240 Result = Tmp1; 241 break; 242 } 243 // FALL THROUGH 244 } 245 case TargetLowering::Expand: 246 if (Node->getOpcode() == ISD::VSELECT) 247 Result = ExpandVSELECT(Op); 248 else if (Node->getOpcode() == ISD::UINT_TO_FP) 249 Result = ExpandUINT_TO_FLOAT(Op); 250 else if (Node->getOpcode() == ISD::FNEG) 251 Result = ExpandFNEG(Op); 252 else if (Node->getOpcode() == ISD::SETCC) 253 Result = UnrollVSETCC(Op); 254 else 255 Result = DAG.UnrollVectorOp(Op.getNode()); 256 break; 257 } 258 259 // Make sure that the generated code is itself legal. 260 if (Result != Op) { 261 Result = LegalizeOp(Result); 262 Changed = true; 263 } 264 265 // Note that LegalizeOp may be reentered even from single-use nodes, which 266 // means that we always must cache transformed nodes. 267 AddLegalizedOperand(Op, Result); 268 return Result; 269 } 270 271 SDValue VectorLegalizer::PromoteVectorOp(SDValue Op) { 272 // Vector "promotion" is basically just bitcasting and doing the operation 273 // in a different type. For example, x86 promotes ISD::AND on v2i32 to 274 // v1i64. 275 EVT VT = Op.getValueType(); 276 assert(Op.getNode()->getNumValues() == 1 && 277 "Can't promote a vector with multiple results!"); 278 EVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT); 279 DebugLoc dl = Op.getDebugLoc(); 280 SmallVector<SDValue, 4> Operands(Op.getNumOperands()); 281 282 for (unsigned j = 0; j != Op.getNumOperands(); ++j) { 283 if (Op.getOperand(j).getValueType().isVector()) 284 Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Op.getOperand(j)); 285 else 286 Operands[j] = Op.getOperand(j); 287 } 288 289 Op = DAG.getNode(Op.getOpcode(), dl, NVT, &Operands[0], Operands.size()); 290 291 return DAG.getNode(ISD::BITCAST, dl, VT, Op); 292 } 293 294 295 SDValue VectorLegalizer::ExpandLoad(SDValue Op) { 296 DebugLoc dl = Op.getDebugLoc(); 297 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode()); 298 SDValue Chain = LD->getChain(); 299 SDValue BasePTR = LD->getBasePtr(); 300 EVT SrcVT = LD->getMemoryVT(); 301 ISD::LoadExtType ExtType = LD->getExtensionType(); 302 303 SmallVector<SDValue, 8> LoadVals; 304 SmallVector<SDValue, 8> LoadChains; 305 unsigned NumElem = SrcVT.getVectorNumElements(); 306 unsigned Stride = SrcVT.getScalarType().getSizeInBits()/8; 307 308 for (unsigned Idx=0; Idx<NumElem; Idx++) { 309 SDValue ScalarLoad = DAG.getExtLoad(ExtType, dl, 310 Op.getNode()->getValueType(0).getScalarType(), 311 Chain, BasePTR, LD->getPointerInfo().getWithOffset(Idx * Stride), 312 SrcVT.getScalarType(), 313 LD->isVolatile(), LD->isNonTemporal(), 314 LD->getAlignment()); 315 316 BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR, 317 DAG.getIntPtrConstant(Stride)); 318 319 LoadVals.push_back(ScalarLoad.getValue(0)); 320 LoadChains.push_back(ScalarLoad.getValue(1)); 321 } 322 323 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 324 &LoadChains[0], LoadChains.size()); 325 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, 326 Op.getNode()->getValueType(0), &LoadVals[0], LoadVals.size()); 327 328 AddLegalizedOperand(Op.getValue(0), Value); 329 AddLegalizedOperand(Op.getValue(1), NewChain); 330 331 return (Op.getResNo() ? NewChain : Value); 332 } 333 334 SDValue VectorLegalizer::ExpandStore(SDValue Op) { 335 DebugLoc dl = Op.getDebugLoc(); 336 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode()); 337 SDValue Chain = ST->getChain(); 338 SDValue BasePTR = ST->getBasePtr(); 339 SDValue Value = ST->getValue(); 340 EVT StVT = ST->getMemoryVT(); 341 342 unsigned Alignment = ST->getAlignment(); 343 bool isVolatile = ST->isVolatile(); 344 bool isNonTemporal = ST->isNonTemporal(); 345 346 unsigned NumElem = StVT.getVectorNumElements(); 347 // The type of the data we want to save 348 EVT RegVT = Value.getValueType(); 349 EVT RegSclVT = RegVT.getScalarType(); 350 // The type of data as saved in memory. 351 EVT MemSclVT = StVT.getScalarType(); 352 353 // Cast floats into integers 354 unsigned ScalarSize = MemSclVT.getSizeInBits(); 355 356 // Round odd types to the next pow of two. 357 if (!isPowerOf2_32(ScalarSize)) 358 ScalarSize = NextPowerOf2(ScalarSize); 359 360 // Store Stride in bytes 361 unsigned Stride = ScalarSize/8; 362 // Extract each of the elements from the original vector 363 // and save them into memory individually. 364 SmallVector<SDValue, 8> Stores; 365 for (unsigned Idx = 0; Idx < NumElem; Idx++) { 366 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 367 RegSclVT, Value, DAG.getIntPtrConstant(Idx)); 368 369 // This scalar TruncStore may be illegal, but we legalize it later. 370 SDValue Store = DAG.getTruncStore(Chain, dl, Ex, BasePTR, 371 ST->getPointerInfo().getWithOffset(Idx*Stride), MemSclVT, 372 isVolatile, isNonTemporal, Alignment); 373 374 BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR, 375 DAG.getIntPtrConstant(Stride)); 376 377 Stores.push_back(Store); 378 } 379 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 380 &Stores[0], Stores.size()); 381 AddLegalizedOperand(Op, TF); 382 return TF; 383 } 384 385 SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) { 386 // Implement VSELECT in terms of XOR, AND, OR 387 // on platforms which do not support blend natively. 388 EVT VT = Op.getOperand(0).getValueType(); 389 DebugLoc DL = Op.getDebugLoc(); 390 391 SDValue Mask = Op.getOperand(0); 392 SDValue Op1 = Op.getOperand(1); 393 SDValue Op2 = Op.getOperand(2); 394 395 // If we can't even use the basic vector operations of 396 // AND,OR,XOR, we will have to scalarize the op. 397 if (!TLI.isOperationLegalOrCustom(ISD::AND, VT) || 398 !TLI.isOperationLegalOrCustom(ISD::XOR, VT) || 399 !TLI.isOperationLegalOrCustom(ISD::OR, VT)) 400 return DAG.UnrollVectorOp(Op.getNode()); 401 402 assert(VT.getSizeInBits() == Op.getOperand(1).getValueType().getSizeInBits() 403 && "Invalid mask size"); 404 // Bitcast the operands to be the same type as the mask. 405 // This is needed when we select between FP types because 406 // the mask is a vector of integers. 407 Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1); 408 Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2); 409 410 SDValue AllOnes = DAG.getConstant( 411 APInt::getAllOnesValue(VT.getScalarType().getSizeInBits()), VT); 412 SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes); 413 414 Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask); 415 Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask); 416 return DAG.getNode(ISD::OR, DL, VT, Op1, Op2); 417 } 418 419 SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) { 420 EVT VT = Op.getOperand(0).getValueType(); 421 DebugLoc DL = Op.getDebugLoc(); 422 423 // Make sure that the SINT_TO_FP and SRL instructions are available. 424 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, VT) || 425 !TLI.isOperationLegalOrCustom(ISD::SRL, VT)) 426 return DAG.UnrollVectorOp(Op.getNode()); 427 428 EVT SVT = VT.getScalarType(); 429 assert((SVT.getSizeInBits() == 64 || SVT.getSizeInBits() == 32) && 430 "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide"); 431 432 unsigned BW = SVT.getSizeInBits(); 433 SDValue HalfWord = DAG.getConstant(BW/2, VT); 434 435 // Constants to clear the upper part of the word. 436 // Notice that we can also use SHL+SHR, but using a constant is slightly 437 // faster on x86. 438 uint64_t HWMask = (SVT.getSizeInBits()==64)?0x00000000FFFFFFFF:0x0000FFFF; 439 SDValue HalfWordMask = DAG.getConstant(HWMask, VT); 440 441 // Two to the power of half-word-size. 442 SDValue TWOHW = DAG.getConstantFP((1<<(BW/2)), Op.getValueType()); 443 444 // Clear upper part of LO, lower HI 445 SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Op.getOperand(0), HalfWord); 446 SDValue LO = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), HalfWordMask); 447 448 // Convert hi and lo to floats 449 // Convert the hi part back to the upper values 450 SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI); 451 fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW); 452 SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO); 453 454 // Add the two halves 455 return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO); 456 } 457 458 459 SDValue VectorLegalizer::ExpandFNEG(SDValue Op) { 460 if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) { 461 SDValue Zero = DAG.getConstantFP(-0.0, Op.getValueType()); 462 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 463 Zero, Op.getOperand(0)); 464 } 465 return DAG.UnrollVectorOp(Op.getNode()); 466 } 467 468 SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) { 469 EVT VT = Op.getValueType(); 470 unsigned NumElems = VT.getVectorNumElements(); 471 EVT EltVT = VT.getVectorElementType(); 472 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2); 473 EVT TmpEltVT = LHS.getValueType().getVectorElementType(); 474 DebugLoc dl = Op.getDebugLoc(); 475 SmallVector<SDValue, 8> Ops(NumElems); 476 for (unsigned i = 0; i < NumElems; ++i) { 477 SDValue LHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS, 478 DAG.getIntPtrConstant(i)); 479 SDValue RHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS, 480 DAG.getIntPtrConstant(i)); 481 Ops[i] = DAG.getNode(ISD::SETCC, dl, TLI.getSetCCResultType(TmpEltVT), 482 LHSElem, RHSElem, CC); 483 Ops[i] = DAG.getNode(ISD::SELECT, dl, EltVT, Ops[i], 484 DAG.getConstant(APInt::getAllOnesValue 485 (EltVT.getSizeInBits()), EltVT), 486 DAG.getConstant(0, EltVT)); 487 } 488 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElems); 489 } 490 491 } 492 493 bool SelectionDAG::LegalizeVectors() { 494 return VectorLegalizer(*this).Run(); 495 } 496